2016-06-10 8 views
-2

JSONParser.classWie JSON dat mit HTTP-POST-Methode in Android Studio

package com.example.diptiagravat.myapplication; 

public class JSONParser { 

    public String getJSON(String url, int timeout) { 
     HttpURLConnection c = null; 
     try { 
      URL u = new URL(url); 
      c = (HttpURLConnection) u.openConnection(); 
      c.setRequestMethod("GET"); 
      c.setRequestProperty("Content-length", "0"); 
      c.setUseCaches(false); 
      c.setAllowUserInteraction(false); 
      c.setConnectTimeout(timeout); 
      c.setReadTimeout(timeout); 
      c.connect(); 
      int status = c.getResponseCode(); 

      switch (status) { 
       case 200: 
       case 201: 
        BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream())); 
        StringBuilder sb = new StringBuilder(); 
        String line; 
        while ((line = br.readLine()) != null) { 
         sb.append(line + "\n"); 
        } 
        br.close(); 
        return sb.toString(); 
      } 

     } catch (MalformedURLException ex) { 
      Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); 
     } catch (IOException ex) { 
      Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); 
     } finally { 
      if (c != null) { 
       try { 
        c.disconnect(); 
       } catch (Exception ex) { 
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); 
       } 
      } 
     } 
     return null; 
    } 

    public String sendHTTPData(String urlpath, String id) { 
     HttpURLConnection connection = null; 
     try { 
      URL url=new URL(urlpath); 
      connection = (HttpURLConnection) url.openConnection(); 
      connection.setDoOutput(true); 
      connection.setDoInput(true); 
      connection.setRequestMethod("POST"); 
      connection.setRequestProperty("Content-Type", "application/json"); 
      connection.setRequestProperty("Accept", "application/json"); 
      OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream()); 
      streamWriter.write(id); 
      streamWriter.flush(); 
      StringBuilder stringBuilder = new StringBuilder(); 
      if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){ 
       InputStreamReader streamReader = new InputStreamReader(connection.getInputStream()); 
       BufferedReader bufferedReader = new BufferedReader(streamReader); 
       String response = null; 
       while ((response = bufferedReader.readLine()) != null) { 
        stringBuilder.append(response + "\n"); 
       } 
       bufferedReader.close(); 

       Log.d("test", stringBuilder.toString()); 
       return stringBuilder.toString(); 
      } else { 
       Log.e("test", connection.getResponseMessage()); 
       return null; 
      } 
     } catch (Exception exception){ 
      Log.e("test", exception.toString()); 
      return null; 
     } finally { 
      if (connection != null){ 
       connection.disconnect(); 
      } 
     } 
    } 
} 

MainActivity.java

package com.example.diptiagravat.myapplication; 

public class MainActivity extends AppCompatActivity { 

    private TextView txtid, txtcname; 
    Spinner spcnt, spstate; 
    public ArrayList<String> clist; 
    ArrayAdapter<String> cad; 
    public ArrayList<String> slist; 
    ArrayAdapter<String> sad; 
    public String strcnt; 
    private static String url = "http://urmiinfotech.com/demo/ifirst/app_api/get_country_list.php"; 
    private static String stateUrl = "http://urmiinfotech.com/demo/ifirst/app_api/get_state_list.php"; 
    private static final String TAG_USER = "country"; 
    private static final String TAG_ID = "id"; 
    private static final String TAG_NAME = "country_name"; 
    private ArrayList<Country> clistModels; 

    /** 
    * ATTENTION: This was auto-generated to implement the App Indexing API. 
    * See https://g.co/AppIndexing/AndroidStudio for more information. 
    */ 
    private GoogleApiClient client; 

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

     initViews(); 

