安卓:保存JSON数据到共享preferences [英] Android: Save JSON data into SharedPreferences

查看:118
本文介绍了安卓:保存JSON数据到共享preferences的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的ListView其获取在网络上从JSON的数据(图像+文字)。
现在我有一个任务,使ListView控件是没有互联网连接访问。我的想法是由当应用程序运行在第一次与互联网,当它无法找到互联网连接它会从持久性存储获取数据的Web保存JSON数据。

任何人可以帮助我呢?我还是一个初学者无法找到共享的JSON preferences的例子。
非常感谢

 公共类ProjectsList延伸活动{
    / **当第一次创建活动调用。 * /
    // ListView控件,将举行我们的项目引用回的main.xml
    ListView的lstTest;    //数组适配器,将持有我们的ArrayList和显示在ListView中的项目
    ProjectAdapter arrayAdapter;
    //列表将承载我们的项目,让我们修改该阵列适配器
    ArrayList的<项目> prjcts = NULL;
    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.projects_list);        //初始化的ListView
        lstTest =(ListView控件)findViewById(R.id.lstText);         //初始化我们的ArrayList
        prjcts =新的ArrayList<项目>();
        //初始化我们的阵列适配器注意它引用listitems.xml布局        arrayAdapter =新ProjectAdapter(ProjectsList.this,R.layout.listitems,prjcts,ProjectsList.this);        //设置上述适配器作为首选适配器我们的名单
        //lstTest.setAdapter(arrayAdapter);            lstTest.setAdapter(arrayAdapter);
            如果(isOnline())
            {
        //实例化Web服务类与他URL中的Web服务不是说你必须通过
        WebService的web服务=新的WebService(http://liebenwald.spendino.net/admanager/dev/android/projects.json);
        //传递参数如果需要的话,如果不是则通过如下一个虚构的
        地图<字符串,字符串> PARAMS =新的HashMap<字符串,字符串>();
        params.put(变种,);        //从服务器获取JSON响应的,在哪里的方法名称通常会去,如果需要的例子
        // webService.webGet(getMoreAllerts,则params);
        字符串的响应= webService.webGet(,则params);        尝试
        {
            //解析响应到我们的对象
            键入collectionType =新TypeToken< ArrayList的<项目及GT;>(){}的getType()。            // JSON期待一个列表,这样不能从lstart使用我们的ArrayList
            清单<项目> 。LST =新GSON()fromJson(响应,collectionType);
            //现在我们有一个列表,可以将其添加到将举行我们的项目ArrayList中。
            对于(项目L:LST)
            {
                prjcts.add(升);
                ConstantData.projectsList.add(升);
            }            //既然我们已经修改了ArrayList的,我们现在需要通知适配器
            //它的数据已经更改,因此,它更新UI
            arrayAdapter.notifyDataSetChanged();
        }
        赶上(例外五)
        {
            Log.d(错误,e.getMessage());
        }
       }        lstTest.setOnItemClickListener(新OnItemClickListener(){
            公共无效onItemClick(适配器视图<>母公司,观景,INT位置,长的id){
                意图护理=新意图(ProjectsList.this,ProjectDetail.class);
                care.putExtra(spendino.de.ProjectDetail.position位置);
                startActivity(保健);
            }
        });
    }
    @覆盖
    公共无效的onDestroy()
    {
        yAdapter.imageLoader.stopThread();
        lstTest.setAdapter(NULL);
        super.onDestroy();
    }    保护布尔isOnline(){
        ConnectivityManager厘米=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetInfo的的NetworkInfo = cm.getActiveNetworkInfo();
        如果(NetInfo的= NULL&放大器;!&安培; netInfo.isConnected()){
            返回true;
        }其他{
             AlertDialog.Builder alertbox =新AlertDialog.Builder(本);
             alertbox.setTitle(spendino Helfomat);
             alertbox.setMessage(请检查您的网络连接);
             alertbox.setPositiveButton(OK,新DialogInterface.OnClickListener(){
                 公共无效的onClick(DialogInterface对话,诠释的id){
                      //Main.this.finish();
                 }
             });
             alertbox.show();
            返回false;
        }
    }
}


解决方案

共享preferences有救了一个JSON对象,你必须设法将其转换为字符串没有方法。然后让当它必须解析字符串返回JSON。祝你好运!

JSON为String:

 的JSONObject O =新的JSONObject(data.trim());
                字符串名称= o.getString(Constants.NAME);
                长日期= o.getLong(Constants.DATE);
                字符串MES = o.getString(Constants.MESSAGE);                StringBuilder的BUF =新的StringBuilder(text.getText());                。buf.append(名称).append(().append(dfTime.format(新日期(日期)))追加()\\ n)追加(MES).append(\\ n);                text.setText(buf.toString());

从字符串制作一个JSON是不是一个艰巨的任务,使用的StringTokenizer。祝你好运!

I have this ListView which fetches its data (image+text) from JSON on the web. Now I have a task to make the ListView is accessible without internet connection. My idea is by saving the JSON data from the web when the app is run for the first time with internet, and when it can't find internet connection it will get the data from the persistent Storage.

Can anybody help me with this? I'm still a beginner can't find the example of SharedPreferences with JSON. Thanks a lot

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 has no methods for saving a JSON object as is, you must try to convert it to a String. Then when getting it you must parse this String back to JSON. Good luck!

JSON to 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());

Making a JSON from a String is not a harder task, use StringTokenizer. Good luck!

这篇关于安卓:保存JSON数据到共享preferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