I am trying to make a simple QR Code scanner and run well if the result shows in the MainActivity. But when I'm trying to generate new Activity as a result, it can't show. Would you like to help me with this problem? Thank you.
Here is the result of the scanner code in the scanner.java:
@Override
public void handleResult(Result rawResult) {
startActivity(new Intent(getApplicationContext(),ResultActivity.class));
ResultActivity.scanText2.setText(rawResult.getText());
onBackPressed();
}
And here is the code of my new Activity for showing the result:
public class ResultActivity extends AppCompatActivity {
public static TextView scanText2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patient);
scanText2 = (TextView) findViewById(R.id.scanText2);
}
}
There are a lot of issues with this:
PatientActivity
, not ResultActivity
in handleResult()
TextView
in another Activity
with this code:
ResultActivity.scanText2.setText(rawResult.getText());
This is an absolute no-no. Pass the data to ResultActivity
as an Intent
extra when you launch it. You cannot access the views of another Activity
like that.
ResultActivity.scanText2
will contain a reference to a TextView
, but at this point it will only contain null
. The reason is that it takes some time for ResultActivity
to actually start and call its onCreate()
. You have not accounted for this timing in your code. To solve this problem, just see (2) above.Also, you should have gotten a bunch of crashes with useful messages in your logcat. In the future please look there to solve problems and/or post the messages with stacktrace in your Stackoverflow questions.