     CountryAsyncTask countryAsyncTask= new CountryAsyncTask(); 
     countryAsyncTask.execute(); 
    } 

    private void initViews() { 

     txtid = (TextView) findViewById(R.id.tvid); 
     txtcname = (TextView) findViewById(R.id.tvcname); 
     spcnt = (Spinner) findViewById(R.id.spcnt); 
     spstate = (Spinner) findViewById(R.id.spstate); 
     clist = new ArrayList<String>(); 
     slist = new ArrayList<String>(); 

    } 


    public class CountryAsyncTask extends AsyncTask<Void, Void, String> { 

     @Override 
     protected String doInBackground(Void... params) { 
      // TODO Auto-generated method stub 
      JSONParser jParser = new JSONParser(); 

      // Getting JSON from URL 
      JSONObject json = null; 
      try { 
       json = new JSONObject(jParser.getJSON(url, 5000)); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

      return json.toString(); 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      // TODO Auto-generated method stub 
      super.onPostExecute(result); 

      Log.i("Result Ravi", result); 

      try { 
       JSONObject obj = new JSONObject(result); 
       JSONArray cntArray = obj.getJSONArray("country"); 

       if (cntArray.length() > 0) { 
        for (int i = 0; i < cntArray.length(); i++) { 
         final JSONObject temp = cntArray.getJSONObject(i); 
         // txtid.setText(temp.getString("id")); 
         // txtcname.setText(temp.getString("country_name")); 


         Country country = new Gson().fromJson(temp.toString(), Country.class); 
         clist = new ArrayList<String>(); 
         clistModels = new ArrayList<Country>(); 
         clistModels.add(new Country(temp.optString("id"), temp.optString("country_name"), "", null)); 
         clist.add(temp.getString("country_name")); 
         cad = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, clist); 
         spcnt.setAdapter(cad); 
         spcnt.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
          @Override 
          public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 

           strcnt = clistModels.get(position).getId(); 
           //strcnt = parent.getItemAtPosition(position).toString(); 
           Log.i("id", strcnt); 
           new StatesAsyncTask().execute(); 

          } 

          @Override 
          public void onNothingSelected(AdapterView<?> parent) { 

          } 
         }); 

         // txtid.setText(temp.getString(country.getId())); 
         // txtcname.setText(temp.getString(country.getCountryName())); 
        } 
       } 
      } catch (JSONException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
    } 

    public class StatesAsyncTask extends AsyncTask<Void, Void, String> { 

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

     @Override 
     protected String doInBackground(Void... params) { 
      JSONParser jParser = new JSONParser(); 

      // Getting JSON from URL 


      JSONObject json = null; 
      try { 
       json = new JSONObject(jParser.sendHTTPData(stateUrl, strcnt)); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

      return json.toString(); 


     } 

     @Override 
     protected void onPostExecute(String s) { 
      super.onPostExecute(s); 

      try { 
       JSONObject obj = new JSONObject(s); 
       JSONArray stArray = obj.getJSONArray("statelist"); 

       if (stArray.length() > 0) { 
        for (int i = 0; i < stArray.length(); i++) { 
         final JSONObject temp = stArray.getJSONObject(i); 
         // txtid.setText(temp.getString("id")); 
         // txtcname.setText(temp.getString("country_name")); 


         Statelist stlist = new Gson().fromJson(temp.toString(), Statelist.class); 
         slist = new ArrayList<String>(); 
         // clistModels = new ArrayList<Country>(); 
         //clistModels.add(new Country(temp.optString("id"), temp.optString("country_name"), "", null)); 
         slist.add(temp.getString("state_name")); 
         sad = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, slist); 
         spstate.setAdapter(sad); 
         spstate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
          @Override 
          public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 

           // strcnt = clistModels.get(position).getId(); 
           //strcnt = parent.getItemAtPosition(position).toString(); 
           // Log.i("id", strcnt); 
          } 

          @Override 
          public void onNothingSelected(AdapterView<?> parent) { 

          } 
         }); 

         // txtid.setText(temp.getString(country.getId())); 
         // txtcname.setText(temp.getString(country.getCountryName())); 
        } 
       } 
      } catch (JSONException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

     } 
    } 

} 

Meine Antwort ist null analysieren?

+0

Dies wird hilfreich http://www.tutorialspoint.com/android/android_json_parser.htm oder http://www.androidhive.info/2012/01/android-json versuchen -parsing-tutorial/ –

+0

Vielen Dank, aber ich habe bereits dieses Tutorial.In meiner JSONParser-Klasse Antwortvariable ist Null. Ich kann keine Daten bekommen. –

+0

Was ist der Statuscode vom Server – MNM

Antwort

0

HttpURLConnection ist in Android Lollipop veraltet, bitte versuchen Sie stattdessen DefaultHttpClient zu verwenden. Überprüfen Sie auch Ihre Protokolle, ist dies bei Ihrer onPostExecute():

Log.i("Result Ravi", result); 

Für DefaultHttpClient Überprüfung dieser post.

Ein anderer Weg ist Retrofit

+0

Ja, ich habe die JSON in Log, aber wenn ich sendHttpData in Json übergeben habe, bekomme ich Json = null. –

+0

in dieser URL http://urmiinfotech.com/demo/ifirst/app_api/get_state_list.php Sie haben Json null, also bitte überprüfen pasing Parameter und feuern diese URL im Browser mit richtigen Parameter – ViratBhavsar

+0

Ich fand die Lösung mit Volley. Dank an alle –

Verwandte Themen