2014-01-30 5 views
5

listview의 JSON 데이터를 구문 분석하여 오프라인으로 사용할 수있게하려고합니다. 전화가 오프라인 상태 일 때 데이터를 볼 수 있도록 JSON 데이터를 전화에 저장하는 방법이 있습니까?오프라인에서 Json 데이터를 캐시 할 수 있습니까?

예를 아는 사람이 있습니까?

EDIT 이제 작동합니다

public class MainActivity extends ListActivity { 


    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     new TheTask().execute(); 
    } 

    class TheTask extends AsyncTask<Void, Void, JSONArray> { 
     InputStream is = null; 
     String result = ""; 
     JSONArray jArray = null; 

     ProgressDialog pd; 

     @Override 
     protected void onPostExecute(JSONArray result) { 
      super.onPostExecute(result); 
      pd.dismiss(); 
      ArrayList<String> list= new ArrayList<String>(); 
      try { 
       for(int i=0;i<result.length();i++) { 

        JSONObject jb = result.getJSONObject(i) ; 
        String name = jb.getString("name")+" "+jb.getString("Art"); 
        list.add(name); 
       } 
      } catch(Exception e) { 
       e.printStackTrace(); 
      } 
      setListAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, list)); 
     } 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pd = ProgressDialog.show(MainActivity.this, "State", 
        "Loading...", true); 
     } 

     @Override 
     protected JSONArray doInBackground(Void... arg0) { 
      ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 

       try { 
        HttpClient httpclient = new DefaultHttpClient(); 
        HttpPost httppost = new HttpPost("***"); 
        HttpResponse response = httpclient.execute(httppost); 
        HttpEntity entity = response.getEntity(); 
        is = entity.getContent(); 
       } catch (Exception e) { 
        Log.e("log_tag", "Error in http connection " + e.toString()); 
       } 

       // Convert response to string 
       try { 
        BufferedReader reader = new BufferedReader(new InputStreamReader(
          is, "iso-8859-1"), 8); 
        StringBuilder sb = new StringBuilder(); 
        String line = null; 
        while ((line = reader.readLine()) != null) { 
         sb.append(line + "\n"); 
        } 
        is.close(); 
        result = sb.toString(); 
        writeToFile(result); 
       } catch (Exception e) { 
        Log.e("log_tag", "Error converting result " + e.toString()); 
       } 

       try { 
        jArray = new JSONArray(result); 
       } catch (JSONException e) { 
        Log.e("log_tag", "Error parsing data " + e.toString()); 
       } 

       try { 
        jArray = new JSONArray(readFromFile()); 
       } catch (JSONException e) { 
        Log.e("log_tag", "Error parsing data " + e.toString()); 
       } 

      return jArray; 
     } 
    } 

    private void writeToFile(String data) { 
     try { 
      OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("config.txt", Context.MODE_PRIVATE)); 
      outputStreamWriter.write(data); 
      outputStreamWriter.close(); 
     } 
     catch (IOException e) { 
      Log.e("Exception", "File write failed: " + e.toString()); 
     } 
    } 

    private String readFromFile() { 

     String ret = ""; 

     try { 
      InputStream inputStream = openFileInput("config.txt"); 

      if (inputStream != null) { 
       InputStreamReader inputStreamReader = new InputStreamReader(inputStream); 
       BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 
       String receiveString = ""; 
       StringBuilder stringBuilder = new StringBuilder(); 

       while ((receiveString = bufferedReader.readLine()) != null) { 
        stringBuilder.append(receiveString); 
       } 

       inputStream.close(); 
       ret = stringBuilder.toString(); 
      } 
     } catch (FileNotFoundException e) { 
      Log.e("login activity", "File not found: " + e.toString()); 
     } catch (IOException e) { 
      Log.e("login activity", "Can not read file: " + e.toString()); 
     } 

     return ret; 
    } 
} 
+4

당신을 검색하려면 데이터

