Crash while sending data between Activities - android

So, I'm basically fooling around with some kind of login form, and trying to say a customized hello with the user name on the upcoming activity. The code compiles with no problem but the app crashes as soon as I click on the login button, the login worked successfully before I tried to implement the customized hello, so the problem has to be somewhere in the following code.
Here is where I call the activity:
Intent k = new Intent(this, MainActivity.class);
//Sends login name to activity k
k.putExtra("loginName", login.getText().toString());
//login is the EditText variable name for the login text field
startActivity(k);
Here is where I retrieve the extra data and try to use it as described:
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ProfileActivity extends Activity {
TextView helloString;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
Bundle extras = getIntent().getExtras();
//Getting the hello text string
helloString = (TextView)findViewById(R.id.textHello);
String loginName = extras.getString("loginName");
helloString.setText("¡Hello, " + loginName + "!");
}
}
It somehow avoids the crash if I put in comment these two lines:
String loginName = extras.getString("loginName");
helloString.setText("¡Hello, " + loginName + "!");
Still, I can't be sure if the problem is really there or not, I thought it could have something to do with the type of data sent from the first activity not matching with the type being retrieved on the second, but still got no clue after trying some stuff around that.
Thanks in advance.
Editing:
I actually found out that I may have something to do with the fact that I am calling to mainActivity.class while the text is being shown in an activity called profileActivity.class, the problem is, profileActivity is being shown as a tab inside the mainActivity so I don't really know how should I approach that.
Editing 2:
So I solved it finally myself, for anyone interested I just sent the data to the MainActivity.class
Intent k = new Intent(this, MainActivity.class);
//Sends login name to activity k
k.putExtra("loginName", login.getText().toString());
startActivity(k);
And, inside the Main Activity, when calling the ProfileActivity to set it up as a tab:
//Profile tab
intent = new Intent(this, ProfileActivity.class);
Bundle extras = getIntent().getExtras();
intent.putExtra("loginName", extras.getString("loginName"));
spec = mTabHost.newTabSpec("home")
.setIndicator("Home", res.getDrawable(R.drawable.profile_icon))
.setContent(intent);
mTabHost.addTab(spec);
Problem solved, thanks for the help everyone anyways.

Your intent is refering to MainACtivity.class and you are trying to fetch the extras in ProfileActivity. Try changing the MainActivity.class to ProfileActivity.class if that is what your flow is.Please cross check your activities flow.
Hope it helps.
Intent k = new Intent(this, ProfileActivity.class);
//Sends login name to activity k
k.putExtra("loginName", login.getText().toString());
//login is the EditText variable name for the login text field
startActivity(k);

Since you stated that you want the data sent to ProfileActivity but need to open MainActivity, you can follow one of the 4 approaches.
NOTE: you should be checking when you use getExtra, that the returned value isn't null, and deal with it accordingly.
send the data first to the MainActivity, and then when you launch ProfileActivity from MainActivity, send the data that was previously passed in.
Put the data in a public static field in ProfileActivity. Public static variables can lead to issues, so I would recommend against this.
Save the data to a sharedPreferences file and read it when you need it in ProfileActivity.
SubClass Application, and you can set / access many variables there. The below was copied from Are static fields in Activity classes guaranteed to outlive a create/destroy cycle?:
public class MyApplication extends Application{
private String thing = null;
public String getThing(){
return thing;
}
public void setThing( String thing ){
this.thing = thing;
}
}
public class MyActivity extends Activity {
private MyApplication app;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = ((MyApplication)getApplication());
String thing = app.getThing();
}
}

On MainActivity:
String user = this.getIntent().getStringExtra("loginName");
And when you create the tabhost on MainActivity pass the string the same way:
Intent intent = new Intent().setClass(this, ProfileActivity.class);
intent.putExtra("loginName", user);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = mTabHost.newTabSpec("profile").setIndicator("Profile").setContent(intent);
mTabHost.addTab(spec);
Something like this.
But if you need the user name across the entire application use a Helper Class to store the user name.

Related

how to link a new activity in android studio using a clickable text

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.

Passing data from two activities to a third activity in android

