Pass Value from First Activity to Third Activity via AsyncTask - android

I have an Online Ordering System from where users can complete the order in, at least, three steps. Each step below is a separate activity:
Make selection of a Plan
Select the Starting Date
Select Contents based on selected Plan in Step 1.
Now what I have done in step 1 is, once user clicks on a Plan and Order, below code runs onClick.
Intent intent = new Intent(context, SelectDate.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle extras = new Bundle();
extras.putString("pass_selected_meal_plan_id",mp_id_pass);
extras.putString("pass_selected_meal_name",mp_name_display);
intent.putExtras(extras);
context.startActivity(intent);
Toast.makeText(context, mp_name_display+" Selected",
Toast.LENGTH_SHORT).show();
No in the second Activity, I am asking the user to select the order starting date. That is also simple enough and have no issues in it. But the issue begins when I am trying to switch to the third activity.
Since my third activity content is depending on the Plan selection made in the first activity, therefore I have to transfer the selected ID to the third activity. I have it in Extra Bundle in second activity as "pass_selected_meal_plan_id".
The way I am loading the third activity is also crucial. There are two possible ways to start the third activity. First is very simple by putting onClick on the next button. I assume that it will be very simple to transfer the required selection as well. But in this case, as far as I know being a beginner in Android App Development, I will have to give a button to click and load content based on the selected Plan.
The second way is what I want to use. I am running an AsyncTask in the second activity onClick Next. It is working perfectly fine. The only this is I am unable to getExtras in onPostExecute from the previous Activity, i.e. first activity.
I am open to even using Global Variables, but don't really know how to do. Knowing what Global Variables are, I am not too keen to use them instead.
Here is my onPostExecute code:
#Override
protected void onPostExecute(String result) {
Intent intent = new Intent(ctx, SelectMeals.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle extras = new Bundle();
//Instead of "1" I want the value from previous Activity, which already available in Extras from previous Activity
extras.putString("pass_selected_meal_plan_id", "1");
//This is the second value I want to be transferred from first activity to the third activity
extras.putString("pass_selected_meal_name","Test");
intent.putExtras(extras);
ctx.startActivity(intent);
}
Would really appreciate if anyone can help.

You can use below code
In your second activity
// declare global variables
String id;
String name;
Use below code inside onCreate
Bundle bundle = getIntent().getExtras();
//Extract the data…
id = bundle.getString("pass_selected_meal_plan_id");
name = bundle.getString("pass_selected_meal_name");
Now in your Asynctask, write the code below before launching 3rd activity.
#Override
protected void onPostExecute(String result) {
Intent intent = new Intent(ctx, SelectMeals.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle extras = new Bundle();
extras.putString("pass_selected_meal_plan_id",id); // first activity data
extras.putString("pass_selected_meal_name",name); // first activity data
intent.putExtras(extras);
ctx.startActivity(intent);
}
Finally, you can get these values in third activity.
One important point I would like to highlight is that avoid using generic variable names, e.g. id. It is used just for reference in this answer but it is not a good idea. One obvious problem you may face doing so is with Refactor > Rename. It will change even the #+id in XML files.

Related

Android activity getting old values in bundle

In my android activity B, I read values bundled in the intent like this
Bundle bundle = getIntent().getExtras();
Boolean mine = bundle.getString("mine").equals("1");
int pagenum = bundle.getInt("page");
When I start B from another activity A, I give in mine=0,pagenum=0.
And I can read that fine in B.
But then in B, I want to reload the activity, by finishing itself and opening another B. I also need to pass in the new data like this:
private void refresh(Boolean mine, int newpage) {
finish();
Intent myIntent = new Intent(this, AllThreadsScreen.class);
myIntent.putExtra("mine", mine ? "1" : "0");
myIntent.putExtra("page", Integer.toString(newpage, 10));
startActivity(myIntent);
}
When I call this, I make sure that newpage has a value of 1. However the problem is that, after starting the activity, when I read the page value from the bundle, it becomes 0 again...
Does anyone know whats wrong?
Thanks.
You are not "restarting" the Activity. If you call finish() and the lines after still work, then it ins't really finished, is it?
What is happening is the Activity may begin the process of finishing, but then receives a new Intent. Android doesn't actually destroy it.
Also, you don't need to finish the Activity anyway. just use onNewIntent (a little known, little used Activity method).
How to capture the new Intent in onNewIntent()?

How to show different text in the same activity? eclipse

I am making an app in which, dialog pops up and user selects an option. based on this option, next activity opens up in which there is some text. There are lots of options for the user to choose from in the dialog. Every option is intended to have the same layout just the text is different. Do I need to make these many new activities or can I somehow change the string based on user's choice by adding some conditionals somewhere? Please help
You need not create separate activity for each user input, as the layout is same. You can achieve this by using a TextView and changing its text according to user input like this:
TextView textView = (TextView) findViewById(R.id.<YourTextViewID>);
textView.setText("SetTextAccordingToUserInput");
One Activity is sufficient. Set the text on selection event in dialogue.
You can use only one Activity with content and create this activity with parameter depend on user selection in dialog.
To open activity with parameter:
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
Bundle b = new Bundle();
b.putInt("yourParameter", 1);
intent.putExtras(b);
startActivity(intent);
Then to use it in your SecondActivity.class onCreate method
onCreate(Bundle instance)
{
// some stuff like setting layout ant etc.
Bundle b = getIntent().getExtras();
int value = b.getInt("yourParameter");
}

Refresh activity and re-open

This is my first post, so please be nice :)
I have a question and no one gave the answer in the post I've seen.
My app has a list and a button to open an activity, this activity creates a new item to show in the list of the previous activity when pressing the button Create.
How can I do this?
This is the code I made for the first button:
intent = new Intent(this.getBaseContext(), NewTestActivity.class);
this.finish();
startActivity(intent);
and this is the code to go back an refresh:
Intent intent = new Intent(getBaseContext(), TestListActivity.class);
startActivity(intent);
But the code to goback is useful, because the activity don't refresh.
I have to call the new activity in a diferent way? Or go back to previus activity in a diferent way? Or go back normally and refresh the activity when I'm back in the previus activity?
Well...this is all.
Sorry for my bad english and, if this question has been answered in another thread, give me the link to read, because I can't find it :)
PS: I started with android in December.
Thanks for your help.
When you are going to start new activity you shouldn't close a current one until you actually need this behaviour. (remove this.finish(); row from your code)
Also you shouldn't close an active activity manually until you actually need it. When the user presses the "back" button on the device Android pops the previous activity from the "back stack". Read once more Activity documentation.
According to your description you have a list of elements. So in order to refresh the list you need to update your dataset and notify the list about it by ListView.notifyDataSetChanged() method call.
Before getting to a real answer, I'd like to show some improvements to your code.
First, when creating an Intent (or when you need a context in general) from an Activity there is no need to call getBaseContext(), you can just use this:
intent = new Intent(this, NewTestActivity.class);
Second, android is good at handling Activities, you do not have to close your first activity manually with finish(). Android will automatically pause or stop your first activity and bring it back when you return to it.
Third, in your case you might want to use startActivityForResult() instead of startActivity() for reasons I will explain below.
This will make your code look like the following:
private static final int MY_REQUEST_CODE = 33487689; //put this at the top of your Activity-class, with any unique value.
intent = new Intent(this, NewTestActivity.class);
startActivityForResult(intent, MY_REQUEST_CODE);
Now, the startActivityForResult() starts an activity and waits for a result from that new Activity. When you call finsih() in the new Activity you will end up in the first Activitys onActivityResult()-method, with data supplied from the new Activty that is now closed:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode != MY_REQUEST_CODE) return; //We got a result from another request, so for this example we can return.
if(resultCode != RESULT_OK) return; //The user aborted the action, so we won't get any data.
//After the above if-statements we know that the activity that gives us a result was requested with the correct request code, and it's action was successful, we can begin extracting the data, which is in the data-intent:
Item item = (Item) data.getSerializableExtra("customData"); //casts the data object to the custom Item-class. This can be any class, as long as it is serializable. There are many other kinds of data that can be put into an intent, but for this example a serializable was used.
itemList.add(item); //This is the list that was specified in onCreate()
//If you use an Adapter, this is the place to call notifyDataSetChanged();
}
For this all to work, we need to do some things in the second Activity:
When the item has been created, we must set a result:
//We begin by packing our item in an Intent (the Item class is an example that is expected to implement Serializable)
Item theCreatedItem; //This is what was created in the activity
Intent data = new Intent();
data.putSerializable(theCreatedItem);
setResult(RESULT_OK, data);
finish();
This should return to the first Activitys onActivityResult()-method with the item, as explained above.

I want to make use two variables in next Activity but thread make it null

Here in my application I want to use 2 variables which I want to use in another activity. But in first activity I make thread for progress dialog bar but in thread I call one xml and get data from web service but thease two variables make null after end of thread. So please help me.
You need to add them to the Intent that is calling the 2nd activity and then read them back:
e.g. for writing:
Intent i = new Intent(this, NewTweetActivity.class);
i.putExtra("op", "I want to transport this");
startActivity(i);
and for reading back:
Bundle bundle = getIntent().getExtras();
if (bundle!=null) {
String op = bundle.getString("op");

android switchstatement question

I was wondering, how would I make a switch statement, that when that certain case was triggered, it would open a new screen with text. Would I use an intent? And if so, which one?
Thank you for your help in advance.
When you want to open a "new screen", you probably want to open a new activity. You would create a second Activity-derived class and use the following overload of the Intent constructor with startActivity:
Intent intent = new Intent(this, MySecondActivity.class);
startActivity(intent);
this will explicitly attempt to open a new Activity with the class name MySecondActivity
to pass a String of text from one Activity to another in this way, you can add it to the intent.
String someValue = "Some Value";
intent.putExtra("Some Key", someValue);
and in the code of your other Activity, you can get at this string via the Intent
getIntent().getStringExtra("Some Key");
Obviously you want to do null checks to make sure the key exists in the Intent, and you want to put a proper constant String somewhere instead of using a literal String for a key, but this is the basic gist.
Kriem... As Rich said you can launch a new activity using intents and push data to the new activity using extras. You can push data back to your main activity using startActivityForResult instead of startActivity. You can return to your main screen by calling finish() in the new screen. Finally, you can put the new screen event handlers into the NewScreen.java file.
The overall effect is a near full separation from dependency between the two activities, so that you might be able to easily re-use the NewScreen.java class in another project. I have some code here.

Categories

Resources