2011-05-12 83 views
0

我有這個ListView從Web上的JSON獲取其數據(圖像+文本)。 現在我有一個任務,使ListView無需互聯網連接即可訪問。我的想法是,當應用程序第一次運行互聯網時,通過從網絡上保存JSON數據,當它無法找到互聯網連接時,它將從持久存儲中獲取數據。Android:將JSON數據保存到SharedPreferences

有人可以幫我嗎?我還是一個初學者無法找到與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; 
     } 
    } 


} 

回答

1

SharedPreferences有保存JSON對象是,你必須設法將其轉換爲字符串沒有方法。然後,當你得到它時,你必須把這個字符串解析回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()); 

從字符串製作一個JSON是不是一個艱鉅的任務,使用的StringTokenizer。祝你好運!

+2

+1打我吧:) – MByD 2011-05-12 12:44:03

+0

你能告訴我一個我上面的代碼的例子嗎? thx – hectichavana 2011-05-12 14:57:20

+0

我會將它添加到我上面的答案中。 – Egor 2011-05-12 15:29:41