transfer data between 2 activities in a tab layout - android

I am implementing a fitness app. I have a tab layout for this app, the first tab shows the location(latitude, longitude), speed and other status, and the second tab shows a google map where the running route will be shown as a polyline in the map.
The first tab activity has a location manager that receive the new location.
My question is: how can I transfer the data received from the location manager in the first tab activity to the google map tab activity?
As I know, by using intent.putExtra() and startActivity() can transfer data between 2 activities, but by calling startActivity() I will just immediately go to the map activity right? But I want to update the polyline in the map and stay in the status tab.
Any hints?
Thanks in advance :)

Create One Global class and declare static varible and assign value to it and use another class.
And another way
Intent i =new Intent()setClass(this, ListViewerIncompleted.class);
i.putStringArrayListExtra(name, value);

Ok i solved this with that code:
in my Login Activity(1st Activity) i need to pass username and Password strings:
btnLogin.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String userName = txtUsername.getText().toString();
String password = txtPass.getText().toString();
//instance for UserFunctions.
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(userName, password);
//Check login response
try {
if(json.getString(KEY_REQUESTRESULT)!= null ){
txtErrorM.setText("");
//Log.e("Passed fine:", "first if condition");
String res = json.getString(KEY_REQUESTRESULT);//Obtaining the value 0 or 1 from the KEY loginstatus from JSONObject.
if(Integer.parseInt(res) == 1){
Intent iii = new Intent("com.mariposatraining.courses.MariposaTrainingActivity");
Bundle bundle1 = new Bundle();
Bundle bundle2 = new Bundle();
bundle1.putString("UN", userName);
bundle2.putString("PW", password);
iii.putExtras(bundle1);
iii.putExtras(bundle2);
//iii.putExtra("userName", userName);
//iii.putExtra("Password", password);
startActivity(iii);
finish();
//Log.e("OBJECTOO", json.toString());
}
i send this Strings to the TAB HANDLER CLASS and then the activity that manages this information:
public class MariposaTrainingActivity extends TabActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
TabHost tabHost = getTabHost();
TabHost.TabSpec spec ; //recurse to the property tabs
Intent intent; //intent for open tabs
//created intent for open the class tab1
intent = new Intent().setClass(this, ListViewerIncompleted.class); //List 2 Incompleted
spec = tabHost.newTabSpec("ListViewerIncompleted").setIndicator("INCOMPLETED").setContent(intent);
tabHost.addTab(spec);
Bundle bundle1 = getIntent().getExtras();
String userName=bundle1.getString("UN");
Bundle bundle2 = getIntent().getExtras();
String password=bundle2.getString("PW");
Bundle bundle3 = new Bundle();
Bundle bundle4 = new Bundle();
bundle3.putString("UN", userName);
bundle4.putString("PW", password);
intent.putExtras(bundle3);
intent.putExtras(bundle4);}}
in the Class to use this info:
Bundle bundle3 = getIntent().getExtras();
String userName=bundle3.getString("UN"); //Getting the userName
Bundle bundle4 = getIntent().getExtras();
String password=bundle4.getString("PW");
Hope this give you ideas...

Use public static variables in your destination Activity to have immediate access to required values from source Activity.

Related

How do I pass gson JsonObject between fragments in the same activity

I'm refactoring my app and currently rewriting two activities as two fragments in the same activity. This was how I used to send gson JsonObject from the first activity to the second activity:
Activity1:
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("form", gson.toJson(form));
startActivity(intent);
Activity2:
intent = getIntent();
form = gson.fromJson(intent.getStringExtra("form"), JsonObject.class);
Now that I've rewritten Activity1 and Activity2 as fragments in the same activity, is there a similar approach that I can use to send and retrieve data in the fragments? I just find using intents very intuitive, but I figured fragments use a different way of communicating with one another.
Bundle args = new Bundle();
args.putString("form", gson.toJson(form));
secondFragment.setArguments(args);
and in your targeted Fragment :
getArguments().getString("form");
Hi hope i am not late on this. Using the Gson Library you can achieve this feature.
In your first fragment say Fragment A. you can parse the Gson to a new
Bundle bundle = new Bundle();
bundle.putSerializable("form", new Gson().toJson(Form));
FragmentA fragment = new FragmentA();
fragment.setArguments(bundle);
loadFragment(fragment); // TODO
Then get this in your second fragment (Fragment B) as so
private Form form;
....
....
Bundle bundle = this.getArguments();
if(bundle != null){
form = new Gson().fromJson((String) bundle.getSerializable("form"), Form.class);
// get parameters e.g form name, form id
String name = form.getName();
....
}
Hope this helps. Have fun :)

Can't retrieve intent extras

