简体   繁体   中英

Saving user input to text file, android studio

Well, I'm trying to implement some basic java knowledge I gained by creating a simple app with Android Studio.

Basically my app would receive some information from user and save it to a text file, the app serves as kind of a template to receive information.

Elements are;

2 text fields, actually one field with option of entering Letters ( A,B,C etc...) or numbers, the Second TextField would accept only Numbers.

6 Radio Buttons, user should and only could choose one, i already placed these Buttons in a Radio Group.

4 Check boxes, user should tick the box or boxes suitable for the entry.

2 Buttons, one to save, other to edit.

as it is shown in the screen capture.

My code goes as this so far, and MY ISSUE is , that I can't figure out how to implement the write command into the java file, as i learned doing so in eclipse. I want to save the entry into a text file, but not sure what is the write syntax for this in android studio, and how to do that with the check boxes and radio buttons ?

I've tried to go over several question and tutorials but can't put it together, any guidance and tips would be really appreciated .

CODE:

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;

public class MainActivity extends AppCompatActivity {



EditText CodNum;
EditText PltNum;
RadioButton radButA;
RadioButton radButD;
RadioButton radButS;
RadioButton radButR;
RadioButton radButO;
RadioButton radButI;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);



    CodNum = (EditText) findViewById(R. id.CodNum);
    PltNum = (EditText) findViewById(R. id.PltNum);
    radButA = (RadioButton) findViewById(R. id.radButA);
    radButD = (RadioButton) findViewById(R. id.radButD);
    radButS = (RadioButton) findViewById(R. id.radButS);
    radButR = (RadioButton) findViewById(R. id.radButR);
    radButO = (RadioButton) findViewById(R. id.radButO);
    radButI = (RadioButton) findViewById(R. id.radButI);
    checkBoxMw = (CheckBox) findViewById(R. id.checkBoxMw);
    checkBoxG7 = (CheckBox) findViewById(R. id.checkBoxG7);
    checkBoxGw = (CheckBox) findViewById(R. id.checkBoxGw);
    checkBoxF = (CheckBox) findViewById(R. id.checkBoxF);
    final FileOutputStream outputStream;
    String fileName = "feederTxtFile";


    Button buttonS = (Button) findViewById(R. id.buttonS);
    buttonS.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                try{
                    outputStream = openFileOutput(fileName,CONTEXT.MOOD_PRIVATE);
                    outputStream.write(String.getBytes());
                    outputStream.close();
                }catch (Exception e){
                    e.printStackTrace();
                }

                }
            });

    Button buttonE = (Button) findViewById(R. id.buttonE);
    buttonE.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //Editing to text file.
        }
    });

All right so i corrected the code, and added the right syntax to save the Code and Number but i am still having a problem with it to save the right RadioButton and CheckBox, Actually iwas able to make it save the Radio button but with a weird message and part of it including the RadioButton id, and i wan it to just save the Radiobutton name ( A, D, R, etc .. ) next to the number and the same with the check box which i do not have any clue how to even deal with the check boxes !?

Could someone please guid me on what is wrong with my RadioButton code and HOW TO SAVE THE CHECK BOXES !?

This is the new code:

public class MainActivity extends AppCompatActivity {

private EditText entryCode;
private EditText entryNum;

private RadioGroup radioBtnGr;
private RadioButton radioButtonA;
private RadioButton radioButtonD;
private RadioButton radioButtonS;
private RadioButton radioButtonR;
private RadioButton radioButtonO;
private RadioButton radioButtonI;

private CheckBox checkBoxGw;
private CheckBox checkBoxG7;
private CheckBox checkBoxKL;
private CheckBox checkBoxFW;


View.OnClickListener checkBoxListener;

private Button buttonE;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    entryAcceptance();
}

public void entryAcceptance(){

    entryCode = (EditText) findViewById(R. id.entryCode);
    entryNum = (EditText) findViewById(R. id.entryNum);

    radioBtnGr = (RadioGroup) findViewById(R. id.RadioBtnGr);
    radioButtonA = (RadioButton)findViewById(R.id.radioButtonA);
    radioButtonD = (RadioButton)findViewById(R.id.radioButtonD);
    radioButtonS = (RadioButton)findViewById(R.id.radioButtonS);
    radioButtonR = (RadioButton)findViewById(R.id.radioButtonR);
    radioButtonO = (RadioButton)findViewById(R.id.radioButtonO);
    radioButtonI = (RadioButton)findViewById(R.id.radioButtonI);

    checkBoxGw = (CheckBox) findViewById(R. id.checkBoxGw);
    checkBoxG7 =  (CheckBox) findViewById(R. id.checkBoxG7);
    checkBoxKL =  (CheckBox) findViewById(R. id.checkBoxKL);
    checkBoxFW =  (CheckBox) findViewById(R. id.checkBoxFW);


}

public void radioButtonClicked(View v)
{
    int selectedCode = radioBtnGr.getCheckedRadioButtonId();
    RadioButton selected = (RadioButton)findViewById(selectedCode);
    toasting(selected.getText().toString());
}

