I need help converting a string to an integer - android-studio

Good day,
I have an array adapter in Activity1 in my AndroidStudio project. I would like to transfer two specific items from the ArrayAdapter (in positions 1 and 2) to Activity2 with an intent. (the ArrayAdapter is connected to an editTextNumber) That works well if I then display the two items in a TextView. But if I want to convert the items to an int, the app always crashes. I can somehow just convert "message1" into an int. Why is that so?
Thank you for your help
(Activity 1):
[...]
#Override
protected void onCreate(Bundle savedInstanceState) {
ArrayAdapter adapterzeit = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, zeit1);
Intent intent = new Intent(this, Activity2.class);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent.putExtra("EXTRA_MESSAGE1", adapterzeit.getItem(1).toString());
intent.putExtra("EXTRA_MESSAGE2", adapterzeit.getItem(3).toString());
startActivity(intent);
}
});
}
(Activity 2):
[...]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
Intent intent = getIntent();
String message1 = intent.getStringExtra("EXTRA_MESSAGE1");
String message2 = intent.getStringExtra("EXTRA_MESSAGE2");
int numberInt = Integer.parseInt(message1);
int number2 = Integer.parseInt(message2);
}
}

You add the extra to the Intent like this:
intent.putExtra("EXTRA_MESSAGE1", adapterzeit.getItem(1).toString());
and then you try to extract it from the Intent like this:
String message1 = intent.getStringExtra("EXTRA_MESSAGE");
You are using different String values for the keys! EXTRA_MESSAGE != EXTRA_MESSAGE1
This is one reason why you should always use constant definitions for these kinds of things, then you wouldn't have this problem. For example, in Activity1:
public static final String EXTRA_MESSAGE1 = "EXTRA_MESSAGE1";
intent.putExtra(EXTRA_MESSAGE1, adapterzeit.getItem(1).toString());
and then in Activity2:
String message1 = intent.getStringExtra(Activity1.EXTRA_MESSAGE1);

Related

How to add numbers together using and If statement?

I'm trying to make a program in android studio that when sellected a higher education it automatically adds 200$ to the pay that was previously entered. But instead of getting 500+200=700, I get 500200. I ran trough the code numerous times and just can't seem to find the error. I'm still new on Java. This is the second window that appears when submitting the information, It shows all the info entered in the first window, but for some reason it can't 200 to the entered pay
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rezultatas);
Intent duom = getIntent();
String pavarde = duom.getStringExtra("pavarde");
String issilavinimas = duom.getStringExtra("issilavinimas");
int pay = duom.getIntExtra("atlyginimas", 0);
String laikas = duom.getStringExtra("laikas");
TextView rez = findViewById(R.id.rezultatas);
rez.setText("Pavardė: "+pavarde+"\n");
rez.append("Išsilavinimas: "+issilavinimas+"\n");
if(issilavinimas.equals("Aukštasis")){
rez.append("Gaunamas atlyginimas: " +pay+ 200 + "\n");
} else{
rez.append("Gaunamas atlyginimas: "+pay+ "\n");
}
rez.append("Keliasi: "+laikas+"\n");
}
This is the first window where all the information is entered:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void saugoti(View v){
EditText txt = findViewById(R.id.lastName);
String pavarde = txt.getText().toString();
Spinner issilavinimas = findViewById(R.id.issilavinimas);
String issilav = issilavinimas.getSelectedItem().toString();
EditText atl = findViewById(R.id.pay);
int pay = Integer.parseInt(atl.getText().toString());
TextView txt2 = findViewById(R.id.time);
String laikas = txt2.getText().toString();
Intent duom = new Intent(this, rezultatas.class);
duom.putExtra("pavarde", pavarde);
duom.putExtra("issilavinimas", issilav);
duom.putExtra("laikas", laikas);
duom.putExtra("atlyginimas", pay);
startActivity(duom);
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
Try this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rezultatas);
Intent duom = getIntent();
String pavarde = duom.getStringExtra("pavarde");
String issilavinimas = duom.getStringExtra("issilavinimas");
int pay = duom.getIntExtra("atlyginimas", 0);
int total=pay+ 200;
String laikas = duom.getStringExtra("laikas");
TextView rez = findViewById(R.id.rezultatas);
rez.setText("Pavardė: "+pavarde+"\n");
rez.append("Išsilavinimas: "+issilavinimas+"\n");
if(issilavinimas.equals("Aukštasis")){
rez.append("Gaunamas atlyginimas: " + total + "\n");
} else{
rez.append("Gaunamas atlyginimas: "+pay+ "\n");
}
rez.append("Keliasi: "+laikas+"\n");
}
when you + with String concatination is actually working there instead of addition