new AppPreference().setGeneralSettings(appGeneralSettings).commit(); 

을 저장하려면 그것을 전화 데이터베이스에 저장할 수 있습니다. 그것을 검색하십시오. –

답변

14

두 가지 방법이있다. 데이터베이스를 만들고 거기에 모든 데이터를 저장하고 원할 때 다시 검색하십시오. 또는 가지고있는 데이터가 많지 않고 데이터베이스를 다루지 않으려는 경우 json 문자열을 메모리 카드의 텍스트 파일에 쓰고 나중에 오프라인 일 때 읽을 수 있습니다.

두 번째 경우에는 온라인에 갈 때마다 웹 서비스에서 동일한 json을 검색하고 이전 json에 기록 할 수 있습니다. 이 방법을 사용하면 최신 json을 장치에 저장했는지 확인할 수 있습니다.

+0

JSON에 따라 (항목 수가 두 개인 경우) @ user3241084는 ['SharedPreferences'] (http://developer.android.com/reference/android/content/SharedPreferences.html)를 사용할 수 있습니다. –

+1

@YordanLyubenov 사용자가 JSON 개체를 프로그래밍 할 때 오프라인으로 저장할 때 JSON 개체를 프로그래밍 방식으로 저장하려고한다고 가정 할 때 몇 가지 항목 일뿐입니다. – osayilgan

+0

내 코드에 어떻게 추가 할 수 있습니까? 방금 시도했지만 아무 것도 일하지 않았습니까? – user3241084

0

일단 데이터를 다운로드하면 데이터베이스 또는 원하는 시스템을 사용하여 모바일에 데이터를 유지할 수 있습니다.

당신은 여기에 다른 옵션을 확인할 수 있습니다 data-storage

0

당신은 당신의 SharedPreferences의 문자열로 그 두 가지 방법이 개 가게 당신에게 JSON 파일을 사용하고 다시 검색 할 수 있습니다

public String getStringProperty(String key) { 
    sharedPreferences = context.getSharedPreferences("preferences", Activity.MODE_PRIVATE); 
    String res = null; 
    if (sharedPreferences != null) { 
     res = sharedPreferences.getString(key, null); 
    } 
    return res; 
} 

public void setStringProperty(String key, String value) { 
    sharedPreferences = context.getSharedPreferences("preferences", Activity.MODE_PRIVATE); 
    if (sharedPreferences != null) { 
     SharedPreferences.Editor editor = sharedPreferences.edit(); 
     editor.putString(key, value); 
     editor.commit(); 
     CupsLog.i(TAG, "Set " + key + " property = " + value); 
    } 
} 

그냥에 setStringProperty("json", "yourJsonString")를 사용 검색하고 저장할 getStringProperty("json")을 저장하십시오.

0

SharedPreferences를 사용하면 sqlite를 준비해야합니다 (물론 데이터베이스 구조가없는 경우). 캐싱과 인터넷에서 가져온 데이터 저장을 위해 나는 robospice : https://github.com/octo-online/robospice을 추천합니다. 사용하기 쉽고 매우 잘 작성된 라이브러리이며, 인터넷에서 데이터를 다운로드하거나 장기간 실행해야 할 때마다 사용해야합니다.

2

이 클래스는 나중에 검색 할 키가있는 파일의 문자열을 캐시하는 데 도움이됩니다. 문자열은 json 문자열이 될 수 있으며 키는 요청한 URL 일 수 있으며 post 메소드를 사용하는 경우 url의 식별자도 될 수 있습니다.

public class CacheHelper { 

static int cacheLifeHour = 7 * 24; 

public static String getCacheDirectory(Context context){ 

    return context.getCacheDir().getPath(); 
} 

public static void save(Context context, String key, String value) { 

    try { 

     key = URLEncoder.encode(key, "UTF-8"); 

     File cache = new File(getCacheDirectory(context) + "/" + key + ".srl"); 

     ObjectOutput out = new ObjectOutputStream(new FileOutputStream(cache)); 
     out.writeUTF(value); 
     out.close(); 
    } catch (Exception e) { 

     e.printStackTrace(); 
    } 
} 

public static void save(Context context, String key, String value, String identifier) { 

    save(context, key + identifier, value); 
} 

public static String retrieve(Context context, String key, String identifier) { 

    return retrieve(context, key + identifier); 
} 


public static String retrieve(Context context, String key) { 

    try { 

     key = URLEncoder.encode(key, "UTF-8"); 

     File cache = new File(getCacheDirectory(context) + "/" + key + ".srl"); 

     if (cache.exists()) { 

      Date lastModDate = new Date(cache.lastModified()); 
      Date now = new Date(); 

      long diffInMillisec = now.getTime() - lastModDate.getTime(); 
      long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMillisec); 

      diffInSec /= 60; 
      diffInSec /= 60; 
      long hours = diffInSec % 24; 

      if (hours > cacheLifeHour) { 
       cache.delete(); 
       return ""; 
      } 

      ObjectInputStream in = new ObjectInputStream(new FileInputStream(cache)); 
      String value = in.readUTF(); 
      in.close(); 

      return value; 
     } 

    } catch (Exception e) { 

     e.printStackTrace(); 
    } 

    return ""; 
} 
} 

