-2

how to fetch data from local json file?

As per the above link. I tried to fetch data from json file which is stored in internal memory. But I got system error which fetching data from internal storage(json file). Please help on it.

               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; 
           }}

Error is..W/System.err(407): org.json.JSONException: Value [{"ImageDesc":"Img1 Img1Img1 ","ImageId":"12","ImageName":"Img1","ImageUrl":"http://192.168.10.200/dinesh/images/pro1.jpg"},{"ImageDesc":"Img13 Img13 Img13Img13 ","ImageId":"13","ImageName":"Img13","ImageUrl":"http://192.168.10.200/dinesh/images/pro2.jpg"},{"ImageDesc":"Img14 Img14 Img14 Img14 Img14 ","ImageId":"14","ImageName":"Img14","ImageUrl":"http://192.168.10.200/dinesh/images/pro3.jpg.jpg"},null] of type org.json.JSONArray cannot be converted to 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): at android.view.View.performClick(View.java:2485) 07-31 11:57:11.814: W/System.err(407): at android.view.View$PerformClick.run(View.java:9080) 07-31 11:57:11.814: W/System.err(407): at android.os.Handler.handleCallback(Handler.java:587) 07-31 11:57:11.824: W/System.err(407): at android.os.Handler.dispatchMessage(Handler.java:92) 07-31 11:57:11.824: W/System.err(407): at android.os.Looper.loop(Looper.java:123) 07-31 11:57:11.824: W/System.err(407): at 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)

I need to fetch data from json file which is stored in internal storage and display it in list view. Plese help on it.

Sample JSON file is.. {"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"},]}

Community
  • 1
  • 1
user3879110
  • 17
  • 1
  • 7

2 Answers2

0

This piece of code is working perfectly fine on the provided sample 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();
       }
    }
}

This code produce the output

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

What json library you are using. I hope, this one

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

Prashant
  • 190
  • 1
  • 9
0

Try this, you should be able to get it working.

                    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();
                    }
User12111111
  • 1,179
  • 1
  • 19
  • 41