Why isn't my ImageView link displaying via Intent?

I'm loading an Image into an ImageView using a link, and I'm trying to pass this link from one activity to display on another activity by an Intent. However, the Image just seems to come up blank.
Below I have listed the code associated with the two activities, as well as the adapter of the RecyclerView that the information is being passed from in the first activity
ActivityOne.java
private ArrayList<String> mImageUrls = new ArrayList<>();
...
mImageUrls.add("https://data.oireachtas.ie/ie/oireachtas/member/id/Se%C3%A1n-Haughey.S.1987-04-25/image/large");
...
#Override
public void onNoteClick(int position) {
Intent intent = new Intent(this, ActivityTwo.class);
intent.putExtra("EXTRA_KEY_NAME", mNames.get(position));
intent.putExtra("EXTRA_KEY_IMAGE", mImageUrls.get(position));
startActivity(intent);
}
ActivityTwo.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_members_map_detailed);
tvMemberName = findViewById(R.id.tvClareMemberNameDetailed);
tvMemberParty = findViewById(R.id.tvClareMemberPartyDetailed);
tvMemberConstituency = findViewById(R.id.tvClareMemberConstituencyDetailed);
tvMemberAddress = findViewById(R.id.tvClareMemberAddressDetailed);
tvMemberEmail = findViewById(R.id.tvClareMemberEmailDetailed);
tvMemberPhone = findViewById(R.id.tvClareMemberPhoneDetailed);
tvMemberContributions = findViewById(R.id.tvClareMemberContributionsDetailed);
imgMember = findViewById(R.id.imgClareMemberImageDetailed);
Intent intent = getIntent();
String mName = intent.getStringExtra("EXTRA_KEY_NAME");
String mParty = intent.getStringExtra("EXTRA_KEY_PARTY");
String mConstituency = intent.getStringExtra("EXTRA_KEY_CONSTITUENCY");
String mAddress = intent.getStringExtra("EXTRA_KEY_ADDRESS");
Uri myUri = Uri.parse(intent.getStringExtra("EXTRA_KEY_IMAGE"));
String mEmail = intent.getStringExtra("EXTRA_KEY_EMAIL");
String mPhone = intent.getStringExtra("EXTRA_KEY_PHONE");
String mContributions = intent.getStringExtra("EXTRA_KEY_CONTRIBUTIONS");
tvMemberName.setText(mName);
tvMemberParty.setText(mParty);
tvMemberConstituency.setText(mConstituency);
tvMemberAddress.setText(mAddress);
tvMemberEmail.setText(mEmail);
tvMemberPhone.setText(mPhone);
tvMemberContributions.setText(mContributions);
imgMember.setImageURI(myUri);
Adapter information associated with Image
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Glide.with(mContext)
.asBitmap()
.load(mImageUrls.get(position))
.into(holder.image);
holder.name.setText(mNames.get(position));
holder.party.setText(mParties.get(position));

How to create when i click 1st item in arrayList1 will open page with 1st item in arrayList2