사용 방법 :

String string = "cache me!"; 
String key = "cache1"; 
CacheHelper.save(context, key, string); 
String getCache = CacheHelper.retrieve(context, key); // will return 'cache me!' 
+1

이 수업을 어떻게 사용합니까? –

+0

@BhoomiZalavadiya 나는 대답을 편집했고, 이제 사용할 준비가되었습니다! 발생할 수있는 버그를 알려주십시오. –

0

어떻게 오프라인으로 사용할 수 JSON 데이터를 캐시?

gson을 사용하면 JSON 데이터를보다 쉽게 ​​파싱 할 수 있습니다. build.gradle 파일에이 종속성을 추가하십시오.

compile 'com.google.code.gson:gson:2.8.0' 

그런 다음 POJO 클래스를 만들어 JSON 데이터를 구문 분석하십시오.

예 POJO 클래스 :

public class AppGeneralSettings { 
    @SerializedName("key1") 
String data; 


    public String getData() { 
     return data; 
    } 

} 
  • 인터넷 사용으로

    AppGeneralSettings data=new Gson().fromJson(jsonString, AppGeneralSettings.class); 
    

그런 다음 JSON을 저장하고 검색하는 헬퍼 클래스를 추가이 조각

를 JSON 문자열을 구문 분석하려면 환경 설정과의 데이터 교환.

예 : 도우미 클래스를 저장하는 데이터

public class AppPreference { 
    private static final String FILE_NAME = BuildConfig.APPLICATION_ID + ".apppreference"; 
    private static final String APP_GENERAL_SETTINGS = "app_general_settings"; 
    private final SharedPreferences preferences; 

    public AppPreference(Context context) { 
     preferences = context.getSharedPreferences(FILE_NAME, MODE_PRIVATE); 
    } 

    public SharedPreferences.Editor setGeneralSettings(AppGeneralSettings appGeneralSettings) { 
     return preferences.edit().putString(APP_GENERAL_SETTINGS, new Gson().toJson(appGeneralSettings)); 
    } 

    public AppGeneralSettings getGeneralSettings() { 
     return new Gson().fromJson(preferences.getString(APP_GENERAL_SETTINGS, "{}"), AppGeneralSettings.class); 
    } 
} 

데이터

AppGeneralSettings appGeneralSettings = new AppPreference().getGeneralSettings(); 
+0

gson을 사용하는 것이 좋습니다. 또한 sharedPreferences도 작동 할 수 있지만 json 결과가 큰 경우 다른 파일에 각각 저장하는 것이 좋습니다. –

관련 문제