Прочитайте другой.txt в зависимости от того, какая кнопка была нажата в предыдущем упражнении.
Я пытаюсь прочитать другой файл.txt (в необработанной папке) во второй активности TextView в зависимости от того, какая кнопка нажата в MainActivity
(предыдущее действие), но это не работает. Я использую .putextras
метод и вот мой код 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();
}
});
Вот мой код SecondActivity с 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();
}
}
}
}
2 ответа
Вы в настоящее время сравниваете данные Bundle со строкой в
if (extradata.equals("textnumberone"))
Это не будет работать, вы должны сначала извлечь данные String. Попробуй это:
Bundle extradata = getIntent().getExtras();
String textString = extradata.getString("Thistext");
if (textString.equals("textnumberone")) {
Еще одна вещь: вы устанавливаете String из Bundle в (я полагаю) TextView в
vitautori.setText(extradata.getString("Thistext"));
но я не вижу инициализации vitautori
в любом месте. Поэтому убедитесь, что он инициализирован, иначе произойдет сбой.
При создании Intent
(в обоих местах, конечно), я предлагаю вам попробовать установить тип на текст:
int1.setType("text/plain");
Посмотрите, поможет ли это.