我想将值从一个活动发送到另一个活动,但我得到了空指针 例外请解决我的问题。第一项活动包含短信的细节 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);
}
}
活性2:
Intent i=getIntent();
Bundle bundle=i.getExtras();
String fromAdd=bundle.getString("from");
String msgBody=bundle.getString("body");
答案 0 :(得分:1)
更改此
String msgBody=bundle.getString("body");
到
String msgBody=bundle.getString("msg");
答案 1 :(得分:1)
试试这个:
@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");
}
}
答案 2 :(得分:1)
在Android Bundle中我们放置了键值对,并且必须传递相同的键,同时从bundle中获取数据,这是您放置数据的。检查你的代码,你在意图上放了两个字符串,它们是: “from”和“msg” 并且您通过密钥从意图中获取值: “来自”和“身体”
所以在启动活动或活动2中更改它,以便键值匹配。
答案 3 :(得分:0)
试试这个......
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);
答案 4 :(得分:0)
尝试这种方式..
Bundle bu = getIntent()。getExtras();
String title = bu.get(“from”)。toString();
String msg = bu.get(“body”)。toString();
答案 5 :(得分:0)
试试这个.....将值从Activity1传递给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);
还可以提取您可以使用的值
Intent intent = getIntent();
UserId=intent.getStringExtra("UserId");
UserName=intent.getStringExtra("UserName");
CompanyID=intent.getStringExtra("CompanyID");
CompanyName=intent.getStringExtra("CompanyName");