java - 从共享首选项加载数据(JSON 数组)

标签 java android arrays json sharedpreferences

我有 4 个数组,需要能够保存并加载到共享首选项:

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

以下是我的完整 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;
    }

}

运行时,不会抛出任何错误。我遇到的问题是如何将数据检索回 JSON 数组,然后返回数组,以便我可以在应用程序的其他部分操作数据。

最佳答案

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

使用上面的方法,通过将key传入方法来获取数据

关于java - 从共享首选项加载数据(JSON 数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19781848/

相关文章:

android - 如何访问android中的电池剩余时间

c++ - 使用 unique_ptr 管理三维数组

javascript - Highcharts 使用数组显示每个气泡点的附加信息

java - 使用 Java 读取包含数组的文件

javax.persistence.NoResultException : No entity found for query

java - 用于查找超过 3 小时的条目的 Hibernate HQL 查询

java - 我可以使用父对象调用子类方法吗?

java - 两个角色的 SecurityConfig

android - 使用表示资源名称的变量访问 R.string 的内容

android - 如何在 Honeycomb 上以编程方式关闭 ActionMode 菜单?