public void saveLogOnClick(View view){
    int selectedCodNum = radioBtnGr.getCheckedRadioButtonId();
    RadioButton selected = (RadioButton)findViewById(selectedCodNum);

    CheckBox selectedChBx = (CheckBox)findViewById();


    String FILENAME = "entry_log.csv";
    String entry = entryCode.getText().toString() + "-" +
            entryNum.getText().toString() +
            selected + "\n";
    try {
        FileOutputStream out = openFileOutput(FILENAME, Context.MODE_APPEND);
        out.write(entry.getBytes());
        out.close();
        toasting("Entry Saved");
    }catch (Exception e){
        e.printStackTrace();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public void toasting(String msg){
    Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();

}

}

and the a screen shot of the content of the CSV file CSV content 在此输入图像描述 在此输入图像描述

OK, so i was able to fix the problem with the RadioButton correct Syntax, in order for it to save the Character it represent ( A, D, etc.. ). i had to change this part : String entry = entryCode.getText().toString() + "-" + entryNum.getText().toString() + selected + "\\n"; adding .getText().toString() before " selected ". and it saved the right Character the chosen RadioButton selected in the CSV file.

But i am still not sure how to deal with the CheckBoxes ... how to save the name of the CheckBox checked in the CSV file !?

thought of adding an if else statement somewhere and save it in a way or another to the CSV file, but i am trying to figure out if will be able to do this and how, or IF THERE IS A BETTER WAY !?

Will keep trying, hopefully someone could suggest something, and show me a good way to do it ...

I am still trying to get the right values and only the values of the checked boxes, which i was able only to list, True & False for the check boxes states, with this code :

    public void saveLogOnClick(View view){
    int selectedCodNum = radioBtnGr.getCheckedRadioButtonId();
    RadioButton selected = (RadioButton)findViewById(selectedCodNum);

   StringBuffer chkdbx = new StringBuffer();
    chkdbx.append(checkBoxGw.isChecked());
    chkdbx.append(checkBoxG7.isChecked());
    chkdbx.append(checkBoxKL.isChecked());
    chkdbx.append(checkBoxFW.isChecked());

    String FILENAME = "entry_log.csv";
    String entry = entryCode.getText().toString() + " - " +
            entryNum.getText().toString() + " - " +
            selected.getText().toString() +" - " + chkdbx.toString() +  "\n";
    try {
        FileOutputStream out = openFileOutput(FILENAME, Context.MODE_APPEND);
        out.write(entry.getBytes());
        out.close();
        toasting("Entry Saved");
    }catch (Exception e){
        e.printStackTrace();
    }
}

Not getting any responses on this post from previous participant, i am aware this is a straight forward issues, and it is simple to solve, but i am learning to implement new methods i am just learning by building this simple app.

Hope i get some hints on how to do this the right way.

Need to save the Value of the checked Boxes in the CSV file, not true and false;

Finally the right way to log the Value of the Checked boxes is this way :

       List<CheckBox>checkBoxes=new ArrayList<>();
    checkBoxes.add(checkBoxGw);
    checkBoxes.add(checkBoxG7);
    checkBoxes.add(checkBoxKL);
    checkBoxes.add(checkBoxFW);
    String checkBoxText = "";

    for(CheckBox checkBox: checkBoxes){
        if(checkBox.isChecked()){
            checkBoxText = checkBoxText + " - " + checkBox.getText().toString();
        }
    }

    String FILENAME = "entry_log.csv";
    String entry = entryCode.getText().toString() + " - " +
            entryNum.getText().toString() + " - " +
            selected.getText().toString() +" - " + checkBoxText +  "\n";

but apparently it only saves the first check box that is checked and comes up in the list without going over the rest of the list or saving more than one checked box !?

So i fixed the part suggested by @NickIsaacs which is CheckBoxText + " , " + checBoxes.getText().toString(); and it should have saved the Checked Boxes, but instead i did not get any Values at all for the Check Boxes !?

I understand this is turning to a tutorial more than a question and answer, which should be considering how simple this is, but i am learning along the way, thank yall.

attached screen shot of the CSV file after the change in the code , no Values of Checked boxes ??

ALL RIGHT, at last, the minor issue was that in the code, that goes over the check boxes list, and list the checked boxes, separating each entry with " , " should be replaced with something else such as " - ", since the file the input is being saved on is CSV file.

在此输入图像描述

在此输入图像描述

           String text = editText.getText().toString();
           boolean checked = radioButton.isChecked();
           // do what you want with these
           FileOutputStream outputStream;
           try{
                outputStream = openFileOutput(fileName,CONTEXT.MODE_PRIVATE);
                outputStream.write(text.getBytes());
                outputStream.close();
            }catch (Exception e){
                e.printStackTrace();
            }

EDIT:

Create a List of CheckBoxes.

List<CheckBox> checkBoxes= new ArrayList<CheckBox>();
checkBoxes.add(checkBox1);

//keep adding all your checkboxes to this list
String checkBoxText = "";

for (CheckBox checkBox: checkBoxes){
   if(checkBox.isChecked()){ 
      checkBoxText= checkBoxText + "-" +checkBox.getText().toString();
      //Do what you like with this
   }
}

simply you can use OutputStreamWriter for this purpose. It gives you facility to directly give String as a parameter. And write to file

String data = editText.getText().toString();
private void writeToFile(String data) {
try {
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
    outputStreamWriter.write(data);
    outputStreamWriter.close();
}
catch (IOException e) {
    Log.e("Exception", "File write failed: " + e.toString());
} 
}

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