在App上保存EditTexts关闭

时间:2014-11-19 16:53:23

标签: java android

在我的应用程序的主页上,我有edittexts,代表我列表中每一行的计数器。每当我更改活动并返回到我的主屏幕时,所有数字都会消失,当我关闭应用程序并再次打开它时也会发生同样的情况。我如何让数字保持不变?

我的主要活动,我用edittexts调用行布局

import android.app.Activity; 
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class MyActivity extends Activity implements MyAdapterInterface{

private CustomCursorAdapter customAdapter;
public ListView list1;

//instantiating the database class
com.example.rory.dripdrop.DBAdapter db = new com.example.rory.dripdrop.DBAdapter(this);
public MyActivity mMyActivity;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);

    list1 = (ListView)findViewById(R.id.data_list);
    db.open();

    mMyActivity = this;

    //button and listener for add activity
    Button addBtn = (Button)findViewById(R.id.add);
    addBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(MyActivity.this, Add.class);
            startActivity(i);
        }
    });

    //button and listener for delete activity
    Button deleteBtn = (Button)findViewById(R.id.delete);
    deleteBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(MyActivity.this, Delete.class);
            startActivity(i);
        }
    });

    //button and listener for update activity
    Button updateBtn = (Button)findViewById(R.id.update);
    updateBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(MyActivity.this, Update.class);
            startActivity(i);
        }
    });


    try {
        String destPath = "/data/data/" + getPackageName() + "/databases/AssignmentDB";
        File f = new File(destPath);
        if (!f.exists()) {
            CopyDB( getBaseContext().getAssets().open("mydb"),
                    new FileOutputStream(destPath));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }


    //handler function for custom adapter, found example online to help with this
    new Handler().post(new Runnable() {
        @Override
        public void run() {
            customAdapter = new CustomCursorAdapter(MyActivity.this, db.getAllRecords(), mMyActivity);
            list1.setAdapter(customAdapter);
        }
    });

}


public void onResume()
{
    super.onResume();
    //update list
    addData();
}

//refreshes data base when main page is resumed
public void addData()
{

    //handler function for custom adapter, found example online to help with this
    new Handler().post(new Runnable() {
        @Override
        public void run() {
            customAdapter = new CustomCursorAdapter(MyActivity.this, db.getAllRecords(), mMyActivity);
            list1.setAdapter(customAdapter);
        }
    });

}


//chaning the running total
public void updateLitres(int value)
{
    EditText editLitres = (EditText)findViewById(R.id.edit1);
    //EditText myEditText2 = (EditText)findViewById(R.id.edit2);

    editLitres.setText(String.valueOf(value));
    //myEditText2.setText(String.valueOf(value));
}

public void updateCost(double value)
{
    EditText editCost = (EditText)findViewById(R.id.edit2);
    String.format("%.2f", value);
    editCost.setText("€" + String.valueOf(value));
}

private class DBAdapter extends BaseAdapter {
    private LayoutInflater mInflater;
    //private ArrayList<>

    @Override
    public int getCount() {

        return 0;
    }

    @Override
    public Object getItem(int arg0) {

        return null;
    }

    @Override
    public long getItemId(int arg0) {

        return 0;
    }

    @Override
    public View getView(int arg0, View arg1, ViewGroup arg2) {

        return null;
    }

}

public void CopyDB(InputStream inputStream, OutputStream outputStream)
        throws IOException {
    //---copy 1K bytes at a time---
    byte[] buffer = new byte[1024];
    int length;
    while ((length = inputStream.read(buffer)) > 0) {
        outputStream.write(buffer, 0, length);
    }
    inputStream.close();
    outputStream.close();
}
}

我的行自定义适配器

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; 
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.TextView;

import java.util.ArrayList;


public class CustomCursorAdapter extends CursorAdapter {

//public int counter = 0;
public ArrayList<Integer> counter;
public ArrayList<Integer> counter2;
private MyAdapterInterface mMyInterface;

public CustomCursorAdapter(Context context, Cursor cursor, MyAdapterInterface myInterface) {

    //instantiating the values
    super(context, cursor);
    this.context = context;
    this.mMyInterface = myInterface;

    //array to sort each value per row
    counter = new ArrayList<Integer>();
    counter2 = new ArrayList<Integer>();

    //default all counters to 0
    for(int i=0; i<cursor.getCount(); i++)
    {
        counter.add(0);
        counter2.add(0);
    }

}
Context context;


@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    // when the view will be created for first time,
    // we need to tell the adapters, how each item will look
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View retView = inflater.inflate(R.layout.row, parent, false);