have total 3 activites. I pass the data from the first activity like this:
Intent intent = new Intent(getActivity(), Movie_rev_fulldis_activity.class);
intent.putExtra("mov_pos", position + "");
startActivity(intent);
this working fine all data visible to my second activity but i want to display
one filed item to third activity when i click second activity image
here my second activity
youtube_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent youtube= new Intent(getApplicationContext(),PlayYouTube1st.class);
youtube.putExtra("youtubeLink",youtubeLink);
startActivity(youtube);
// Toast.makeText(Movie_rev_fulldis_activity.this,
// youtubeLink, Toast.LENGTH_LONG).show();
}
});
youtubeLink=Reviews_update.revData.get(mov_pos).getYoutubeLink();
Toast.makeText(Movie_rev_fulldis_activity.this,
Reviews_update.revData.get(mov_pos).getYoutubeLink(), Toast.LENGTH_LONG).show();
mov_pos=Integer.parseInt((getIntent().getExtras()).getString("mov_pos"));
in second activity i am getting values but when i send one filed to third activity that value passing null any one please help me i stuck in their,
I want to show YoutubeLink field sencnd activity to third activity how to parse that any one please help
In FastActivity:
Intent in = new Intent(FastActivity.this, SecondActivity.class);
in.putExtra("a", yourdata);
startActivity(in);
In SecondActivity:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String a = extras.getString("a");
}
You can also use any static variable and use it in any class
static int a = 5;
And in any other class
int b = classname.a;
classname is the class where static variable is declared.
Make that variable static and then pass
Your variable object reference get change in the THIRD Activity so, it returns null

Pass parameters without open activity

I am novice programming on Android. I have one question, I have 2 activities. Firs I pass a parameter from the Activity A to the B like this:
Intent intent = new Intent(getBaseContext(), ActivityB.class);
intent.putExtra("ALMACEN_ANTES", almacen.getText().toString());
startActivity(intent);
And now in the activity B y get the extras. Later since the Activity B, I pass parameters to the A too.
My question is, is it possible to pass parameters to another activity without doing
Intent intent = new Intent(getBaseContext(), ActivityB.class) because I don´t want to open 2 times the same activity.
Thank you!
Yes . You can save the value using SharedPreferences
It will be stored in an internal xml file and you can save it and retrive whenever you want. It need not start the activity when value passing.
An example shows below
SharedPreferences sharedpreferences;
Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.commit;
you can retrive this value from the activity where you need to access these values. It can be done by:
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String name=sharedpreferences.getString("Name","");
String ph=sharedpreferences.getString("Phone","");
You want to update a value in the activity A , you mean? because if you don't open it why sending a value to it ?
you can share data between two activities by other ways. In your case the best one would be a Singleton class:
you create a class which is inheriting from Application and containing your data, and from every activity you can update you data or get it...
Your singleton class:
import android.app.Application;
public class MyApplication extends Application {
private String data;
public String getData() {return data;}
public void setData(String data) {this.data = data;}
}
From activity B , you can set your data:
MyApplication app = (MyApplication) getApplicationContext();
app.setData(someData);
And teh Ativity A can have them like this:
MyApplication app = (MyApplication) getApplicationContext();
String data = app.getData();
See this answer

Send a variable between classes through the Intent

I'm getting problems using the Intent for navigate through the screens. I want to send a variable and use it in the other class.
I'm using a method, the method takes the variable but i don't know how to send it with the intent to the new screen, which will use it to do some things.
Main class calls the metod:
private void pantallaDetalles(final int identificador)
{
startActivityForResult(new Intent(this,MostrarDetalles.class),REQST_CODE);
}
MostrarDetalles.class is the *.java which will take the variable. I'm begining it like this:
public class MostrarDetalles extends Activity {
SQLiteDatabase db;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.detalles);
//more code...
Cursor c = db.rawQuery("SELECT * FROM table WHERE _id="+ identificador, null);
}
Did you see? I'm talking about this. I don't know how to send the "identificador" variable from the main class to the second class through the Intent.
Can you help me with this? Thank you very much in advice.
JMasia.
Use the extras bundle in the intent.
Intent i = new Intent(...);
i.putExtra("name_of_extra", myObject);
Then on onCreate:
getIntent.getIntExtra("name_of_extra", -1);
Screen 1:
Intent i=new Intent("com.suatatan.app.Result");
i.putExtra("VAR_RESULT", "Added !");
startActivity(i);
Screen 2: (Receiver):
TextView tv_sonuc = (TextView) findViewById(R.id.tv_sonuc);
Bundle bundle = getIntent().getExtras();
String var_from_prev_intent = bundle.getString("VAR_RESULT");
tv_sonuc.setText(var_from_prev_intent);
You can use Intent.putExtra() to bundle the data you want to send with the intent.

Android: problem in getText method of EditText

In my project I have two activities or classes. In first activity I have a EditText and I want to get the text of it from second class.
In the first class I wrote this code but it seems has problem.
public String getTextMessage()
{
return textMessage.getText().toString();
}
because in second class when I want to get it, program crashes.
message = encode.getTextMessage();
What is your suggestion?
As told by sunil you have to firstly get string from edittextbox and through intent send it to another second activity. After start of second activity you have to get text from bundle.
code snippet is given below...
Activity A
Intent i = new Intent(this, Second.class);
i.putExtra("EXTRATEXT", editText.gettext().toString());
startActivity(i);
Activity B
Class Second extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String text = getIntent().getExtras().getString("EXTRATEXT");
}
Access the text by getText() from edit text and store it in an string. when you move to second activity sent string variable to second class via bundel. Extract the bundel in second class and use it.
You have to pass the value through intents

Categories

Resources