我有2项活动。 MainActivity和Screen2。我想在按下按钮到Screen2的同时从MainActivity发送在EditView中编写的文本,在那里的EditView上显示它。然后按下Screen2上的按钮,它需要 将其返回到MainActivity并显示连接的消息。但我的应用程序一直在关闭,请帮助我
package com.example.car.cerdo;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
String msg;
public static final String Extra_Message = "myFirst";
static final int Main_requestCode=1;
TextView t = (TextView) findViewById(R.id.t1);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.b1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this, Screen2.class);
msg = t.getText().toString();
myIntent.putExtra(Extra_Message, msg);
startActivityForResult(myIntent,Main_requestCode);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==Main_requestCode)
{
String msg= data.getStringExtra(Screen2.Result_Message);
t.setText(msg);
}
}
}
package com.example.car.cerdo;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Screen2 extends AppCompatActivity {
String msg;
public static final String Result_Message="my_Res";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen2);
Intent i=getIntent();
msg=i.getStringExtra(MainActivity.Extra_Message);
TextView t= (TextView)findViewById(R.id.t2);
t.setText(msg);
Button b=(Button)findViewById(R.id.b2);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent resultIntent= new Intent();
resultIntent.putExtra(Result_Message, msg+" this is new");
setResult(RESULT_OK,resultIntent);// REsultcode
finish();
}
});
}
}
编辑:在Mr.HHAR HUSSAIN'答案之后已经纠正,问题仍然存在。我在评论部分的基础上添加了日志,请检查一下
答案 0 :(得分:1)
在第一个活动中,在onActivityResult中,当您使用“my_res”字符串从第二个屏幕发送时,您正在使用“Result_Message”作为stirng接收字符串。而不是从Screen2调用变量,只需将变量名称放在字符串中以获得解决方案,请参阅下面的代码
在MainActivity.java中执行此操作:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==Main_requestCode) {
String msg= data.getStringExtra(Screen2.Result_Message);
t.setText(msg);
}
}