I have a little/big problem in my app in android.I have 2 activity:Activity1 and Activity2. Activity1 has a TextView and a Button and Activity2 has an EditText and a Button. From Activity1 I go to Acvity2 and 开发者_C百科I want to send the text from EditText from Activity2 to Activity 1. I get force close because I don't know the order in code. What should I do? Thanks
Here is my code :
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Activity1 extends Activity {
TextView txt;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt = (TextView) findViewById(R.id.txt);
Button next=(Button)findViewById(R.id.btn);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(Activity1.this,Activity2.class);
startActivityForResult(intent, 0);
}
});
}
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Activity2 extends Activity {
EditText txt2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
txt2 = (EditText)findViewById(R.id.txt2);
final Bundle bundle = new Bundle();
String x=txt2.getText().toString();
bundle.putString("param",x);
Button btn2=(Button)findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(Activity2.this,Activity1.class);
intent.putExtra(bundle)
finish();
}
});
}
}
One problem with your code is that you don't have anything handling the result of the second activity. (There's no onActivityResult in the first activity.)
The notepad tutorial includes a decent example of calling a second activity and getting a result.
In Activity1 @override onActivityResult.
and In Activity2 write this.
txt2 = (EditText)findViewById(R.id.txt2);
final Bundle bundle = new Bundle();
String x=txt2.getText().toString();
Button btn2=(Button)findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
intent.putExtra("param",x);
setResult(RESULT_OK, intent);
finish();
}
In Activity1 @override onActivityResult.
and In Activity2 write this.
txt2 = (EditText)findViewById(R.id.txt2);
final Bundle bundle = new Bundle();
String x=txt2.getText().toString();
bundle.putString("param",x);
Button btn2=(Button)findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
intent.putExtra("param",x);
setResult(RESULT_OK, intent);
finish();
}
});
精彩评论