I have a main activity with a recyclerview that contains images inside imageviews. When you click on an image, a detail activity is launched.
I need to pass 2 objects to an intent and retrieve them in the detail activity, but for some reason I can't do it. When I use a debugger, I can see that both objects are saved in the intent extras.
However, when I fetch them on the other side, I can't find my arraylist extra.
Can you help me to figure out why?
This is my code:
holder.mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mActivity.isTwoPaneMode()) {
Bundle arguments = new Bundle();
arguments.putParcelable(MovieListActivity.MOVIE,movie);
arguments.putStringArrayList("TRAILERS", (ArrayList)movie.getTrailerList());
MovieDetailFragment fragment = new MovieDetailFragment();
fragment.setArguments(arguments);
mActivity.getSupportFragmentManager().beginTransaction()
.replace(R.id.movie_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, MovieDetailActivity.class);
intent.putExtra(MovieListActivity.MOVIE, movie);
intent.putStringArrayListExtra("TRAILERS", (ArrayList)movie.getTrailerList());
context.startActivity(intent);
}
}
});
On the other activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_detail);
if (savedInstanceState == null) {
Intent intent = getIntent();
ArrayList<String> trailers = intent.getStringArrayListExtra("TRAILERS");
Movie movie = intent.getParcelableExtra(MovieListActivity.MOVIE);
Bundle arguments = new Bundle();
arguments.putParcelable(MovieListActivity.MOVIE, movie);
arguments.putStringArrayList(MovieListActivity.MOVIE,
getIntent().getStringArrayListExtra("TRAILERS"));
MovieDetailFragment fragment = new MovieDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.add(R.id.movie_detail_container, fragment)
.commit();
}
}
My movie class implements parcelable correctly.
Take a look at the Android Intent docs here.
Specifically, the The name must include a package prefix, ... when using Intent#putStringArrayListExtra.
Try something like this:
intent.putStringArrayListExtra(PACKAGE_NAME + ".TRAILERS", (ArrayList)movie.getTrailerList());
where PACKAGE_NAME is equal to your application's package name.
Try fetching data from a Bundle instead of and Intent. This way you can know if data was actually passed to the activity because the Bundle will be null if nothing was passed. Also add the package name to the data String.
PACKAGE_NAME = getApplicationContext().getPackageName();
arguments.putStringArrayList(PACKAGE_NAME+"TRAILERS,(ArrayList)movie.getTrailerList());
Instead of doing:
Intent intent = getIntent();
ArrayList<String> trailers = intent.getStringArrayListExtra(PACKAGE_NAME+"TRAILERS");
do:
Bundle extras = getIntent().getExtras();
ArrayList<String> trailers;
if(extras!=null){
ArrayList<String> trailers = extras.getStringArrayList("TRAILERS");
}else{
Toast.makeToast(this, "No data was passed", Toast.LENGTH_LONG).show();
}
If the Toast shows up it means your data wasn't passed correctly.

Intent - Put and Get Extras - Android - NullPointer

I have nullpointer exception.
Function in MainActivity.
public void intentLoginUser(){
Intent aux = new Intent(MainActivity.this, LoginUserSplashScreen.class);
aux.putExtra("user", username);
aux.putStringArrayListExtra("notificationList", MainActivity.this.notificationsList);
aux.putStringArrayListExtra("friendList", MainActivity.this.friendList);
aux.putStringArrayListExtra("localizationList", MainActivity.this.localizationList);
MainActivity.this.startActivity(aux);
}
Function in another Activity, named LoginUserSplashScreen
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); // Removes title bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Removes notification bar
notificationList = getIntent().getStringArrayListExtra("notificationList");
friendList = getIntent().getStringArrayListExtra("friendList");
localizationList = getIntent().getStringArrayListExtra("localizationList");
myUsername = getIntent().getStringArrayListExtra("user");
Log.e("Erro Aqui YA?", myUsername.get(0));
setContentView(R.layout.activity_loginuser);}
What's wrong?
I have nullpointer in function onCreate, in Log.e(); ... I'm trying debugging that, but I can't.
EDIT - Nullpointer in function onCreate in line Log.e()
Because all lists are null (can't get anything from last activity).
Try
getIntent().getStringExtra("user");
instead of
getIntent().getStringArrayListExtra("user");
"user" was not ArrayList.
You have a mismatch in your put and get calls.
aux.putExtra("user", username);
myUsername = getIntent().getStringArrayListExtra("user");
Use aux.putStringArrayListExtra("user", username) with getIntent().getStringArrayListExtra("user") (assuming username is an ArrayList< String >) and use aux.putExtra("user", username) with getIntent().getStringExtra("user") (assuming username is a String).
In main activity you have assigned object with putExtra
aux.putExtra("user", username);
But in receiving point your getStringArrayListExtra
myUsername = getIntent().getStringArrayListExtra("user");
Log.e("Erro Aqui YA?", myUsername.get(0));
This is error code
aux.putExtra("user", username);
myUsername = getIntent().getStringArrayListExtra("user");
you can use bundle,this code is work for you
getIntent().getStringExtra("user");
or
Bundle bundle = new Bundle();
bundle.putString("user", username);
aux.putExtras(bundle);
getIntent().getExtras().getString("user");
I think the issue is that when you assign myUsername, you are saying that the variable with key "user" is a StringArrayList, but instead it is a String when you put it in the intent. The putExtra() method takes String types, not StringArrayLists.
My solution,
In MainActivity:
public ArrayList<String> usernameList = new ArrayList<String>();
public Queue<String> serverMessages = new LinkedList<String>();
public ArrayList<String> notificationsList = new ArrayList<String>();
public ArrayList<String> friendList = new ArrayList<String>();
public ArrayList<String> localizationList = new ArrayList<String>();
public void intentLoginUser(){
Intent aux = new Intent(MainActivity.this, LoginUserSplashScreen.class);
usernameList.add(username);
aux.putStringArrayListExtra("user", MainActivity.this.usernameList);
aux.putStringArrayListExtra("notificationList", MainActivity.this.notificationsList);
aux.putStringArrayListExtra("friendList", MainActivity.this.friendList);
aux.putStringArrayListExtra("localizationList", MainActivity.this.localizationList);
MainActivity.this.startActivity(aux);
}
In LoginUserSplashScreen
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); // Removes title bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Removes notification bar
notificationList = getIntent().getStringArrayListExtra("notificationList");
friendList = getIntent().getStringArrayListExtra("friendList");
localizationList = getIntent().getStringArrayListExtra("localizationList");
myUsername = getIntent().getStringArrayListExtra("user");
Log.e("Erro Aqui YA?", myUsername.get(0));
setContentView(R.layout.activity_loginuser);
// Start timer and launch main activity
IntentLauncher launcher = new IntentLauncher();
launcher.start();
}
And Log.e(); works and pass all data.

