简体   繁体   中英

Write and Read Android

I have a problem with my code, I need to read EditText from a user and than put that text into another layout and do some calculations. My problem is that I don't understand how to read/write data in Android. Below is a snippet of the read/write code.

Thanks for the help!

EDIT: Should be noted that all of this is inside of my MainActivity class

public EditText editName;
public EditText editAMT;
public Button save;

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

    editName = (EditText) findViewById(R.id.editName);
    editAMT = (EditText) findViewById(R.id.editAMT);
    save = (Button) findViewById(R.id.save);


    File fName = new File(name);
    File fAMT = new File(AMT);

    //WRITING TO THE FILE
    try{
        FileOutputStream test = openFileOutput(name, Context.MODE_PRIVATE);
        FileOutputStream test2 = openFileOutput(AMT, Context.MODE_PRIVATE);

        test.write(editName.getText().toString().getBytes());
        test2.write(editAMT.getText().toString().getBytes());

        test.close();
        test2.close();

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

    //READING FROM THE FILE

    try{
        BufferedReader inputReader = new BufferedReader(new InputStreamReader(openFileInput(name)));
        String inputString;
        StringBuffer stringBuffer = new StringBuffer();

        while ((inputString = inputReader.readLine()) != null){
            stringBuffer.append(inputString + "\n");
        }

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

}

EDIT: Here is my action plan.

1) Get information from EditText called (eAMT). 2) Get information from EditText called (eName). 3) Put the information of eAMT into a file called eName.txt 4) In another activity, search for the file called eName. 5) Once search is completed, pull the contents of that file and display onto another activity (Main activity).

Instead of writing to a file, use Android's SharedPreferences :

SharedPreferences preferences = getSharedPreferences("com.example.myapp", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("UniqueEditNameKey", editName.getText().toString);

From another activity, you can do the following to retrieve the value:

SharedPreferences preferences = getSharedPreferences("com.example.myapp", MODE_PRIVATE);
String name = preferences.getString("UniqueEditNameKey", ""); // second argument is default value if key does not exist

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM