I know how to pass data from one activity to another using Intent:
Intent intent = new Intent(getBaseContext(), AddTextNote.class);
intent.putExtra("text", note.text);
I'll ask my question with example: If one activity would pass only a string to another, the second activity will know that everytime it receives intent from the first activity, it contains only a string. But if the first activity passes multiple set of data on various occations to another, what is the best way to distinguish them? I mean let's say first activity will pass an integer if user presses button1, will pass an array of customClass if user presses button2 and will pas float if user presses button3. So briefly there is 3 ways to start the second activity.
How should I know what intent contains? I can check for being null, like:
string myStringParameter = intent.GetStringExtra("myStringParameter");
But it is a not a wise and efficient way. Is there anyway to distinguish them fast and effective?
Thanks
I think that way could do the trick:
public enum State {
BUTTON_1, BUTTON_2, BUTTON_3
}
public class Activity1 extends Activity {
Intent intent = new Intent(getBaseContext(), Activity2.class);
intent.putExtra("text", note.text);
intent.putExtra("state", BUTTON_1);
}
public class Activity2 extends Activity {
State s = (State) intent.getSerializableExtra("state")
switch (s) {
case BUTTON_1:
//get String value from intent and do what needed
break;
case BUTTON_2:
//etc
break;
....
}
}
Hope you got the idea.
Data is identified via strings.
Activity A sends:
intent.putExtra("stringA", ""+BUTTON_A);
intent.putExtra("stringB", ""+BUTTON_B);
Activity B receives:
String stringAdata = getIntent().getStringExtra("stringA");
String stringBdata = getIntent().getStringExtra("stringB");
Related
I have an activity which can be accessed via different activities.
Like you have one activity containing a listview and the second containing a gridview and both shows the same data. When you click on an item a new activity with some details is shown. I need to somehow remember which activity was the initial one (with gridview or listview) so that I can set a button to redirect here. But it's not enough to just return to previous activity (like using finish() to close the current one), because there is a way to navigate among different objects from inside the details activity (I have a gridview on that screen). So I need to remember the initial view during moving through the details activity for various number of times.
Is there a way?
EDIT: omg why so many downvotes? At least tell me why it is so stupid, I'm learning coding for Android for 2 weeks how am I supposed to know everything??
This sounds like it would best be solved by using two Fragments within the same Activity
You can use a bundle object to pass data to the new activity (B) so you could know wich activity (listView or gridView) had started it.
In activity B:
private static final String ACTIVITY_TYPE = "activity_type";
public static Intent createIntent(Context context,String activityType)
{
Intent intent = new Intent(context, ActivityB.class);
Bundle b = new Bundle();
b.putString(ACTIVITY_TYPE,activityType);
intent.putExtras(b);
return intent;
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
String activityType;
if (b != null)
{
activityType = b.getString(ACTIVITY_TYPE);
}
//the calling activity didn't use the createIntent method and didn't provide the activity type
else
{
activityType = "some_default_type";
}
//save activity type to use later
//rest of your code
}
In the calling activity:
Intent intent = ActivityB.createIntent(ActivityListView.this,"activity_list_view");
startActivity(intent);
I am creating an Android app. One of the functions is to collect some data (item name, item ID and the barcode string) from the user .
Activity1 is a form. User enters the item name and item number manually. For the barcode string, user clicks on the "scan" button then Activity2 (Scanner) is started in order to scan and read the barcode. Once the barcode is read, Activity1 (the form) starts again and all data should appear on the form.
When Activity2 starts by Intent, Activity1 is killed. So, I have to get the item name and item number and store them temporarily before staring the Intent. Then when Activity1 starts again, those data will be rendered on the form again.
Now I am thinking to use Intent Extra to keep the item name and number, and pass them to Activity2 and back to Activity1. Given that Activity2 doesn't need those data, I wonder if that is the right way to do in this scenario. Is there any better way? Should I use Shared Preferences instead?
In Your first activity use put extra argument to intent like this:
// Assuming Activity2.class is second activity
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("variable_name", var); // here you are passing var to second activity
startActivity(intent);
Then in second activity retrieve argument like this:
String var2 = getIntent().getStringExtra(variable_name);
You could create a singleton class and expose setter(for saving) and getter (for retrieving) methods for the model objects (here two private string variables).This class will be alive with your application:
public class MyClass{
private static MyClass instance=null;
public static getInstance(){
if(instance==null){
instance=new MyClass();
}
return instance;
}
private String itemName;
private String itemNumber;
//setter and getter methods here
}
why need to kill the Activity 1, try to call
on Activity 1
declare private int SCAN_BARCODE_REQUEST = 101;
and then
//finish(); dont use this to destroy activity 1
startActivityForResult(new intent(this,Activity2.class), SCAN_BARCODE_REQUEST);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SCAN_BARCODE_REQUEST) {
if (resultCode == RESULT_OK) {
String barcode = data.getStringExtra("BARCODE");
//handle your barcode string here
}
}
}
on your Activity 2,
change your start Activity1 with
Intent intent = new Intent();
intent.putExtra("BARCODE", barcodeString);
setResult(RESULT_OK, intent);
finish();
You can use SharedPreferences.
You can learn how to use them here:
https://www.tutorialspoint.com/android/android_shared_preferences.htm
https://developer.android.com/training/basics/data-storage/shared-preferences.html
SharedPreferences is a really good solution for such applications. It is very simple and easy to use and implement.
I am wondering about the best way to design / program this:
If I have a Boolean value (let's say whether the user has extra power or not) and I need to pass it from Activity A to B to C. Should I add it to an intent from each activity to another OR should I just store it in a static variable and access it every time?
Its is safer to pass it in the intent. sometimes android kills apps without warning when it needs memory and your static values will not be retained on the other hand intent extras are kept. if you want to push it a little further, use shared preference. its designed using Map data struct so speed will not be a problem.
Android Intents have a putExtra method that you can use to pass variables from one activity to another.
public class ActivityA extends Activity {
...
private void startActivityB() {
Intent intent = new Intent(this, ActivityB.class);
intent.putExtra("HAS EXTRA POWER", false);
startActivity(intent);
}
}
public class ActivityB exntends Activity {
Bundle bundle;
private void hasExtraPower() {
bundle = getIntent().getExtras();
if(!bundle.getBoolean("HAS EXTRA POWER")
// do something
else
// do something else
}
}
Passing data through Intent
If you use that only in that activity that's fine but
When u need to pass to other layer like viewmodel that will make your operation's speed slower
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.
I need some help with using integer from one activity to another.
I am making some basic math program(game). It gets two random numbers, random operator, and 30 secs to solve math problems as much as you can.
If you solve problem u get 1 point.
Anyway right now, I want to get number of points that user have made and use it in another activity called *RankActivity*.
Main activity is called *BrzoRacunanjeActivity* and it contains button and one *int* called *poenibrojanje* which get number of points that user have made, and when I click on button, it opens new Activity with this line:
startActivity(new Intent(this, RankActivity.class));
As you can see another Activity is called RankActivity, and there I wrote :
*BrzoRacunanjeActivity a1 = new BrzoRacunanjeActivity();*
*System.out.println("Number of points:" + a1.poenibrojanje);;*
and I get all time this reuslt: 09-22 09:09:14.940: INFO/System.out(289): Number of points:0
Try this:
Intent intent = new Intent(this, RankActivity.class);
intent.putExtra("points", pointsVar);
startActivity(intent);
In onCreate of RankActivity:
getIntent().getIntExtra("points", 0);
so you want to pass integer value from one activity to another activity? right...
try:
Intent intent = new Intent(currentclass.this, destination.class);
intent.putExtra("point", pointvalue);
startActivity(intent);
at destination activity:
final int getpoint = getIntent().getExtras().getInt("point");
This will solve your problem.
first of all make
static variable like as public static int poenibrojanje;
in your BrzoRacunanjeActivity.class file now you can use this variable in any other class like as
BrzoRacunanjeActivity.poenibrojanje
or you can use putExtras(); method.
in you main activity.
Intent i = new Intent(this, RankActivity.class);
i.putExtra("Value",poenibrojanje);
in your next activity
int v = (getIntent().getExtras().getInt("Value")) ;