繁体   English   中英

Android:将JSON数据保存到SharedPreferences中

[英]Android: Save JSON data into SharedPreferences

我有这个ListView,它从Web上的JSON获取其数据(图像+文本)。 现在,我有一个任务,使ListView在没有互联网连接的情况下也可以访问。 我的想法是,当应用程序首次通过Internet运行时,通过从Web保存JSON数据;当它找不到Internet连接时,它将从持久性存储中获取数据。

有人可以帮我吗? 我仍然是一个初学者,找不到JSON的SharedPreferences的示例。 非常感谢

public class ProjectsList extends Activity {
    /** Called when the activity is first created. */
    //ListView that will hold our items references back to main.xml
    ListView lstTest;

    //Array Adapter that will hold our ArrayList and display the items on the ListView
    ProjectAdapter arrayAdapter;


    //List that will  host our items and allow us to modify that array adapter
    ArrayList<Project> prjcts=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.projects_list);

        //Initialize ListView
        lstTest= (ListView)findViewById(R.id.lstText);

         //Initialize our ArrayList
        prjcts = new ArrayList<Project>();
        //Initialize our array adapter notice how it references the listitems.xml layout

        arrayAdapter = new ProjectAdapter(ProjectsList.this, R.layout.listitems,prjcts,ProjectsList.this);

        //Set the above adapter as the adapter of choice for our list
        //lstTest.setAdapter(arrayAdapter);



            lstTest.setAdapter(arrayAdapter);
            if (isOnline())
            {
        //Instantiate the Web Service Class with he URL of the web service not that you must pass
        WebService webService = new WebService("http://liebenwald.spendino.net/admanager/dev/android/projects.json");


        //Pass the parameters if needed , if not then pass dummy one as follows
        Map<String, String> params = new HashMap<String, String>();
        params.put("var", "");

        //Get JSON response from server the "" are where the method name would normally go if needed example
        // webService.webGet("getMoreAllerts", params);
        String response = webService.webGet("", params);

        try
        {
            //Parse Response into our object
            Type collectionType = new TypeToken<ArrayList<Project>>(){}.getType();

            //JSON expects an list so can't use our ArrayList from the lstart
            List<Project> lst= new Gson().fromJson(response, collectionType);


            //Now that we have that list lets add it to the ArrayList which will hold our items.
            for(Project l : lst)
            {
                prjcts.add(l);
                ConstantData.projectsList.add(l);
            }

            //Since we've modified the arrayList we now need to notify the adapter that
            //its data has changed so that it updates the UI
            arrayAdapter.notifyDataSetChanged();
        }
        catch(Exception e)
        {
            Log.d("Error: ", e.getMessage());
        }
       }

        lstTest.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              
                Intent care = new Intent(ProjectsList.this, ProjectDetail.class);
                care.putExtra("spendino.de.ProjectDetail.position",position);
                startActivity(care);
            }
        });




    }
    @Override
    public void onDestroy()
    {
        yAdapter.imageLoader.stopThread();
        lstTest.setAdapter(null);
        super.onDestroy();
    }

    protected boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected()) {
            return true;
        } else {
             AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
             alertbox.setTitle("spendino Helfomat");
             alertbox.setMessage ("Please check your internet connection");
             alertbox.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int id) {
                      //Main.this.finish();
                 }
             });
             alertbox.show();
            return false;
        }
    }


}

SharedPreferences没有用于按原样保存JSON对象的方法,您必须尝试将其转换为String。 然后,在获取它时,必须将此字符串解析回JSON。 祝好运!

JSON转换为String:

JSONObject o = new JSONObject(data.trim());
                String name = o.getString(Constants.NAME);
                long date = o.getLong(Constants.DATE);
                String mes = o.getString(Constants.MESSAGE);

                StringBuilder buf = new StringBuilder(text.getText());

                buf.append(name).append(" (").append(dfTime.format(new Date(date))).append(")\n").append(mes).append("\n");

                text.setText(buf.toString());

使用String制作JSON并非难事,请使用StringTokenizer。 祝好运!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM