I am having trouble passing data read from a text file to another class in the app. I can read from the file just fine, but I think I need to use Bundle, but I’m not sure how to do it. I would like to have the second class handle the data from the text file, and then display it in the first class.
Edit: I’ve figured out how to pass the string from the file using an intent. I’m still working on getting some of the bugs out.
2nd Edit: I know there is a more efficient way of doing this. The only way I can get it to work is to have the first button in MainActivity use startActivity(intent) to allow secondActivity to bundle the string read from the file.
MainActivity.java:
public class MainActivity extends Activity {
Button btn;
Button bReadFile;
TextView tvRead;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.btnNext);
bReadFile = (Button) findViewById(R.id.btnRead);
tvRead = (TextView) findViewById(R.id.tvMain);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//trying to find a way to remove this button
Intent intent = new Intent(MainActivity.this, econdActivity.class);
startActivity(intent);
}
});
bReadFile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String value = getIntent().getExtras().getString("key");
tvRead.setText(value);
}
});
}
}
secondActivity.java:
public class secondActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent mIntent = new Intent(secondActivity.this, MainActivity.class);
mIntent.putExtra("key", readDataFile());
startActivity(mIntent);
}
public String readDataFile() {
String strData = null;
InputStream is = null;
try {
is = getResources().openRawResource(R.raw.data_text);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
strData = br.readLine();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return strData;
}
}
Use the below edited code for your requirement
MainActivity.java
the code for secondActivity.java