Why does the Intent that starts my activity not contain the extras data I put in the Intent I sent to startActivity()?

I explained this badly originally. This is my question: The Intent I send to the startActivity() method, contains a private field, mMap, which is a Map containing the strings I sent to putExtra(). When the target activity starts, a call to getIntent() returns an Intent that does not contain those values. The mMap field is null. Obviously, something in the bowels of the View hierarchy or the part of the OS that started the new activity created a new Intent to pass to it, since the object IDs are different.
But why? And why are the putData() values not carried fowrard to the new Intent?
The activity that starts the new activity extends Activity. Here's the startup code:
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case 4:
i = new Intent(this, StatList.class);
i.putExtra("Name1", "Test1");
i.putExtra("Name3", "Test2");
startActivity(i);
}
}
I've tried the key values with and without the (recommended) complete package name prefix.
In the Eclipse debugger, I have verified the values for the player names are being inserted into i.mExtras.mMap properly.
Here's the code from the startee:
public class StatList extends ListActivity {
private final StatsListAdapter statsAdapter;
public StatList() {
statsAdapter = StatsListAdapter.getInstance(this);
} // default ctor
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent i = getIntent();
final Bundle extras = i.getExtras();
< more code here >
}
When execution gets to this method, mIntent.mExtras.mMap is null, and mIntent.mExtras.mParcelledData now contains some values that don't look sensible (it was null when startActivity() was called). getIntent() returns mIntent.
I've also tried startActivityForResult(), with the same result.
From the docs and the samples I've seen online & in the sample apps, this should be easy. I've found another way to meet my immediate need, but I'd like to know if anyone can help me understand why something this simple doesn't work.
In your main Activity:
i = new Intent(this, StatList.class);
i.putExtra("Name1", "Test1");
i.putExtra("Name3", "Test2");
startActivity(i);
Then in StatList.class
Bundle extras = getIntent().getExtras();
String name1 = extras.getString("Name1");
String name3 = extras.getString("Name3");
Log.i("StatList", "Name1 = " + name1 + " && Name3 = " + name3)
Update the following two line
final Intent i = getIntent();
final Bundle extras = i.getExtras();
Replace it with
Bundle extras = getIntent().getExtras();
if(extras!= null){
String var1= extras.getString("Name1");
String var2= extras.getString("Name2");
}

getIntent.getExtras() does not return null but has no values.

