Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have 4 arrays that I need to be able to save and load to sharedpreference:

String[] debtName = new String[10];
String[] debtAmount = new String[10];
String[] debtRate = new String[10];
String[] debtPayment = new String[10];

Below is my full activity:

import java.util.Arrays;

import org.json.JSONArray;
import org.json.JSONException;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;

public class DebtList<T> extends Activity {

    String[] debtName = new String[10];
    String[] debtAmount = new String[10];
    String[] debtRate = new String[10];
    String[] debtPayment = new String[10];

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.debtlist);

        JSONArray nameJSONArray = new JSONArray(Arrays.asList(debtName));
        JSONArray amountJSONArray = new JSONArray(Arrays.asList(debtAmount));
        JSONArray rateJSONArray = new JSONArray(Arrays.asList(debtRate));
        JSONArray paymentJSONArray = new JSONArray(Arrays.asList(debtPayment));

        Bundle extras = getIntent().getExtras();

        int trigger = 0;

        //Load Data
        SharedPreferences sharedPrefs= getSharedPreferences("chaosdata", 0);
        //public static JSONArray loadJSONArray(Context c, String prefName, String key)
        ////JSONSharedPreferences.saveJSONArray(this.getApplicationContext(), "prefName", "prefKey", nameJSONArray);

        String jsonString = sharedPrefs.getString("debtNames", "1234");
        if (jsonString != null) {
            JSONArray jsonArray;
            try {
                jsonArray = new JSONArray(jsonString);
                for (int i = 0; i < jsonArray.length(); i++) {
                    debtName[i] = jsonArray.optString(i);
                }
            } catch (JSONException e) {
            }
        }




        //End Load

        for (int i=0;i<10;i++)
        {
            if (debtName[i] == null && extras != null && trigger==0)
            {
                debtName[i] = extras.getString("debtName");
                debtAmount[i] = extras.getString("debtAmount");
                debtRate[i] = extras.getString("debtRate");
                debtPayment[i] = extras.getString("debtPayment");
                trigger = 1;
            }
        }

        TableLayout tl = (TableLayout) findViewById(R.id.debtListTableView);
        for (int i=0;i<10;i++)
        {
            if (debtName[i] != null)
            {

                TableRow tr = new TableRow(this);
                TextView tv0 = new TextView(this);
                TextView tv1 = new TextView(this);
                TextView tv2 = new TextView(this);
                TextView tv3 = new TextView(this);
                TableRow.LayoutParams trlp = new TableRow.LayoutParams();
                tv0.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
                tv1.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
                tv2.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
                tv3.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
                trlp.span = 3;
                tr.setLayoutParams(trlp);
                tv0.setText("" + debtName[i]);
                tv1.setText("" + debtAmount[i]);
                tv2.setText("" + debtPayment[i]);
                tv3.setText("Holder");
                tr.addView(tv0);
                tr.addView(tv1);
                tr.addView(tv2);
                tr.addView(tv3);
                tl.addView(tr);
            }
        }

        //Save Data
        JSONSharedPreferences.saveJSONArray(this.getApplicationContext(), "chaosdata", "debtNames", nameJSONArray);
        JSONSharedPreferences.saveJSONArray(this.getApplicationContext(), "chaosdata", "debtAmounts", amountJSONArray);
        JSONSharedPreferences.saveJSONArray(this.getApplicationContext(), "chaosdata", "debtRates", rateJSONArray);
        JSONSharedPreferences.saveJSONArray(this.getApplicationContext(), "chaosdata", "debtPayments", paymentJSONArray);
        //End Save


    }

    public static class JSONSharedPreferences {
        private static final String PREFIX = "json";

        public static void saveJSONArray(Context c, String prefName, String key, JSONArray array) {
            SharedPreferences settings = c.getSharedPreferences(prefName, 0);
            SharedPreferences.Editor editor = settings.edit();
            editor.putString(JSONSharedPreferences.PREFIX+key, array.toString());
            editor.commit();
        }

        public static JSONArray loadJSONArray(Context c, String prefName, String key) throws JSONException {
            SharedPreferences settings = c.getSharedPreferences(prefName, 0);
            return new JSONArray(settings.getString(JSONSharedPreferences.PREFIX+key, "[]"));
        }

        public static void remove(Context c, String prefName, String key) {
            SharedPreferences settings = c.getSharedPreferences(prefName, 0);
            if (settings.contains(JSONSharedPreferences.PREFIX+key)) {
                SharedPreferences.Editor editor = settings.edit();
                editor.remove(JSONSharedPreferences.PREFIX+key);
                editor.commit();
            }
        }

    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.debt_list, menu);
        return true;
    }

}

When run, it does not throw any errors. What I'm having problems figuring out is how to retrieve the data back to JSON arrays and then back to arrays so I can manipulate the data in other parts of the application.

share|improve this question
    
See Edited version above –  jpgerb Nov 5 '13 at 4:59

2 Answers 2

public static String getPref(String key, Context context) {
    SharedPreferences preferences= c.getSharedPreferences(prefName, 0);
    return preferences.getString(key, null);
}

Use the above method to get data by passing the key into the method

share|improve this answer
    
based on the "public static JSONArray loadJSONArray" how would I retrieve the JSONArray? –  jpgerb Nov 5 '13 at 4:45

To retrieve the data back into arrays, you have to iterate over the JSONArray:

String jsonString = prefs.getString("key", null);
if (jsonString != null) {
    JSONArray jsonArray;
    try {
        jsonArray = new JSONArray(jsonString);
        for (int i = 0; i < jsonArray.length(); i++) {
            debtName[i] = jsonArray.optString(i);
        }
    } catch (JSONException e) {
    }
}

For clarification, here's the code I used for testing:

In MainAcitivity:

String[] debtName = {"Douglas", "Fabiano", "Drumond"};
SharedPreferences prefs = getSharedPreferences("com.douglasdrumond.test.prefs", Context.MODE_PRIVATE);
Editor editor = prefs.edit();
JSONArray nameJSONArray = new JSONArray(Arrays.asList(debtName));
editor.putString("com.douglasdrumond.test.debtName", nameJSONArray.toString());
editor.commit();

In SecondActivity:

String[] debtName = new String[3];
SharedPreferences prefs = getSharedPreferences("com.douglasdrumond.test.prefs", Context.MODE_PRIVATE);
String jsonString = prefs.getString("com.douglasdrumond.test.debtName", null);
if (jsonString != null) {
    JSONArray jsonArray;
    try {
        jsonArray = new JSONArray(jsonString);
        for (int i = 0; i < jsonArray.length(); i++) {
            debtName[i] = jsonArray.optString(i);
        }
    } catch (JSONException e) {
    }
}
share|improve this answer
    
it's not returning any values, though it is not providing an error either –  jpgerb Nov 5 '13 at 4:58
    
Is the jsonString empty or null? –  Douglas Drumond Nov 5 '13 at 6:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.