简体   繁体   中英

How to simply write and read integer data in a text file?

I have have this app where in my main menu and I want to show the earned stars in a textview which is written in a text file. And also if I earned more stars I want to read the data and add the earned stars and append to the txtfile. For some reasons my app crashes and I have been stuck here for hours. Can anyone please help me with this?

Here's my code:

 import android.widget.TextView; public class MainActivity extends Activity { private static TextView txt_stars; private static final String FILENAME = "Stars.txt"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); onButtonClickListener(); txt_stars = (TextView) findViewById(R.id.txtStars); //This is where I should view the number of stars remaining } public void onButtonClickListener { button_next = (Button) findViewById(R.id.btnNext); button_next.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setMessage("You have earned 50 stars"); alert.setCancelable(false); alert.setPositiveButton("next", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { //Can anyone please help me here? //this should compute the data inserted in textfile and the stars earned, and the result should append to the file. } }); AlertDialog alertDialog = alert.create(); alertDialog.show(); } } ); } } 

Thanks for the help.

You can write two helper methods to read and write.

 private String readStars(String file) {
    BufferedReader reader = null;
    String stars = null;
    StringBuffer buffer = new StringBuffer(); 
    try {
        reader = new BufferedReader(new FileReader(file));
        if(reader != null){
        while((stars = reader.readLine())!= null){buffer.append(stars);};// if you have more lines in your text if not you can simply say reader.readLine()
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return buffers.toString(); // or you can send the length to get the number of stars but you should take care to remove emptylines and empty strings.
}

private String appendStars(String file, String starData) {
    BufferedWriter writer = null;
    String stars = null;
    try {
        writer = new BufferedWriter(new FileWriter(file));
        if(writer != null){
            writer.append(starData);
        }
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return stars;
}

and call them in dialog and button listeners and get the data and append the data to the file.

    SharedPreferences preferences = null;

In OncreateView:

  //This is where I should view the number of stars remaining
    String starsData = readStars("stars.file"); // or you can read it from preference as other said
    /* if you are trying to get it from preferences . here is the sampel*/
    preferences = getSharedPreferences("your preferences key", MODE_PRIVATE); // mode completely depends on you. you can change it as per requirements.
    starsData = preferences.getString("your stars edittext key", ""); // default values can be anything either 1 or empty if string. your choice
    txt_stars.setText(starsData);       

In Dialoglistener:

     //Can anyone please help me here?
    //this should compute the data inserted in textfile and the stars earned, and the result should append to the file.

    String newStars = txt_stars.getText().toString();
    //do the stars calculation and depending . If it is a sample app you can simply append the star in the new line to the file and see if it works for you and later you can modify based on the requirements.
    appendStars("stars.txt", newStars);


    // if you want to use the sharedpreferences
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("your stars edittext key", newStars);
    editor.commit();

It is a good thing that you want to handle the low level management on your own but Is it worth it, when you have to spend more time with it which can be utilized in making something more cool.

Android provides Shared Preference framework which handles saving small amount of data majorly Primitives (eg int , boolean , String , float etc). It can do more than that but you will figure it out as much as you use it.

This can easily reduce your code as it takes care of low level of coding for you.

I have written a test for the which can be used. it is also uploaded on the GitHub link if you would like to check

public class SharedPreferencesActivity extends Activity {

    private EditText count_editText;
    private TextView count_textView;
    private Button save_read_button;

    private static final String FILE_NAME = "text"; //this is the name of file where you will save your count
    private static final String COUNT_KEY = "COUNT_KEY"; // this framework saves data in xml, so we will need key value pair, so this would be a key

    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;

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


        sharedPreferences = getApplicationContext().getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();

        initializeUI();

        String count_Integer = sharedPreferences.getString(COUNT_KEY, "");

        count_textView.setText("" + count_Integer);
        count_editText.setText("" + count_Integer);


    }

    private void initializeUI() {
        count_editText = (EditText) findViewById(R.id.SharedPreferencesActivity_editText);
        count_textView = (TextView) findViewById(R.id.SharedPreferencesActivity_textView);
        save_read_button = (Button) findViewById(R.id.SharedPreferencesActivity_button);
        save_read_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String count_text = count_editText.getText().toString();
                if (count_text != null && count_text.length() > 0) {
                    count_textView.setText("" + count_text);
                    editor.putString(COUNT_KEY, count_text).apply();
                } else {
                    Toast.makeText(getApplicationContext(), "Kindly provide a valid number", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

}

xml file

  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="4dp"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="4dp">


    <EditText
        android:id="@+id/SharedPreferencesActivity_editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_margin="4dp"
        android:ems="10"
        android:inputType="number"
        android:padding="4dp" />

    <TextView
        android:id="@+id/SharedPreferencesActivity_textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_margin="4dp"
        android:padding="4dp"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <Button
        android:id="@+id/SharedPreferencesActivity_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_margin="4dp"
        android:padding="4dp"
        android:text="Read_Save"
        android:textAllCaps="false" />
</LinearLayout>

Output

在此处输入图片说明

In DDMS you can pull the file to see how your data looks like

在此处输入图片说明

When you open this file you may see your data entered is saved in a key value pair provided by you. which would be something like this....

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="COUNT_KEY">235</string>
</map>

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