2016-04-03 16 views
1

ich ein Json Parser-Klasse haben, die wie folgt aussieht: public class JSONParser {Android Json Parse gibt nichts

static InputStream is = null; 
static JSONObject jObj = null; 
static String json = ""; 

public JSONParser() { 

} 

// function get json from url 
// by making HTTP POST or GET mehtod 
public JSONObject makeHttpRequest(String url, String method, 
            List<NameValuePair> params) { 

    // Making HTTP request 
    try { 

     // check for request method 
     if(method == "POST"){ 
      // request method is POST 
      // defaultHttpClient 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 
      httpPost.setEntity(new UrlEncodedFormEntity(params)); 

      HttpResponse httpResponse = httpClient.execute(httpPost); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      is = httpEntity.getContent(); 

     }else if(method == "GET"){ 
      // request method is GET 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      String paramString = URLEncodedUtils.format(params, "utf-8"); 
      url += "" + paramString; 
      HttpGet httpGet = new HttpGet(url); 

      HttpResponse httpResponse = httpClient.execute(httpGet); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      is = httpEntity.getContent(); 
     } 


    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "iso-8859-1"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     is.close(); 
     json = sb.toString(); 
    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 

    // try parse the string to a JSON object 
    try { 
     JSONArray jObj = new JSONArray(json); 
     System.out.println(jObj.toString()); 
    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
    } 
    // return JSON String 
    return jObj; 

} 

}

Nahe dem Ende am letzten Versuch und catch-Anweisung I drucken die JSONObject als String ich die Daten korrekt in der Konsole, die json sieht wie folgt aus:

[{ "id": 1, "name": "Blooper", "Beschreibung": "Blooper",“ video_url ":" Blooper "," Plattform ": 1100110011," logo ":" " "avaible": 0, "Token": "", "created_at": "2016-04-03 17:19:49", "aktualisiert_at": "2016-04-03 17:19:49", "release_at": "2016-05-08"}, {"id": 2, "name": "Blooper", "beschreibung": "Blooper", "video_url": "Blooper", "plattform": "11000000000 "," logo ":" "," avaible ": 0," token ":" "," created_at ":" 2016-04-03 17:26:13 "," updated_at ":" 2016-04-03 17.26.13" , "release_at": "2016.05.08"}]

benutzte ich ein Validator und es ist in Ordnung.

In meiner AllProducts-Aktivität versuche ich das in der Android-App anzuzeigen.

Es sieht wie folgt aus:

public class AllProductsActivity extends ListActivity { 

    // Progress Dialog 
    private ProgressDialog pDialog; 

    // Creating JSON Parser object 
    JSONParser jParser = new JSONParser(); 

    ArrayList<HashMap<String, String>> productsList; 

    // url to get all products list 
    private static String url_all_products = "http://192.168.155.27:8000/index"; 

    // JSON Node names 
    private static final String TAG_SUCCESS = "id"; 
    private static final String TAG_PRODUCTS = "name"; 
    private static final String TAG_PID = "description"; 
    private static final String TAG_NAME = "video_url"; 

    // products JSONArray 
    JSONArray products = null; 

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

     // Hashmap for ListView 
     productsList = new ArrayList<HashMap<String, String>>(); 

     // Loading products in Background Thread 
     new LoadAllProducts().execute(); 

     // Get listview 
     ListView lv = getListView(); 

     // on seleting single product 
     // launching Edit Product Screen 
     lv.setOnItemClickListener(new OnItemClickListener() { 

      @Override 
      public void onItemClick(AdapterView<?> parent, View view, 
            int position, long id) { 
       // getting values from selected ListItem 
       String pid = ((TextView) view.findViewById(R.id.pid)).getText() 
         .toString(); 

       // Starting new intent 
       Intent in = new Intent(getApplicationContext(), 
         EditProductActivity.class); 
       // sending pid to next activity 
       in.putExtra(TAG_PID, pid); 

       // starting new activity and expecting some response back 
       startActivityForResult(in, 100); 
      } 
     }); 

    } 

    // Response from Edit Product Activity 
    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     // if result code 100 
     if (resultCode == 100) { 
      // if result code 100 is received 
      // means user edited/deleted product 
      // reload this screen again 
      Intent intent = getIntent(); 
      finish(); 
      startActivity(intent); 
     } 

    } 

    /** 
    * Background Async Task to Load all product by making HTTP Request 
    * */ 
    class LoadAllProducts extends AsyncTask<String, String, String> { 

     /** 
     * Before starting background thread Show Progress Dialog 
     * */ 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(AllProductsActivity.this); 
      pDialog.setMessage("Loading products. Please wait..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(false); 
      pDialog.show(); 
     } 

     /** 
     * getting All products from url 
     * */ 
     protected String doInBackground(String... args) { 

      // updating UI from Background Thread 
      runOnUiThread(new Runnable() { 
       public void run() { 
        // Building Parameters 
        List<NameValuePair> params = new ArrayList<NameValuePair>(); 
        // getting JSON string from URL 

       JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params); 
        // Check your log cat for JSON reponse 
        Log.d("All Products: ", json.toString()); 

        try { 
         // Checking for SUCCESS TAG 
         int success = json.getInt(TAG_SUCCESS); 

         if (success == 1) { 
          // products found 
          // Getting Array of Products 
          products = json.getJSONArray(TAG_PRODUCTS); 

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

           // Storing each json item in variable 
           String id = c.getString(TAG_PID); 
           String name = c.getString(TAG_NAME); 

           // creating new HashMap 
           HashMap<String, String> map = new HashMap<String, String>(); 

           // adding each child node to HashMap key => value 
           map.put(TAG_PID, id); 
           map.put(TAG_NAME, name); 

           // adding HashList to ArrayList 
           productsList.add(map); 
          } 
         } else { 
          // no products found 
          // Launch Add New product Activity 
          Intent i = new Intent(getApplicationContext(), 
            NewProductActivity.class); 
          // Closing all previous activities 
          i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
          startActivity(i); 
         } 
        } catch (JSONException e) { 

         e.printStackTrace(); 
        } 
       } 
      }); 
      return null; 
     } 

     /** 
     * After completing background task Dismiss the progress dialog 
     * **/ 
     protected void onPostExecute(String file_url) { 
      // dismiss the dialog after getting all products 
      pDialog.dismiss(); 
      // updating UI from Background Thread 
      runOnUiThread(new Runnable() { 
       public void run() { 
        /** 
        * Updating parsed JSON data into ListView 
        * */ 
        ListAdapter adapter = new SimpleAdapter(
          AllProductsActivity.this, productsList, 
          R.layout.list_item, new String[] { TAG_PID, 
          TAG_NAME}, 
          new int[] { R.id.pid, R.id.name }); 
        // updating listview 
        setListAdapter(adapter); 
       } 
      }); 

     } 

    } 
} 

