2017-01-03 2 views
0

JSONデータを解析するアンドロイドアプリケーションを初めて作成しました。 しかし、JSON解析に関するエラーが発生しました。私は問題をグーグルで試してみましたが、ほとんどのソリューションは私のためには機能しませんでした。ここでAndroid JSON解析 - エラー0文字の入力終了

は私のコードです:

MainActivity.java

package com.example.jsonparser; 

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.app.ProgressDialog; 
import android.os.AsyncTask; 
import android.util.Log; 
import android.widget.ListAdapter; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
import android.widget.Toast; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.util.ArrayList; 
import java.util.HashMap; 

public class MainActivity extends AppCompatActivity { 

    private String TAG = MainActivity.class.getSimpleName(); 

    private ProgressDialog pDialog; 
    private ListView lv; 

    // URL to get contacts JSON 
    private static String url = "http://pastebin.com/raw/79D93HR4"; 

    ArrayList<HashMap<String, String>> itemList; 

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

     itemList = new ArrayList<>(); 

     lv = (ListView) findViewById(R.id.list); 

     new GetItems().execute(); 
    } 

    /** 
    * Async task class to get json by making HTTP call 
    */ 
    private class GetItems extends AsyncTask<Void, Void, Void> { 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      // Showing progress dialog 
      pDialog = new ProgressDialog(MainActivity.this); 
      pDialog.setMessage("Please wait..."); 
      pDialog.setCancelable(false); 
      pDialog.show(); 

     } 

     @Override 
     protected Void doInBackground(Void... arg0) { 
      HttpHandler sh = new HttpHandler(); 

      // Making a request to url and getting response 
      String jsonStr = sh.makeServiceCall(url); 

      Log.e(TAG, "Response from url: " + jsonStr); 

      if (jsonStr != null) { 
       try { 
        //JSONObject jsonObj = new JSONObject(jsonStr); 

        // Getting JSON Array node 
        JSONArray items = new JSONArray(""); 

        // looping through All Contacts 
        for (int i = 0; i < items.length(); i++) { 
         JSONObject c = items.getJSONObject(i); 

         String ItemCode = c.getString("ItemCode"); 
         String ItemName = c.getString("ItemName"); 

         // tmp hash map for single item 
         HashMap<String, String> item = new HashMap<>(); 

         // adding each child node to HashMap key => value 
         item.put("ItemCode", ItemCode); 
         item.put("ItemName", ItemName); 

         // adding item to item list 
         itemList.add(item); 
        } 

       } catch (final JSONException e) { 
        Log.e(TAG, "Json parsing error: " + e.getMessage()); 
        runOnUiThread(new Runnable() { 
         @Override 
         public void run() { 
          Toast.makeText(getApplicationContext(), 
            "Json parsing error: " + e.getMessage(), 
            Toast.LENGTH_LONG) 
            .show(); 
         } 
        }); 

       } 
      } else { 
       Log.e(TAG, "Couldn't get json from server."); 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         Toast.makeText(getApplicationContext(), 
           "Couldn't get json from server. Check LogCat for possible errors!", 
           Toast.LENGTH_LONG) 
           .show(); 
        } 
       }); 

      } 

      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      super.onPostExecute(result); 
      // Dismiss the progress dialog 
      if (pDialog.isShowing()) 
       pDialog.dismiss(); 
      /** 
      * Updating parsed JSON data into ListView 
      * */ 
      ListAdapter adapter = new SimpleAdapter(
        MainActivity.this, itemList, 
        R.layout.list_item, new String[]{"ItemCode", "ItemName"}, new int[]{R.id.ItemCode, 
        R.id.ItemName}); 

      lv.setAdapter(adapter); 
     } 

    } 
} 

HttpHandler.java

package com.example.jsonparser; 

/** 
* Created by Me on 1/3/2017. 
*/ 
import android.util.Log; 

import java.io.BufferedInputStream; 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.ProtocolException; 
import java.net.URL; 

public class HttpHandler { 

    private static final String TAG = HttpHandler.class.getSimpleName(); 

    public HttpHandler() { 
    } 

    public String makeServiceCall(String reqUrl) { 
     String response = null; 
     try { 
      URL url = new URL(reqUrl); 
      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      conn.setRequestMethod("GET"); 
      // read the response 
      InputStream in = new BufferedInputStream(conn.getInputStream()); 
      response = convertStreamToString(in); 
     } catch (MalformedURLException e) { 
      Log.e(TAG, "MalformedURLException: " + e.getMessage()); 
     } catch (ProtocolException e) { 
      Log.e(TAG, "ProtocolException: " + e.getMessage()); 
     } catch (IOException e) { 
      Log.e(TAG, "IOException: " + e.getMessage()); 
     } catch (Exception e) { 
      Log.e(TAG, "Exception: " + e.getMessage()); 
     } 
     return response; 
    } 

    private String convertStreamToString(InputStream is) { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
     StringBuilder sb = new StringBuilder(); 

     String line; 
     try { 
      while ((line = reader.readLine()) != null) { 
       sb.append(line).append('\n'); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       is.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     return sb.toString(); 
    } 
} 

そして、ここでは、エラーコードは次のとおりです。

01-04 00:13:05.366 10069-10112/com.example.jsonparser E/MainActivity: Response from url: [{"ItemCode":"C0100001 ","ItemName":"UBNT CRM-P-CRM Point","LocationCode":null,"ViewBy":null,"SearchDate":null,"CutOffDate":"\/Date(-62135596800000)\/","CurrentDate":"\/Date(-62135596800000)\/"},{"ItemCode":"C0100002 ","ItemName":"UBNT ETH-SP-Ethernet Surge Protector","LocationCode":null,"ViewBy":null,"SearchDate":null,"CutOffDate":"\/Date(-62135596800000)\/","CurrentDate":"\/Date(-62135596800000)\/"}] 
01-04 00:13:05.367 10069-10112/com.example.jsonparser E/MainActivity: Json parsing error: End of input at character 0 of 

私は間違っていますか?

答えて

2

JSONArrayにはJSON文字列が必要です。 JSONArrayであなたのJSONを渡すあなたが `新しいJSONArray(jsonStr)を使用する必要があります意味

JSONArray items = new JSONArray(jsonStr); 
+0

ありがとう!できます :) –

0
   JSONArray items = new JSONArray(""); 

jsonから変換するには、空の文字列を渡しています。文字列にデータがないため、無効な入力で文字0に失敗します(入力は有効なJSONではありません)。

+2

を初期化;' – Zircon

関連する問題