    return retView;
}

public void bindView(View view, Context context, final Cursor cursor) {

    //getting the first value for the custom row (the item name)
    TextView textViewItemName = (TextView) view.findViewById(R.id.item1);
    textViewItemName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));


    final int litres = Integer.parseInt(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(2))));

    //editText for custom row
    final EditText runningTotal = (EditText) view.findViewById(R.id.runningTotal);

    //setting up the plus button
    final Button plusButton = (Button)view.findViewById(R.id.plusButton);
    plusButton.setOnClickListener(new View.OnClickListener() {
        private int counterPos;
        private int counter2;

        public void onClick(View v) {
            //code to change the value of the editText and the array, not working

            //cursor.getPosition() returns the position in the list
            counterPos = counter.get(cursor.getPosition());


            //increments the number at counterPos
            counterPos = counterPos + litres;

            //incrementing the edittext
            //counter2 = counter.get(cursor.getPosition());
            counter2++;

            //set the new value to the array position
            counter.set(cursor.getPosition(), counterPos);

            //changes the editText in middle of row
            runningTotal.setText(Integer.toString(counter2));

            //sends counterPos to the interface for the running total
            mMyInterface.updateLitres(counterPos);
            mMyInterface.updateCost(counterPos * 0.00488);
        }
    });

    //setting up the minus button
    final Button minusButton = (Button)view.findViewById(R.id.minusButton);
    minusButton.setOnClickListener(new View.OnClickListener() {
        private int counterPos = 0;
        private int counter2;

        public void onClick(View v) {
            //code to change the value of the editText and the array, not working

            counterPos = counter.get(cursor.getPosition());


            //increments the number at counterPos
            counterPos = counterPos + litres;

            //incrementing the edittext
            //counter2 = counter.get(cursor.getPosition());
            counter2--;

            //set the new value to the array position
            counter.set(cursor.getPosition(), counterPos);

            //changes the editText in middle of row
            runningTotal.setText(Integer.toString(counter2));

            //sends counterPos to the interface for the running total
            mMyInterface.updateLitres(counterPos);
            mMyInterface.updateCost(counterPos * 0.00488);
        }
    });
}
}

5 个答案:

答案 0 :(得分:0)

您将需要查看SharedPreferences,一旦您这样做,您将基本上将您的值保存在onPause()/ onDestroy()方法的SharedPreferences中,然后在您的onResume()/ onCreate()方法中,您将检索以前存储的数据

编辑:您可以通过以下方式从EditText中检索字符串

String toStore = EditText.getText().toString();

然后存储

getSharedPreferences("PREFERENCE",MODE_PRIVATE).edit().putString("KEY", toStore);

所以...

public void onPause(){
    super.onPause();
    String toStore = EditText.getText().toString();
    getSharedPreferences("PREFERENCE",MODE_PRIVATE).edit().putString("KEY", toStore);
}

public void onResume(){
    super.onResume();
    String toStore = PreferenceManager.getDefaultSharedPreferences(context).getString("KEY", "defaultStringIfNothingFound");
    EditText.setText(toStore);
}

答案 1 :(得分:0)

没有阅读您的代码兄弟,但是回答您的问题标题:

覆盖onStop并将数据保存到共享首选项,它非常易于使用:

//To save your data
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();

//to extract your data in onCreate or whenever you feel like:

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String restoredText = prefs.getString("text", null);

答案 2 :(得分:0)

您可以使用onSavedInstanceStateonRestoreInstanceState种活动方法!

所以在onSavedInstanceState(在你的活动暂停之前调用)你可以将你的`EditText'值保存到包中,

并将其恢复为onRestoreInstance状态。

您可以使用@Kaique的链接获取更多参考,

以及此答案https://stackoverflow.com/a/16769864/826657以及此处的所有相关答案。

答案 3 :(得分:0)

答案 4 :(得分:0)

你应该看看这里你应该看看共享的偏好,http://developer.android.com/reference/android/content/SharedPreferences.html,我用它并帮助我完成它,你需要保存你想要保存的每个编辑文本。至于每一行,我建议制作一个数组或循环来保存行中的编辑框