如何从本地json文件中获取和显示数据?

时间:2014-07-31 06:51:34

标签: android json android-activity offline-caching

how to fetch data from local json file?

根据以上链接。我试图从存储在内部存储器中的json文件中获取数据。但我收到系统错误,从内部存储(json文件)获取数据。请帮帮忙。

               public class MainActivity extends Activity implements OnClickListener {
      private static final String TAG = "MainActivity";
       Button b1,b2;
        TextView t1;

    JSONArray jsonBranchArray;
        @Override
         public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    if (isNetworkAvailable()) {
        new PrefetchData().execute();
    } else { 
        Toast.makeText(MainActivity.this,
                "No Internet Connection Available", Toast.LENGTH_LONG)
                .show();
    }


    b1 = (Button) findViewById(R.id.button1);


    b1.setOnClickListener(this); 

             }

        @Override
        public void onClick(
                View v) {

            if (v == b1) {

                WriteToFile();
                readResponse();

            }
        }
        private boolean isNetworkAvailable() {
            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = connectivityManager
                    .getActiveNetworkInfo();
            if (activeNetworkInfo != null && activeNetworkInfo.isConnected())
            {
                return true;
            }
            return false;

        }

        private class PrefetchData extends AsyncTask<Void, Void, Void> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }
            @Override
            protected Void doInBackground(Void... arg0) {

                AppUtils appUtils = new AppUtils();

                String jsonResultStr = appUtils
                        .getDataFromUrl("URL for json");


                Log.d(TAG, "JSON content  ::: "
                        + jsonResultStr);
                if (jsonResultStr != null) {

                    try {

                         JSONObject jsObj = new JSONObject(jsonResultStr);


                         jsonBranchArray = jsObj
                                .getJSONArray("ImageData");

                         Log.d(TAG, "JSONArray  content  ::: "
                                    + jsonBranchArray);

                        for (int j = 0; j < jsonBranchArray.length(); j++) {

                            JSONObject objBranchJson = (JSONObject) jsonBranchArray
                                    .get(j);
                            img_id = objBranchJson.getString("ImageId");
                            img_name = objBranchJson.getString("ImageName");
                            img_desc = objBranchJson.getString("ImageDesc");
                            img_url = objBranchJson.getString("ImageUrl");

                        }
                    }

                    catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }

            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                Toast.makeText(MainActivity.this,
                        "Json values saved", Toast.LENGTH_LONG)
                        .show();
            }

        }

        @SuppressWarnings("deprecation")
        public void WriteToFile() {


            try { 

                 final String TESTSTRING =jsonBranchArray.toString();

                   FileOutputStream fOut = openFileOutput("samplefile.json",
                                                                        MODE_WORLD_READABLE);
                   OutputStreamWriter osw = new OutputStreamWriter(fOut); 

                   // Write the string to the file
                   osw.write(TESTSTRING);

                   /* ensure that everything is
                    * really written out and close */
                   osw.flush();
                   osw.close();

            //Reading the file back...

                   /* We have to use the openFileInput()-method
                    * the ActivityContext provides.
                    * Again for security reasons with
                    * openFileInput(...) */

                    FileInputStream fIn = openFileInput("samplefile.json");
                    InputStreamReader isr = new InputStreamReader(fIn);

                    /* Prepare a char-Array that will
                     * hold the chars we read back in. */
                    char[] inputBuffer = new char[TESTSTRING.length()];

                    // Fill the Buffer with data from the file
                    isr.read(inputBuffer);

                    // Transform the chars to a String
                    String readString = new String(inputBuffer);

                    // Check if we read back the same chars that we had written out
                    boolean isTheSame = TESTSTRING.equals(readString);

                    Log.i("File Reading stuff", "success = " + isTheSame);

                } catch (IOException ioe) 
                  {ioe.printStackTrace();}

        }

                               public JSONObject readResponse() {
               InputStream inputStream = null;
           try {
                  inputStream = this.openFileInput("samplefile.json");
               } catch (IOException e1) {
               e1.printStackTrace();
            }
              JSONObject jsonObject = null;
              if (inputStream != null) {
                      BufferedReader reader = new BufferedReader(new InputStreamReader(
            inputStream));
               StringBuffer buffer = new StringBuffer();
                  String statement;
               try {
               while ((statement = reader.readLine()) != null) {
            if (statement.trim().length() > 0) {
                buffer.append(statement);

                if (img_id=="12"){
                    System.out.println("ID can able to fetch using this method");
                    Log.i("File Reading stuff", "success");
                }
            }
                }
             } catch (IOException e1) { // TODO Auto-generated catch block
        e1.printStackTrace();
            }
             if (buffer.length() > 0) {
        try {
            jsonObject = new JSONObject(buffer.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
                  }
         }
          return (JSONObject) jsonObject; 
           }}

错误是...... W / System.err(407):org.json.JSONException:值[{&#34; ImageDesc&#34;:&#34; Img1 Img1Img1&#34;,&#34; ImageId& #34;:&#34; 12&#34;&#34; ImageName&#34;:&#34; IMG1&#34;&#34;的ImageUrl&#34;:&#34; HTTP://192.168。 10.200 / dinesh / images / pro1.jpg&#34;},{&#34; ImageDesc&#34;:&#34; Img13 Img13 Img13Img13&#34;,&#34; ImageId&#34;:&#34; 13& #34;&#34; ImageName&#34;:&#34; Img13&#34;&#34;的ImageUrl&#34;:&#34; HTTP://192.168.10.200/dinesh/images/pro2.jpg& #34;},{&#34; ImageDesc&#34;:&#34; Img14 Img14 Img14 Img14 Img14&#34;,&#34; ImageId&#34;:&#34; 14&#34;,&#34 ; ImageName&#34;:&#34;看好你哦!&#34;&#34;的ImageUrl&#34;:&#34; HTTP://192.168.10.200/dinesh/images/pro3.jpg.jpg"},类型为org.json.JSONArray的null]无法转换为JSONObject 07-31 11:57:11.804:W / System.err(407):at org.json.JSON.typeMismatch(JSON.java:107) 07-31 11:57:11.804:W / System.err(407):at org.json.JSONObject。(JSONObject.java:158) 07-31 11:57:11.804:W / System.err(407):at org.json.JSONObject。(JSONObject.java:171) 07-31 11:57:11.804:W / System.err(407):at com.example.MainActivity.readResponse(MainActivity.java:310) 07-31 11:57:11.814:W / System.err(407):at com.example.MainActivity.onClick(MainActivity.java:111) 07-31 11:57:11.814:W / System.err(407):在android.view.View.performClick(View.java:2485) 07-31 11:57:11.814:W / System.err(407):在android.view.View $ PerformClick.run(View.java:9080) 07-31 11:57:11.814:W / System.err(407):在android.os.Handler.handleCallback(Handler.java:587) 07-31 11:57:11.824:W / System.err(407):在android.os.Handler.dispatchMessage(Handler.java:92) 07-31 11:57:11.824:W / System.err(407):在android.os.Looper.loop(Looper.java:123) 07-31 11:57:11.824:W / System.err(407):在android.app.ActivityThread.main(ActivityThread.java:3683) 07-31 11:57:11.824:W / System.err(407):at java.lang.reflect.Method.invokeNative(Native Method) 07-31 11:57:11.834:W / System.err(407):at java.lang.reflect.Method.invoke(Method.java:507) 07-31 11:57:11.834:W / System.err(407):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:839) 07-31 11:57:11.834:W / System.err(407):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 07-31 11:57:11.834:W / System.err(407):at dalvik.system.NativeStart.main(Native Method)

我需要从json文件中获取数据,该文件存储在内部存储中并在列表视图中显示。请帮忙。

示例JSON文件是.. {&#34; ImageData&#34;:[{&#34; ImageId&#34;:&#34; 12&#34;,&#34; ImageName&#34;:&# 34; Img1&#34;,&#34; ImageDesc&#34;:&#34; Img1 Img1Img1&#34;,&#34; ImageUrl&#34;:&#34; img_url / pro1.jpg&#34;}, {&#34;图像标识&#34;:&#34; 13&#34;&#34; ImageName&#34;:&#34; Img13&#34;&#34; ImageDesc&#34;:&#34; Img13 Img13 Img13Img13&#34;,&#34; ImageUrl&#34;:&#34; img_url / pro2.jpg&#34;},{&#34; ImageId&#34;:&#34; 14&#34;, &#34; ImageName&#34;:&#34; Img14&#34;,&#34; ImageDesc&#34;:&#34; Img14 Img14 Img14 Img14 Img14&#34;,&#34; ImageUrl&#34;: &#34; img_url / pro3.jpg.jpg&#34;},]}

2 个答案:

答案 0 :(得分:0)

这段代码在提供的示例json上运行得非常好:

package com.so.test.java;

import org.json.JSONArray;
import org.json.JSONObject;
/**
 * @author prashant
 *
 */
public class JsonParser {
    /**
     * @param args
     */
    public static void main(String[] args) {
        String sampleJson = "{\"ImageData\":[{\"ImageId\":\"12\",\"ImageName\":\"Img1\",\"ImageDesc\":\"Img1 Img1Img1 \",\"ImageUrl\":\"img_url/pro1.jpg\"},{\"ImageId\":\"13\",\"ImageName\":\"Img13\",\"ImageDesc\":\"Img13 Img13 Img13Img13 \",\"ImageUrl\":\"img_url/pro2.jpg\"},{\"ImageId\":\"14\",\"ImageName\":\"Img14\",\"ImageDesc\":\"Img14 Img14 Img14 Img14 Img14 \",\"ImageUrl\":\"img_url/pro3.jpg.jpg\"}]}";
        try {
            JSONObject rootObj = new JSONObject(sampleJson);
            JSONArray imageDataArr = rootObj.getJSONArray("ImageData");
            System.out.println("JSONArray  content  ::: "+ rootObj.toString());
           for (int j = 0; j < imageDataArr.length(); j++) {
               JSONObject imageDataObj = (JSONObject) imageDataArr.get(j);
               System.out.println(imageDataObj.getString("ImageId") + " " + imageDataObj.getString("ImageName"));
           }
       }catch(Exception e){
           e.printStackTrace();
       }
    }
}

此代码生成输出

JSONArray  content  ::: {"ImageData":[{"ImageId":"12","ImageName":"Img1","ImageUrl":"img_url/pro1.jpg","ImageDesc":"Img1 Img1Img1 "},{"ImageId":"13","ImageName":"Img13","ImageUrl":"img_url/pro2.jpg","ImageDesc":"Img13 Img13 Img13Img13 "},{"ImageId":"14","ImageName":"Img14","ImageUrl":"img_url/pro3.jpg.jpg","ImageDesc":"Img14 Img14 Img14 Img14 Img14 "}]}
12 Img1
13 Img13
14 Img14

您正在使用的json库。我希望,这一个

http://www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm

答案 1 :(得分:0)

试试这个,你应该能够让它运转起来。

                    try {
                        JSONObject jsonObject = new JSONObject(jsonstring);
                        Iterator keys = jsonObject.keys();
                        while(keys.hasNext()) {
                            Object next = keys.next();
                            String strKey = (String) next;
                            Object obj = jsonObject.get(strKey);
                            if(obj instanceof String) {
                               JSONObject jsonObject = new JSONObject((String)obj);
                               //do your stuff..
                            } else if(obj instanceof JSONObject) {
                               //do your stuff..
                               if(jsonObject.has("<KEY>")) {
                                  String value = jsonObject.getString("<KEY>"));
                               }
                            } else if(obj instanceof JSONArray) {
                                JSONArray jsonArray = (JSONArray) obj;
                                for(int j = 0; j < jsonArray.length(); j ++) {
                                    JSONObject jsonObject1 = jsonArray.getJSONObject(j);
                                    //do your stuff..
                                   if(jsonObject1.has("<KEY>")) {
                                      String value = jsonObject1.getString("<KEY>"));
                                   } .... and so on
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }