Chuck Barnett
Chuck Barnett

Reputation: 5

How to retrieve a specific string from a file? (android)

I am creating an android app that records five EditText inputs and stores them in a file. What I need to know is how to individually retrieve each file and output the result to another EditText field.

MyExampleCode:

package chuck.com;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.app.Activity;
import android.content.Intent;

public class FillFile extends Activity {

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





    Button submit = (Button) findViewById(R.id.button1);
    submit.setOnClickListener(sub);
    Button disp = (Button) findViewById(R.id.button2);
    disp.setOnClickListener(dis);
}
private OnClickListener sub = new OnClickListener(){
    public void onClick(View v){

        try {
            EditText one = (EditText) findViewById(R.id.editText1);
            EditText two = (EditText) findViewById(R.id.editText2);
            EditText three = (EditText) findViewById(R.id.editText3);
            EditText four = (EditText) findViewById(R.id.editText4);
            EditText five = (EditText) findViewById(R.id.editText5);

            FileOutputStream fos;
            fos = openFileOutput("XML.txt", MODE_APPEND);

            String uno = one.getText().toString();
            String dos = two.getText().toString();
            String tres = three.getText().toString();
            String quatro = four.getText().toString();
            String cinco = five.getText().toString();

            fos.write(uno.getBytes());
            fos.write(dos.getBytes());
            fos.write(tres.getBytes());
            fos.write(quatro.getBytes());
            fos.write(cinco.getBytes());

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
};
private OnClickListener dis = new OnClickListener(){
    public void onClick(View v){
        Intent transf = new Intent(v.getContext(), MainActivity.class);
        startActivityForResult(transf, 0);
    }
};
}

the xml layout i want to export the file to:

 package chuck.com;

 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;

 import android.os.Bundle;
 import android.app.Activity;
 import android.content.Intent;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.TextView;

 public class MainActivity extends Activity {

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

    File fileDir = getFilesDir();
    String fileName = ("XML.txt");
    File backup = new File(fileDir, fileName);
    boolean content = backup.length() == 0;

    try {
        backup.createNewFile();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    TextView one = (TextView) findViewById(R.id.textView1);
    TextView two = (TextView) findViewById(R.id.textView2);
    TextView three = (TextView) findViewById(R.id.textView3);
    TextView four = (TextView) findViewById(R.id.textView4);
    TextView five = (TextView) findViewById(R.id.textView5);

    EditText eOne = (EditText) findViewById(R.id.editText1);
    EditText eTwo = (EditText) findViewById(R.id.editText2);
    EditText eThree = (EditText) findViewById(R.id.editText3);
    EditText eFour = (EditText) findViewById(R.id.editText4);

    Button input = (Button) findViewById(R.id.input_button);
    input.setOnClickListener(insert);
    if (content)
    {
        one.setVisibility(View.GONE);
        two.setVisibility(View.GONE);
        three.setVisibility(View.GONE);
        four.setVisibility(View.GONE);

        eOne.setVisibility(View.GONE);
        eTwo.setVisibility(View.GONE);
        eThree.setVisibility(View.GONE);
        eFour.setVisibility(View.GONE);
    }
    else
    {
        five.setVisibility(View.GONE);

        FileInputStream fis;
        fis = openFileInput("XML.txt");

        eOne.setText(uno);
        eTwo.setText(dos);
        eThree.setText(tres);
        eFour.setText(quatro, cinco);
    }
  }
  private OnClickListener insert = new OnClickListener(){
    public void onClick(View v) { 
        Intent trans = new Intent(v.getContext(), FillFile.class);
        startActivityForResult(trans, 0);
    }
};
  }

Upvotes: 0

Views: 330

Answers (1)

kalelien
kalelien

Reputation: 432

fos.write("uno=".getBytes());
fos.write(uno.getBytes());
fos.write("\n".getBytes());
fos.write("dos=".getBytes());
fos.write(dos.getBytes());
...

This will produce a file that has

uno=<editText1 text>
dos=<editText2 text>
...

Then when you read this file. Read one line at a time. Split the line on '=' (or what ever delimiter you decide to use). If the text to the left of the delimiter equals the key you are looking for then you know the text to the right of the delimiter is the text you need to grab.

Personally, if I were going to write a file this way I would use PrintWriter instead of a FileOutputStream only because it would make the code a little cleaner. It would look like

PrintWriter pw = new PrintWriter(fos);
pw.println("uno=" + uno);
pw.println("dos=" + dos);
...

EDIT (Added code requested by OP)

What this does is read line by line. It splits each line on '='. Then it compares the 0th position of the split string (This will be what was to the left of '=') with your keys. If it is equal to the key you want then the 1st position of the split string will be the actual text you want to grab.

BufferedReader br = new BufferedReader(new FileReader("file.txt"));

String line;
whlie( (line = br.readLine()) != null ){
   String[] separated = line.split("=");
   if( "uno".equals(separated[0]) )
      // Key is uno seaparated[1] has <editText1 text> (assuming example above)
   if( "dos".equals(separated[0]) )
      // Key is dos separated[1] has <editText2 text> (assuming example above)
   ...
}

Note You should probably add more error checking - I excluded it for simplicity.

Just as an example though - you could imagine the case where the user input something into the edit text with an '=' in it (say the user input into editText1 "1+1=2"). In this case separated would have 3 parts.

0 Your key (uno in the example)

1 The first part the user entered to the left of the user input '=' ('1+1' in the example)

2 The second part the user entered to the right of the user input '=' ('2' in the example).

An easy solution to this would to simply loop over the rest of the separated String to ensure you get all the info

if( "uno".equals(separated[0]) ){
   String info = "";
   for( int i=1; i<separated.length; i++ ){
      info += separated[i];
      if( (i+1) < separated.length ){
         info += "="; // This replaces the user input '=' that you split out
      }
   }
   // After this loop info has the exact String the user entered even if it contained your delimiter ('=' in this example)
}

Another Note Instead of using .split() you can also use StringTokenizer they pretty much do the same thing, but some prefer one over the other. Use which ever works best and makes sense to you. If you are unfamiliar with both here is a good post that shows the use of the 2 Android Split string

Additional Edit It appears that StringTokenizer is discouraged in new code. From Javadoc http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html

"StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead"

Upvotes: 2

Related Questions