在TextView中显示文本并将其保存在缓存中?

时间:2018-05-08 08:04:03

标签: android android-intent android-activity

我从网址获取新闻数据作为JSONString。 JSONString包含新闻对象,我想获取标题和消息,并在TextView上显示它们。如何在TextView中显示标题和消息并将其保存在缓存中?

public class SEVData extends IntentService { 
    ...

    @Override 
    protected void onHandleIntent(@Nullable Intent intent) { 
        while (serviceIsRunning) { 
            int id_s = 0; 
            String url0 = "http://172.17.100.2/mham/sendapp.php?co>"+id_s;
            String newsData; 
            try { 
                URL url = new URL(url0); 
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
                InputStream in = new BufferedInputStream(urlConnection.getInputStream()); 
                newsData = getJSONString(in);
                in.close(); 
                JSONObject jsonRootObject = new JSONObject(newsData); 
                JSONArray jsonArray = jsonRootObject.optJSONArray("date"); 
                for (int i = 0; i < jsonArray.length(); i++) { 
                    JSONObject jsonObject = jsonArray.getJSONObject(i); 
                    String id= jsonObject.optString("id"); 
                    String title = jsonObject.optString("title"); 
                    String message = jsonObject.optString("message");
                } 
            } // catch unrelated
        } 
    } 
}

1 个答案:

答案 0 :(得分:0)

您可以在for循环中添加如此的SharedPreference键:

SharedPreferences.Editor editor = getActivity().getPreferences(Context.MODE_PRIVATE).edit();
for (int i = 0; i < jsonArray.length(); i++) { 
    JSONObject jsonObject = jsonArray.getJSONObject(i); 
    String id= jsonObject.optString("id"); 
    String title = jsonObject.optString("title"); 
    String message = jsonObject.optString("message");
    editor.putString(title, message);
    editor.apply();
}