enter code here
public class MainActivity extends AppCompatActivity {
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTextInTextView();
setContentView(R.layout.activity_main);
}
public void setTextInTextView(){
tv = (TextView) findViewById(R.id.rate);
Bundle extra = getIntent().getExtras();
tv.setText(""+extra.getString("key"));
}
public void go(View view) {
Intent i = new Intent(MainActivity.this,Activity2.class);
startActivity(i);
}
enter code here
public class Activity2 extends AppCompatActivity {
RatingBar rb;
float str;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
rb = (RatingBar)findViewById(R.id.rt);
}
public void submit(View view) {
String st = String.valueOf(rb.getRating());
Intent i = new Intent(Activity2.this,MainActivity.class);
i.putExtra("key",""+st);
startActivity(i);
}
}
我是Android App Development的初学者。我正在尝试使用intent将第二个活动的评级发送到mainActivity。虽然这样做我得到错误:" java.lang.NullPointerException:尝试调用虚方法' java.lang.String android.os.Bundle.getString(java.lang.String)'在null"
答案 0 :(得分:1)
改变这个:
public void setTextInTextView(){
tv = (TextView) findViewById(R.id.rate);
Bundle extra = getIntent().getExtras();
tv.setText(""+extra.getString("key"));
}
到此:
public void setTextInTextView(){
tv = (TextView) findViewById(R.id.rate);
Bundle extra = getIntent().getExtras();
if(extra != null)
tv.setText(""+extra.getString("key"));
}