Question is simple, I am not exactly new to Android but I cannot, for the life of me, retrieve the extras passed via an intent from Activity A to Activity B.
See Activity A: This is actually a ListFragment, that implements onListItemClick() to start another activity via an intent.
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("FragmentList", "Item clicked: " + id);
Intent i = new Intent(getActivity(), ExpandedTweetView.class);
twitter4j.Status status = adapter.getItem(position);
Bundle extras = new Bundle();
extras.putString(KEY_TEXT, status.getText());
extras.putString(KEY_HANDLE, status.getUser().getScreenName());
extras.putString(KEY_NAME, status.getUser().getName());
extras.putString(KEY_TIMESTAMPS, status.getCreatedAt().toString());
extras.putLong(KEY_RETWEETS, status.getRetweetCount());
i.putExtra(KEY_EXTRAS, extras);
startActivity(i);
}
This part just works, I tested it usng Log.v(TAG, "status.getText()" to make sure that the error was not coming from the Adapter passing an empty item via getItem().
Here is the code on Activity B:
public class ExpandedTweetView extends Activity {
TextView text;
TextView name;
TextView handle;
TextView createdAt;
TextView retweets;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.expanded_list_item);
Bundle extras = getIntent().getExtras();
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
text = (TextView) findViewById(R.id.h_content);
name = (TextView) findViewById(R.id.h_name);
handle = (TextView) findViewById(R.id.h_handle);
createdAt = (TextView) findViewById(R.id.h_timestamp);
retweets = (TextView) findViewById(R.id.h_retweet_count);
if(extras != null) {
text.setText(extras.getString(TimelineFragment.KEY_TEXT));
name.setText(extras.getString(TimelineFragment.KEY_NAME));
handle.setText(extras.getString(TimelineFragment.KEY_HANDLE));
createdAt.setText(extras.getString(TimelineFragment.KEY_TIMESTAMPS));
retweets.setText(String.valueOf(extras.getLong(TimelineFragment.KEY_RETWEETS)));
}
}
As you can see, I believe I am using the right code to obtain the extras, using the same code on other applications worked. Not sure why, when the ExpandedTweetView is created via an intent, ALL of the textViews are empty. See: https://www.dropbox.com/s/pso6jbyn6rpks9n/empty_activity.png
What is even MORE strange is that I had initially tried checking to see if the bundle was null by calling this:
if (extras == null) {
Log.v(TAG, "Extras are empty :(");
}
But that line was never executed, meaning the bundle is not null. I also thought that maybe the keys being used to retrieve the individual Strings from the bundle were mismatching; however, in order to remedy that I decided to create constants that could be used on both sides. As you can see on the code, both the key to set the Extra and the Key to retrieve the Extra are the same.
Any ideas as to what the heck is going on?
Bundle extras = getIntent().getExtras();
if (extras != null) {
extras = extras.getBundle("KEY_EXTRAS");
String status = extras.getString("KEY_TEXT");
}
Try adding the extra variable to intent rather than in Bundle
Ex:
i.putExtra(KEY_1, a);
i.putExtra(KEY_2, b);
i.putExtra(KEY_3, c);
Then retrieve it from other activity from intent
Ex:
getIntent().getStringExtra(KEY_1) ;
In Activity A:
Intent i = new Intent(MainActivity.this, AnotherActivity.class);
Bundle b = new Bundle();
b.putString("thisc", "my name");
i.putExtra("bundle", b);
startActivity(i);
In Activity B:
**Bundle bun = getIntent().getBundleExtra("bundle");
if (bun.containsKey("thisc")) {
Log.i("TAG", bun.getString("thisc"));
} else {
Log.i("TAG", "no thisc");
}**
Check the first line of code in Activity B, that's the main difference actually!!
//put value
Intent inatent = new Intent(this,text.class);
inatent_logo.putExtra("message","hello");
startActivity(inatent);
//get vale
String msg = getIntent().getStringExtra("message").toString();
It's Difficult to maintain intent to Bundle and Bundle to Intent if number of data you want ti share from one Activity to Other Activity.
just Simply use Intent with PuExtra() with different argument.
you can pass number of data in intent like :
Sender's Side :
Create your Intent.
Intent My_Intent = new Intent(FromClass.this,ToClass.class);
Add your value which you want to share with other activity.
My_Intent.putExtra("VAR_A",a_value);
My_Intent.putExtra("VAR_B",b_value);
My_Intent.putExtra("VAR_C",c_value);
Call your Intent.
StartActivity(My_Intent);
Receiver's Side :
Intent My_Intent = getIntent();
First_Value=My_Intent.getStringExtra("VAR_A");
Sec_Value=My_Intent.getStringExtra("VAR_B");
Thred_Value=My_Intent.getStringExtra("VAR_C");
I Think its Easy for you to Handel your data from one Activity to other .

Categories

Resources