When I click first or second item from 1st array list I get first item from array list two, but I need if i click second item on array list 1 I get shown second item from list two
public class SecondActivity extends AppCompatActivity {
ListView listView;
ArrayList<String> 1stArrayList;
ArrayList<String> 2ndArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
listView = (ListView) findViewById(R.id.listView);
1stArrayList = new ArrayList<>();
1stArrayList .add("A");
1stArrayList .add("B");
1stArrayList .add("C");
2ndArrayList = new ArrayList<>();
2ndArrayList.add("1");
2ndArrayList.add("2");
2ndArrayList.add("3");
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.item, 1stArrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String 2ndArrayList= listView.getItemAtPosition(position).toString();
SharedPreferences settings = getSharedPreferences("PREFS", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("2ndArrayList ", 2ndArrayList );
editor.apply();
Intent intent = new Intent(getApplicationContext(), ThirdActivity.class);
startActivity(intent);
}
});
}
}
A possible solution would be getting the value directly from the array using the position of the view clicked. Like the following:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String secListItem = secArrayList.get(position);
SharedPreferences settings = getSharedPreferences("PREFS", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("2ndArrayList", secListItem );
editor.apply();
Intent intent = new Intent(getApplicationContext(), ThirdActivity.class);
startActivity(intent);
}
});
But you have to be sure that both the arrays will have the same size or you may have an IndexOutOfBoundsException.
Another solution would be using some Map with the values from arraylist1 and arraylist2, implementing a custom adapter that extends BaseAdapter, populating the views with the values from the first array with getView() and using getItem() to return the values from the second list, but that's harder to do.
Also if you don't mean to persist the item and only transfer them between activities, you can use the Intent to do it. In this way:
Intent intent = new Intent(getApplicationContext(), ThirdActivity.class);
Intent.putExtra("2ndArrayList", secListItem);
startActivity(intent);
And recover in the third activity with something like:
String secArrayItem = "";
Bundle extras = getIntent().getExtras();
if (extras != null) secArrayItem = extras.getString("2ndArrayList");

Android getIntent() can't find my String

I have a usual Intent from one activity to an other and give the second activity the path to the file needed.
Activity one:
private void onFileClick(int position)
{
File file =new File(folder+ "/"+ getListAdapter().getItem(position).toString());
Intent i = new Intent(this, (Activity two).class);
Log.e("Given File",file.toString());
i.putExtra(file.toString(), key);
startActivity(i);
}
Activity two:
#Override
protected void onCreate(Bundle savedInstanceState)
{
Intent i = getIntent();
String filepath = i.getStringExtra((Activity One).key); //Returns null
File parseFile = new File(filepath); //NullpointerExeption
}
Have i initialized the intent wrong?

Simple Edittext Math Android

new SO user here and I'm new to android as well. I need help doing a simple calculation between two edittext boxes - without a button, using a textwatcher, so that after the user is done using the edittext boxes it can add the two together and output the answer in a textview. I'd post my code here, but it just isn't any good. Can anyone provide an example of how to take two edittext boxes, assign a textwatcher to both, then put the output into a textview. Also, please keep in mind that this is eventually going to use multiple edittext boxes while autoupdating each other. This would be similar to creating forumulas in Microsoft excel and having them update immediately. One of the main problems I seem to have is catching the numberformatexception when just one is empty. Thank you for your time.
I implemented a simple app - I hope it helps you.
public class MainActivity extends Activity implements TextWatcher {
TextView tvResult;
EditText tvNumberOne, tvNumberTwo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvResult = (TextView)findViewById(R.id.tvResult);
tvNumberOne = (EditText)findViewById(R.id.tvNumberOne);
tvNumberTwo = (EditText)findViewById(R.id.tvNumberTwo);
tvNumberOne.addTextChangedListener(this);
tvNumberTwo.addTextChangedListener(this);
}
#Override
public void afterTextChanged(Editable s) {
int numOne = 0, numTwo = 0;
try{
numOne = Integer.valueOf(String.valueOf(tvNumberOne.getText()));
numTwo = Integer.valueOf(String.valueOf(tvNumberTwo.getText()));
}catch(Exception ex){
Toast.makeText(getApplicationContext(), "Parsing error!",Toast.LENGTH_SHORT).show();
}
tvResult.setText(String.valueOf(numOne + numTwo));
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
}

Resources