Intent With Extra 3 Options

Viewed 68

Answered by Intent With Extras

I have an upload activity with two results returned by the server.

Result 1: Data Upload Successful. Result 2: Upload Not Successful.

I added a third result of intent not being received (e.g device data off, or device has no data bundles). How can i return these and set textviews to a message of these depending on what was returned?

ResultsACtivity.java

public class SuccessActivity extends AppCompatActivity {
    public TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.success_main);
        getSupportActionBar().setTitle("Data Upload Results");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        textView = findViewById(R.id.experiences);
        String data;
        String data2 = "Your Data Upload Was NOT Successfull!!";

        Intent intent = getIntent();
        Bundle bundle = getIntent().getExtras();

        if (bundle.containsKey("VAL1")) {
            data = bundle.getString("VAL1");
            textView.setText(data);
        }
        else {
            textView.setText(data2);
        }

VAL1 is data results returned by the server. (1. "Upload Successful" or null.

2 Answers

I recommend you use an enum for this:

enum UploadStatus {
   SUCCESSFUL, UNSUCCESSFUL
}

You can pass this with the intent as a serializable extra, where you start your SuccessActivity from:

intent.putExtra("status", UploadStatus.SUCCESSFUL)

In SuccessActivity you can then read out this value from the intent's extras and set the status text based on that:

Intent intent = getIntent();
UploadStatus status = (UploadStatus) intent.getSerializableExtra("status");

if (intent == UploadStatus.SUCCESSFUL) {
    textView.setText("Your Data Upload was successful");
} 
else {
    textView.setText("Your Data Upload Was NOT Successfull!!");
} 

Please use this code

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.success_main);

    TextView textView = findViewById(R.id.experiences);

    String dataerror = "Your Data Upload Was NOT Successfull!!";

    Intent intent = getIntent();
    if(intent != null) {
        String data = intent.getStringExtra("VAL1"); //  Thats the right way to get the extra String;
        if(data != null && !data.isEmpty()) {
            textView.setText(data);
        } else {
            textView.setText(dataerror);
        }
    } else {
        textView.setText(dataerror);
    }
}
Related