androidandroid-activitytexttextviewextras

Read a different .txt depending on what button is pressed in previous activity


I'm trying to read a different .txt file (in a raw folder) in a second activity TextView depending on what button is pressed in MainActivity (the previous activity), but it doesn't work. I'm using the .putextras method and here is my code of the MainActivity:

    ImageButton but1=(ImageButton) findViewById(R.id.imageButton2);
    but1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent int1=new Intent(MainActivity.this,SecondActivity.class);
            int1.putExtra("Thistext", "textnumberone");
            startActivity(int1);


            finish();



        }
    });

    ImageButton but2(ImageButton) findViewById(R.id.imageButton3);
    but2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent int2=new Intent(MainActivity.this,SecondActivity.class);
            int2.putExtra("Thistext", "textnumbertwo");
            startActivity(int2);


            finish();



        }
    });

Here is my code of the SecondActivity with the Bundle..

    Bundle extradata = getIntent().getExtras();


    TextView tv = (TextView)findViewById(R.id.firsttextView);
    vitautori.setText(extradata.getString("Thistext"));

    if (extradata.equals("textnumberone")) {

        String texttxt = "";
        StringBuffer sbuffer = new StringBuffer();
        InputStream is = this.getResources().openRawResource(R.raw.file);
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        try {

            while ((texttxt = reader.readLine()) !=null){
                sbuffer.append(texttxt + "n");

            }

            tv.setText(sbuffer);
            is.close();


        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    }
}

Solution

  • You are currently comparing the Bundle data to a string in

    if (extradata.equals("textnumberone"))

    This will not work, you have to extract the String data first. Try this:

    Bundle extradata = getIntent().getExtras();
    String textString = extradata.getString("Thistext");
    if (textString.equals("textnumberone")) {
    

    One other thing: You set the String from the Bundle to a (I suppose) TextView in

    vitautori.setText(extradata.getString("Thistext"));

    but I don't see the initialization of vitautori anywhere. So make sure the it is initialized or this will crash.