Android在Sharedpreferences中保存JSON响应

时间:2016-02-16 07:48:33

标签: android json sharedpreferences

我在字符串数据类型中有json响应。我想将此文本保存到sharedpreferences,但它既不会给我错误也不会将其保存到sharedpreferences。 但是当我尝试检索它时,如果我获取它的长度,它会给我空值和空指针异常。我的JSON REPONE在

http://www.professionalhub.pk/recipe/webServices/recipe1.php

1 个答案:

答案 0 :(得分:1)

将此类用于文件目的!希望它能帮到你!

 public class MyJSON {

        static String fileName = "myBlog.json";

        public static void saveData(Context context, String mJsonResponse) {
            try {
                FileWriter file = new FileWriter(context.getFilesDir().getPath() + "/" + fileName);
                file.write(mJsonResponse);
                file.flush();
                file.close();
            } catch (IOException e) {
                Log.e("TAG", "Error in Writing: " + e.getLocalizedMessage());
            }
        }

        public static String getData(Context context) {
            try {
                File f = new File(context.getFilesDir().getPath() + "/" + fileName);
                //check whether file exists
                FileInputStream is = new FileInputStream(f);
                int size = is.available();
                byte[] buffer = new byte[size];
                is.read(buffer);
                is.close();
                return new String(buffer);
            } catch (IOException e) {
                Log.e("TAG", "Error in Reading: " + e.getLocalizedMessage());
                return null;
            }
        }
    }