This question already has answers here:
How to pass a value from one Activity to another in Android? [duplicate]
(7 answers)
Closed 9 years ago.
i would like to send the values from one activity to another but i got null pointer
exception please solve my problem.the first activity contains sms the details of that
sms is send to second activity based on these values th esecond activity search contact
no and send reply sms.
public void onReceive( Context context, Intent intent )
{
// Get SMS map from Intent
Bundle bundle = null;
Bundle extras = intent.getExtras();
String messages = "";
String address = null,body=null;
if ( extras != null )
{
// Get received SMS array
Object[] smsExtra = (Object[]) extras.get( "pdus" );
// Get ContentResolver object for pushing encrypted SMS to incoming folder
//ContentResolver contentResolver = context.getContentResolver();
for ( int i = 0; i < smsExtra.length; ++i )
{
SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[i]);
body = sms.getMessageBody().toString();
address = sms.getOriginatingAddress();
messages += "SMS from " + address + " :\n";
messages += body + "\n";
// Here you can add any your code to work with incoming SMS
// I added encrypting of all received SMS
}
// Display SMS message
Toast.makeText( context, messages, Toast.LENGTH_SHORT ).show();
Intent i=new Intent(context,AlertActivity.class);
bundle.putString("from",address);
bundle.putString("msg",body);
i.putExtras(bundle);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
Activity2:
Intent i=getIntent();
Bundle bundle=i.getExtras();
String fromAdd=bundle.getString("from");
String msgBody=bundle.getString("body");
Change this
String msgBody=bundle.getString("body");
to
String msgBody=bundle.getString("msg");
in Android Bundle we put key value pair, and it is mandatory that you pass same key, while getting data from bundle, which you are putting data. check your code you are putting two string on intent, which are:
"from", and "msg"
and you are getting values from intent by key:
"from" and "body"
so change it either in starting activity or Activity 2. so that key values would match.
try this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bundle bundle = this.getIntent().getExtras();
if (bundle != null)
{
String fromAdd = bundle.getString("from");
String msgBody = bundle.getString("body");
}
}
Try this.....
Activity1.java
Intent intent = new Intent(getApplication(),Activity2.class);
intent.putExtra("from",from);
intent.putExtra("Body",Body);
StartActivity(intent);
Activity2.java
Intent intent = getintent();
Bundle bundle=intent.getExtras();
String Body=bundle.getString("Body");
String From=bundle.getString("From");
setResult("RESULT_OK",intent);
try with this way..
Bundle bu=getIntent().getExtras();
String title=bu.get("from").toString();
String msg=bu.get("body").toString();
Try this..... to pass value from Activity1 to Activity2.
Intent myIntent = new Intent(Activity1.this, Activity2.class);
myIntent.putExtra("UserId",UserId);
myIntent.putExtra("UserName",UserName);
myIntent.putExtra("CompanyID",CompanyID);
myIntent.putExtra("CompanyName",CompanyName);
myIntent.putExtra("ProjectId",ProjectId);
startActivity(myIntent);
Also can extract the value you can use
Intent intent = getIntent();
UserId=intent.getStringExtra("UserId");
UserName=intent.getStringExtra("UserName");
CompanyID=intent.getStringExtra("CompanyID");
CompanyName=intent.getStringExtra("CompanyName");
Related
This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 2 years ago.
I have made the code and there's no error, but logcat shows a NullPointerException. This is my code to pass and to catch the value from each activity. Please help me solve this.
First activity:
try {
Intent in = new Intent();
in.setClass(p_daftar_pelanggan.this, ubah_data_pelanggan.class);
in.putExtra("id", eid.getText().toString());
in.putExtra("nama", tnama.getText().toString());
in.putExtra("alamat", ealamat.getText().toString());
in.putExtra("no_hp", ehp.getText().toString());
startActivity(in);
}
catch(NullPointerException ex)
{
}
Second activity:
Bundle b = getIntent().getExtras();
String idpgu = b.getString("id");
String namapgu = b.getString("nama");
String alamatpgu = b.getString("alamat");
String hppgu = b.getString("no_hp");
idp.setText(idpgu);
idp.setKeyListener(null);
nama.setText(namapgu);
ealamat.setText(alamatpgu);
hp.setText(hppgu);
Try the following in the second activity:
Intent intent = getIntent();
String idpgu = intent.getStringExtra("id");
You can use Bundle for this purpose:
Activity destActivity = new Activty();
Bundle b = new Bundle();
destActivity.putString("TAG_ForValue",YourValue.getText().toString());
destActivity.setArguments(b);
Intent intent = new Intent(startActivity.this, destActivity.class);
startActivity(intent);
And in your destActivity :
Bundle bundle = getArguments();
if(bundle !=null)
String value = bundle.getString("TAG_ForValue");
You are sending and receiving the values correctly, but probably some values are null, you can validate setting an empty string instead of a null value:
Bundle b = getIntent().getExtras();
String idpgu = (b.getString("id") != null)? b.getString("id") : "";
String namapgu = (b.getString("nama") != null)? b.getString("nama") : "";
String alamatpgu = (b.getString("alamat") != null)? b.getString("alamat") : "";
String hppgu = (b.getString("no_hp") != null)? b.getString("no_hp") : "";
You put extras using Intent in FirstActivity But Use Bundle to receive it, that is why you have NullPointerException because SecondActivity is looking for values in different place.
Do the following in your secondActvity
Intent intent = getIntent();
String idpgu = intent.getStringExtra("id");
String namapgu = intent.getStringExtra("nama");
String alamatpgu = intent.getStringExtra("alamat");
String hppgu = intent.getStringExtra("no_hp");
// Check Null for each Values e.g.
if (idpgu.trim().equals(" "))
{ idpgu = "null";
}
New to android, I'm currently trying to send a String value from one Activity to another. I have looked through several threads like How to use putExtra() and getExtra() for string data for an answer, but I cannot get it to work.
The string I want to send is:
public void golf(View view) {
Intent intent = new Intent(SearchSport.this, EventList.class);
intent.putExtra("type", "golf");
startActivity(intent);
and my receiver looks like
String type;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_list);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if ( extras != null)
type = extras.getString("type");
if (type == "golf"){
TextView eventName = (TextView) findViewById(R.id.EOName);
TextView eventTime = (TextView) findViewById(R.id.EOTime);
TextView eventLocation = (TextView) findViewById(R.id.EOLocation);
DatabaseOperations dop = new DatabaseOperations(ctx);
Cursor CR = dop.getInformation(1);
CR.moveToFirst();
eventName.setText(CR.getString(1));
eventTime.setText(CR.getString(7) + " " + CR.getString(8) + ". " + CR.getString(9) + " kl. " + CR.getString(10) + ":" + CR.getString(11));
eventLocation.setText(CR.getString(4));}
else {Toast toast = Toast.makeText(this, "Error in Type.", Toast.LENGTH_LONG);
toast.show();}
I have no Idea what's wrong here. The app displays the toast everytime I test it, instead of filling out the TextViews with the data from my database entry.
EDIT: Code has been changed based on answers, but the problem has not yet been solved. Writing if (type.equals("golf")){} instead of if (type == "golf"){} crashed the app.
EDIT 2: Problem solved! Fixed case sensitivity, used .equals instead of ==, and wrote the receiver as
if(getIntent().hasExtra("Type"))
type = getIntent().getStringExtra("Type");
In the end, it turns out is was the virtual device I used which crashed the app, for as of yet unknown reasons. When tested on an actual android phone, the app works as intented.
Thanks to everyone for their help!
try this
if(getIntent().hasExtra("Type"))
type = getIntent().getStringExtra("Type");
Change the key it is case sensitive :
type = extras.getString("Type");
Key is wrong when try to get String from Intent Extra :
type = extras.getString("type");
Replace with :
type = extras.getString("Type");
Note : Also use equals() instead == for comparing String
if (type.equals("golf")){
1) First keys are case sensitive
2) pass as
Bundle bundle = new Bundle()
bundle.putString("type","golf");
intent.putExtras(bundle);
after that get it using
Bundle received = i.getExtras();
received.getString("type");
As you are passing the value using Extra. You must have to catch that using getStringExtra(); and the Key must be case sensitive.
Intent i = getIntent();
type = i.getStringExtra("Type");
Intent in = new Intent(MainActivity.this, Player.class);
String SongName = SpinSongSelector.getSelectedItem().toString ();
startActivity (in);
i wan to send SongName to next Activity
Try this in your first activity,
Intent intent = new Intent(MainActivity.this, Player.class);
String SongName = SpinSongSelector.getSelectedItem().toString ();
intent.putExtra("message", SongName);
startActivity(intent);
and then in second activity get your string like below
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
then set this string to text-view (This is not necessary but just for your reference, if you want to check whether you got correct string or not)
TextView txtView = (TextView) findViewById(R.id.your_resource_textview);
txtView.setText(message);
use this line before startActivty :
intent.putExtra("SongName",SongName);
then retrieve it from the target activty.
just use
first activity to send :
Intent in = new Intent(MainActivity.this, Player.class);
String SongName = SpinSongSelector.getSelectedItem().toString ();
in.putExtra("data",SongName);
startActivity (in);
to receive in another activity:
String Sname = getIntent().getExtras().getString("data");
to see the details of intents refer here : http://developer.android.com/guide/components/intents-filters.html
protected void onMessage(Context context, Intent intent) {
String msg = intent.getStringExtra("payload");
String newspushid1= intent.getStringExtra("payload1");
gc.setnews_pushid(newspushid1);
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
BackgroundAlert bg = new BackgroundAlert(mNotificationManager, msg);
bg.onReceive(getApplicationContext(), intent);
}
In this i am Getting value of msg and Push id (helloworld and 101 respectively) i want get this value in another activity .
if (gdata.getPush_message() != null) {
String push_id_value = gdata.getnews_pushid();
Log.e("CATID", "ID-->" + push_id_value);
}
I have apply this code for getting value .from GCMIntentService class but i am getting same value push_id_value ,getPush_message in another activity which is hello world i am unable to get value 101 in another activity please check my code tell me solution .
Create a Constant Class like :
public class Constant {
public static String PAYLOAD = "";
public static String PAYLOAD_1 = "";
}
Now, you can set this value in Activity1 like
Constant.PAYLOAD = intent.getStringExtra("payload");
Constant.PAYLOAD_1= intent.getStringExtra("payload1");
Now, get this value in Activity2 like:
String push_id_value = Constant.PAYLOAD;
String push_id_value1 = Constant.PAYLOAD_1;
And/or for Preference go to my this answer:Android. How to save user name and password after the app is closed?
In your current Activity,
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("new_variable_name","value");
Then in the new Activity, retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("new_variable_name");
}
Use this technique to pass values from one Activity to another.
I can start another activity when i receive a sms. what I want to know is how to compare the text message with the content in my resources(xml string) and also the textview, editText. Is it possible to get reference from textview and edittext value in broadcast receiver class? Below is the code starting an activity without comparing any value.
public class SMSReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
String phonenumber = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
phonenumber=msgs[i].getOriginatingAddress();
str += msgs[i].getMessageBody().toString();
str += "\n";
}
//=======launch the ShowMap1 when recieve SMS==============//
Intent mainActivityIntent = new Intent(context, ShowMap2.class);
mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mainActivityIntent.putExtra("phn", phonenumber);
mainActivityIntent.putExtra("sms", str);
context.startActivity(mainActivityIntent);
//========================END=============================//
}
}
}
as far as I understood that will be a global receiver that will get SMS.
So it means that the device can be on sleep, on the home screen, on the some game, on the gmail, or any other app; so that means that the Activity and the EditText do not exist at the moment that this receiver is being fired.
You can save a previously entered value from the activity on the SharedPreferences for example, and compare from those values.
To compare from an XML resource is very simple, you're receiving a reference to your application context with this receiver, just use it to get the value with this code:
String compare = context.getString(R.string.___);