1

on the homepage of my app i have edittexts that represent counters for each row in my list. whenever i change activity and return back to my main screen all the numbers disappear, the same happens when I close the app and open it again. How do i make the numbers stay?

My main activity where I call the row layout with the 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();
}
}

My custom adapter for the rows

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);
        }
    });
}
}
Rory
  • 27
  • 6

5 Answers5

0

You will want to look into SharedPreferences, once you do you will basically be saving your values in SharedPreferences in an onPause() / onDestroy() method, and then in your onResume() / onCreate() methods you will retrieve the previously stored data

Edit: You can retrieve a string from an EditText in the following way

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

and then store it

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

so...

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);
}
Galax
  • 367
  • 1
  • 13
  • thanks for the reply, I have done some reading on the sharedPreferences but can seem to figure out how to add each edittext from the row in, can you help? – Rory Nov 19 '14 at 17:25
  • sorry to be a pain haha but i am struggling with this concept. so i should make an onPause function and add in the code above and then create an onResume function to call the toString variable to resort the values in all the edittexts? – Rory Nov 19 '14 at 17:44
  • The above will work for saving and then reloading them into the fields, you have to specify the fields they go in though. – Galax Nov 19 '14 at 17:48
  • and how would i do that for a list view? – Rory Nov 19 '14 at 17:55
  • You would have to loop through the list view and use listView.getChildAt(i); – Galax Nov 19 '14 at 17:59
  • thanks for all the help, i implemented the functions and tried making a loop but i just cant get it to work! – Rory Nov 19 '14 at 18:20
0

didn't read your code bro, but answering in concern to your question title :

override onStop and save the data to Shared Preferences, its very easy to use:

//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);
Sarthak Mittal
  • 5,794
  • 2
  • 24
  • 44
0

You may use onSavedInstanceState and onRestoreInstanceState methods of activity !

So in onSavedInstanceState (called before your activity pauses) you may save your `EditText' values to the bundle,

And restore them back in onRestoreInstance state.

You can use the link by @Kaique for more reference,

and also this answer https://stackoverflow.com/a/16769864/826657 and all related answers here.

Community
  • 1
  • 1
Rachit Mishra
  • 6,101
  • 4
  • 30
  • 51
0

You should take a look at the shared preferences, http://developer.android.com/reference/android/content/SharedPreferences.html

0

You should have a look here You should take a look at the shared preferences, http://developer.android.com/reference/android/content/SharedPreferences.html, I used this and helped me get through it, You need to save each edit text that you want to save. and as for each row I would suggest making an array or loop for saving the edit boxes in the rows

Hayes121
  • 67
  • 6