Wenn ich versuche, dieses json auszudrucken:

JSONObject json = new JSONObject(); 

bekomme ich keine Werte (null), so meine Ansicht ist leer hält.

Ich erhalte follwing Fehlermeldung:

java.lang.NullPointerException: Der Versuch, virtuelle Methode aufzurufen 'java.lang.String org.json.JSONObject.toString()' auf ein Null-Objekt Referenz bei com.example.androidhive.AllProductsActivity $ LoadAllProducts $ 1.run (AllProductsActivity.java:150)

Linie 150 ist dies:

Log.d("All Products: ", json.toString()); 

So Android Studio erzählt meine, dass

jObj

hier, in meinem jsonparser:

try { 
    JSONArray jObj = new JSONArray(json); 
} catch (JSONException e) { 
    Log.e("JSON Parser", "Error parsing data " + e.toString()); 
} 

nie verwendet wird.

http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

ich nicht wirklich mit dieser Erfahrung bin so hoffe ich wirklich etwas Hilfe, danke.

+1

'if (method ==" POST ") {' -> [Wie kann ich Zeichenfolgen in Java vergleichen?] (Http://stackoverflow.com/questions/513832/how-do-i-compare-strings- in-java) – Pshemo

+0

was meinst du genau? (Die App wird auf die Methode get bekommen) –

+0

Es funktioniert, weil 'String-Methode' scheinbar hardcoded Literal '" POST "' hält. Da Literale in String Pool gespeichert werden, erhalten Sie genau die gleiche String-Instanz, die '==' bestätigt. Aber wenn Sie String verwenden würden, der nicht in diesem Pool ist (wie wenn Sie ihn dynamisch erzeugten - indem Sie eine Quelle auslesen: Datei, Socket) und an Ihre Methode übergeben, würden Sie sehen, dass der Vergleich mit '==' fehlschlagen würde das Vergleichen unter Verwendung von "gleich" ist bevorzugt. – Pshemo

Antwort

0

Mit JSONObject json = new JSONObject(); Sie eine leere JSONObject erstellen,

der JSONObject zurück von jParser.makeHttpRequest(url_all_products, "GET", params); wird nie verwendet.

Sie haben es, wie dies zu tun:

JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

so Ihre JSONObject vom JParser wird in json gespeichert werden.

+0

Zuerst Danke für die Antwort, ich änderte den Code wie Sie mir gesagt zu tun und ich bekomme folgende Fehlermeldung: java.lang.NullPointerException: Versuch, die virtuelle Methode 'java.lang.String org.json.JSONObject.toString aufzurufen() 'auf einem Null-Objekt Referenz –

+0

Ill bearbeiten meinen Code für bessere Sicht –

+0

Es ist, weil Ihr Code aussieht wie 'versuchen { JSONArray jObj = neue JSONArray (JSON); } return jObj; ' Die lokale Variable' jObj' ist nur im try-Block sichtbar, Sie geben die Klassenvariable 'jObj' zurück, die niemals initialisiert wird. – Dimi