3

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 fileCSV content enter image description hereenter image description here

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.

enter image description here

enter image description here

5
  • You have to provide the full path for your fileName. And String.getBytes() looks wrong. But I Think, SharedPreferences would fit much better for your requirements. Commented Feb 15, 2016 at 7:09
  • For radio button and checkboxes you have to save their state whether they are checked or not. Commented Feb 15, 2016 at 7:12
  • @JörnBuitink yeah i discovered that thanks to you, and i replaced it with a different syntax, pretty simple, and serve the purpose, still no luck learning how to save the VALUES of only the checked boxes, i was only able to save True&False of all the check boxes to the CSV file as you could see my new code and the screen shot. Commented Feb 19, 2016 at 4:58
  • plz be specific to ur question.. Commented Feb 19, 2016 at 9:04
  • Yeah well, i tried to be specific but i keep getting different issues, so i demonstrated the issue with screen shots and the CODE, at the moment i reached the final problem which is saving Only the Checked boxes, and @NickIsaacs provided the right code so far, but the way i implemented it, only saved the first check box i listed and found that it is checked, and did not continue to check for the rest and save it ... You could see in my Edit post the last code with the issue that needs to be fixed ... Commented Feb 19, 2016 at 10:03

2 Answers 2

1
           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
   }
}
Sign up to request clarification or add additional context in comments.

9 Comments

Thank you, for the code, it helped i was able to work around it, and as you could see in my post which i added my latest code and the problem i am facing name writing the correct entry to the .CSV file, which was able to write the correct number and code entry but not the right text of the check box, it gave me some kind of a number and a message ? what is wrong with my code ?
use checkBox.getText().toString() to get the text of the checkbox
Hey, yeah that kind of worked, referring to my last code i edit in the main post, i replaces .isChecked with .getText and .toString, which saved ALL the checkBoxes values, and i am trying to only log to the CSV file the CHECKED boxes !? how would i achieve that !? implementing it in : String entry = entryCode.getText().toString() + " - " + entryNum.getText().toString() + " - " + selected.getText().toString() +" - " + chkdbx + "\n";
Create an List of CheckBoxes and iterate through them to see which is checked. I'll edit my answer to show you.
thank you, i got it to save the Values of the check box, but as you could see in my last Edit post with your code, it only saved one check box which came first on the list and it is checked without going over the list as soon it found one checked box ??
|
1

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());
} 
}

1 Comment

Searching online i found your suggestion is the most common one, and to simplify my already dead simple app, i implemented a short code, as you could see it is basic, but i am still having problem saving the check boxes, any hint on what is wrong with my Edited code !?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.