I need to start one Activity (say WriteAtivity), twice, but in different mode.
In MainActivity what happens.
For example:
addNote.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent writeAct = new Intent(MainActivity.this, WriteActivity
// HERE, I DO NOT NEED OF putExtra()
startActivity(writeAct);
}
});
and
editNote.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent visualizza = new Intent(MainActivity.this, WriteActivity.class);
// HERE INSTEAD I HAVE NEED OF putExtra()
visualizza.putExtra("posizione", position);
startActivity(visualizza);
}
});
and in onCreate() of WriteActivity
intent = getIntent().getExtras().getInt("posizione");
rifTitleNote.setText(listNote.get(posizione).getTitle());
As you can see, in one i do not need putExtra() and in second I do.
I do this because I use the WriteActivity, at first, for write a note, and then, for edit the note.
This, in any case causes IndexOutOfBoundsException: Invalid index 0, size is 0
Do you know how I can overcome this problem?
Or give me advice on how to do this?
Thanks! :D
Just use getIntExtra() with a default value, and make sure that the value is not set to the default value before using it.
Intent intent = this.getIntent();
int posizione = intent.getIntExtra("posizione", -1);
if (posizione != -1){
rifTitleNote.setText(listNote.get(posizione).getTitle());
}
Check for the existence of the extra and handle accordingly if it exists or not. See Android's Intent documentation for hasExtra.
if (getIntent().hasExtra("posizione")) {
// Do stuff with extra
}
You could also set an action on the Intent that indicates how the Activity should handle the incoming intent. This is probably the "better" approach but might be overkill depending on your project.
Related
this is my first question being asked on stackoverflow. My question is regarding variable use across different recyclable intents.
e is declared like this.
final Bundle e=getIntent().getExtras();
Here i am creating new intents for different setOnClickListener() and passing a different variable for each intent.
Intent info = new Intent(EItemListView.this, ItemInfo.class);
Bundle extras = new Bundle();
int[] a=new int[listview.getAdapter().getCount()];
if (i == 0) {
extras.putIntArray("img", n5x_images);
extras.putString("info", n5x_info);
extras.putInt("pc",a[0]);
} else if (i == 1) {
extras.putIntArray("img", op3_images);
extras.putString("info", op3_info);
extras.putInt("pc",a[1]);
}
info.putExtras(extras);
startActivity(info);
Now this is the OnClickListener() where i am trying to update the variables which i passed through the intent extras, but am unable to update those variables.
addtc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int c=e.getInt("pc");
c=c+1;
Log.i("Log","value "+c);
}
The log message which i get from the above method is always 1, i think the variable in c is always set to 0 and then increments by 1 and hence the log message shows 1.
I need the variables a[0],a[1],a[2], etc to pertain its increment operation.
To make it more clear, this is the java file i am using. The error is in the OnClickListener of addtc button at the bottom of this code.
public class ItemInfo extends AppCompatActivity {
private ViewAnimator viewanimator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_info);
Button next=(Button)findViewById(R.id.bnext);
Button prev=(Button)findViewById(R.id.bprev);
viewanimator=(ViewAnimator)findViewById(R.id.viewAnimator);
TextView info=(TextView)findViewById(R.id.item_info);
Button addtc=(Button)findViewById(R.id.badd);
Button test=(Button)findViewById(R.id.button);
Bundle e=getIntent().getExtras();
int img[]=e.getIntArray("img");
for(int i=0;i<img.length;i++)
{
ImageView imgview = new ImageView(getApplicationContext());
imgview.setImageResource(img[i]);
viewanimator.addView(imgview);
}
info.setText(e.getString("info"));
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewanimator.showNext();
}
});
prev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewanimator.showPrevious();
}
});
addtc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int c=e.getInt("pc");
c=c++;
Log.i("Log","value "+c);
}
});
}
}
Thanks in advance!!!
Your approach is wrong. You cannot do this in this way. Your understanding of what an "extra" in an Intent is incorrect.
When you do this:
extras.putInt("pc",a[1]);
This adds an "extra" to the extras Bundle. The Bundle is simply a key/value pair map and you have added an entry that contains the key "pc" and the value is whatever a[1] is. It puts a copy of the value of a[1] into the Bundle, it does not put a reference to a[1] in the Bundle.
Therefore, if a[1] is 5 when you add it to the extras Bundle, a[1] will always be 5 and will never be changed to anything else.
You can't do this in this way.
Alternative: Depending on your application architecture and what you are trying to do, you can use one of the following methods:
1) Use startActivityForResult(), pass the data from one Activity to another, have the second Activity update the data and put it back into the Intent which is then returned to the "calling" Activity by using setResult().
2) Use a static variable (basically a "global" variable) to contain the data. Both activities can then access the data directly (you don't need to put the data in the Intent.
3) Put the data in a database. Both activities can then read/write from/to the database.
First advice I can give you is debugging and posting debug result. for example, are you sure that a[0] and a[1] aren't 0?
Assuming they are not, why are you declaring the bundle as final? referring to this probably final is not what you were looking for. Try removing it or replacing with private
Another suggestion is more for readable purpose, replace c = c+1; with c++; but this doesn't change the result, it just make it more linear and easier for reading.
Now after this fix (the final keyword one) tell me if something changed please :)
Please how do I link a new activity from my main activity using a clickable text. I have set the text to clickable from my main.xml but I don't know how to call the new activity from my MainActivity.java class. I know I have to use this code "textView.setOnClickListener(new View.OnClickListener());" I found in a similar question, but I don't know how and where to place it on my MainActivity.java class so that it calls a the next activity I named display
Check out Intent. You use these to start new activities or services within your application.
You're correct in that you have to assign an OnClickListener interface to your text, after you made it clickable. In the interface's onClick() method you would need to do something like this.
For example:
#Override
public void onClick(View v) {
// Create the intent which will start your new activity.
Intent newActivityIntent = new Intent(MainActivity.this, NewActivity.class);
// Pass any info you need in the next activity in your
// intent object.
newActivityIntent.putExtra("aString", "some_string_value");
newActivityIntent.putExtra("anInteger", some_integer_value);
// Start the new activity.
startActivity(newActivityIntent);
}
In the next activity, you can retrieve the intent used to start it, so that you'll have access to the data you passed from the first activity, like so:
#Override
public void onCreate(Bundle savedInstanceState) {
// Get the intent that started this activity.
Intent startingIntent = getIntent();
// Retrieve the values.
String aString = startingIntent.getStringExtra("aString");
Integer anInteger = startingIntent.getIntExtra("anInteger", 0); // 2nd param is the default value, should "anInteger" not exist in the bundle.
// Use the values to your hearts content.
}
Hope that helps.
I have an Activity that uses the following code to retrieve information from another activity:
Bundle extras = getIntent().getExtras();
if (extras != null) {
int tok = extras.getInt("Token");
tempToken += tok;
}
This is the Code inside the first other class that sends this information:
final Button mainMen = (Button) findViewById(R.id.toMainMenu);
mainMen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
Menu.class);
i.putExtra("Token", tok + teTok);
startActivity(i);
}
});
Now i have another Activity that also wants to sen information to the Main Activity like so:
maMenu.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Campaign.this, Menu.class);
intent.putExtra("Token", player.tokens);
intent.putExtra("Round", player.round);
intent.putExtra("Rank", player.rank);
intent.putExtra("Score", player.score);
intent.putExtra("Sec", player.secondsTapped);
intent.putExtra("Min", player.minutesTapped);
intent.putExtra("Hour", player.hoursTapped);
intent.putExtra("Day", player.daysTapped);
intent.putExtra("LifeTap", player.tapsInLife);
intent.putExtra("SecTap", player.tapsPerSec);
intent.putExtra("TapRo", player.tapps);
startActivity(intent);
}
});
Now my question is, how do i handle these different extras from multiple Activities inside the one Main Activity?
Thank You for your time :)
There are two ways to solve your problem..
1)
You can pass one boolean value to or and int variable with some value.. And retrieve this in your new Activity and check with boolean value or int value and get correct data correspond to Activity.
2) You can save your all Data in Shared Preference. And get your all Data in any Activity.
you can send one boolean value that data is in first class or second class and in MainActivity check the value and get the correct data
am trying to send a variable from one activity to another i have set up an intent to send to the second activity. what i want to know is in the second activity what do i need to do in order to be able to use that variable in an if statement?
heres my code
Intent mainIntent = new Intent(TheLeagueActivity.this,IntroActivity.class);
mainIntent.putExtra("leagueCount", leagueCount);
TheLeagueActivity.this.startActivity(mainIntent);
TheLeagueActivity.this.finish();
String strExtra = getIntent().getExtras().getString("leagueCount");
...that's it! ;)
(Depending on what dataType u put in, u have to use "getInt()" or sth..)
in onCreate() method of IntroActivity write the following code
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = getIntent();
// -1 is default value if no value associated with key "leagueCount"
int leagueCount = intent.getIntExtra("leagueCount", -1);
/*
if leagueCount is not equal to -1
use leagueCount here
*/
}
In the target activty, call getIntent to retrieve the intent, then use getStringExtra, getIntExtra, etc. to retrieve the intent parameters.
Depends what is your variable.
It seems to be an int.
So you will call like this:
int myVar = getIntent().getExtras().getInt("leagueCount");
if (myVar == 2) {
//do the stuff
}
I'm stuck in one problem from yesterday and I can't find a solution. I'm trying to set one variable in a child activity in my tabhost to 0. Basically I have this situation :
Activity A -- sends extra "something" to activity B (B is getting it)
Activity B -- starts Activity C
Activity C -- onButton click sends extra "something" to activity B and finish()
This all happens in First tab.
The problem is when I change the tab and return back to Activity A, than B, that extra "something" is still saving the value which Activity C sends, no matter if I send it from Activity A. Here is an example code :
Activity A -- starts B :
if (ownedCards != 0) {
ownedStampii.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent previewMessage = new Intent(getParent(), OwnedStampii.class);
TabGroupActivity parentActivity = (TabGroupActivity)getParent();
previewMessage.putExtra("collection_id", collId);
previewMessage.putExtra("SOMETHING", 0); // this is what I'm trying to se to 0
parentActivity.startChildActivity("OwnedStampii", previewMessage);
}
});
}
This is how I read extra in Activity B :
final int extra = getParent().getIntent().getIntExtra("SOMETHING", 0);
Log.e("", "extra : " + extra);
This is how I send extra from Activity C :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getParent().getIntent();
intent.putExtra("SOMETHING", objectID); // objectId of category which will sort the data
getParent().setResult(RESULT_OK, intent);
finish();
}
});
I tried to set int extra =0 on onResume(), onRestart(), onStop().. and etc. it's still not working.
Any suggestions how can I set this variable to 0?
I think you are reusing an existing intent in activity C and putting another SOMETHING into the same intent. Try calling intent.removeExtra("SOMETHING"); before putting it in again. Or send a new Intent from C to B.
Intent intent = getParent().getIntent();
intent.removeExtra("SOMETHING"); // Hox! Add this.
intent.putExtra("SOMETHING", objectID);
getParent().setResult(RESULT_OK, intent);
finish();
You should pass data between Activities through Intent and startActivityResult() and onActivityResult();
This may be tricky while using TabGroupActivity.
Here is a solution which I posted to another question having somehow same scanario.
You are declaring extra as a final variable which means once you create and assign it to something you cant change it afterwards.
So when you are trying to reassign and change the value it's basically not possible cause your variable is final.