lundi 11 mai 2015

Cannot assign variable value to a string from extra.getString();

New to android, I'm currently trying to send a String value from one Activity to another. I have looked through several threads like How to use putExtra() and getExtra() for string data for an answer, but I cannot get it to work.

The string I want to send is:

public void golf(View view)  {
    Intent intent = new Intent(SearchSport.this, EventList.class);
    intent.putExtra("type", "golf");
    startActivity(intent);

and my receiver looks like

String type;

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

    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    if ( extras != null)
        type = extras.getString("type");

    if (type == "golf"){
        TextView eventName      = (TextView) findViewById(R.id.EOName);
        TextView eventTime      = (TextView) findViewById(R.id.EOTime);
        TextView eventLocation  = (TextView) findViewById(R.id.EOLocation);

        DatabaseOperations dop = new DatabaseOperations(ctx);
        Cursor CR = dop.getInformation(1);
        CR.moveToFirst();

        eventName.setText(CR.getString(1));
        eventTime.setText(CR.getString(7) + " " + CR.getString(8) + ". " + CR.getString(9) + " kl. " + CR.getString(10) + ":" + CR.getString(11));
        eventLocation.setText(CR.getString(4));}

    else {Toast toast = Toast.makeText(this, "Error in Type.", Toast.LENGTH_LONG);
                toast.show();}

I have no Idea what's wrong here. The app displays the toast everytime I test it, instead of filling out the TextViews with the data from my database entry.

EDIT: Code has been changed based on answers, but the problem has not yet been solved. Writing if (type.equals("golf")){} instead of if (type == "golf"){} crashed the app.

EDIT 2: Problem solved! Fixed case sensitivity, used .equals instead of ==, and wrote the receiver as

if(getIntent().hasExtra("Type"))
    type = getIntent().getStringExtra("Type");

In the end, it turns out is was the virtual device I used which crashed the app, for as of yet unknown reasons. When tested on an actual android phone, the app works as intented.

Thanks to everyone for their help!

Aucun commentaire:

Enregistrer un commentaire