2016-03-30 5 views
1

Hallo versuche ich die folgenden JSON-Daten auf meinem Android zu bekommen. Ein Fall-Link kann http://digitaresolutions.com/apps/drugindex/getbrand.php?id=bactiflox sein. Kann mir jemand helfen? Hinweis: Das Array hat ein einzelnes Objekt.Get JSON Daten auf meinem Android

public class Search_view extends AppCompatActivity { 
    String brandURL = "http://digitaresolutions.com/apps/drugindex/getbrand.php?id="; 
    TextView txtProduct; 

    String product; 
    String url=""; 

    TextView outputText; 

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

     txtProduct = (TextView) findViewById(R.id.brand_label); 

     // getting attached intent data 
     Intent i = getIntent(); 
     product = i.getStringExtra("product"); 

     // displaying selected product name 
     url = brandURL + product; 
     txtProduct.setText("Drug Molecule: " + product + "\n Product Url: " + url); 

     new JSONParse().execute(); 
    } 

    // JSON Parsing 
    private class JSONParse extends AsyncTask<String, Void, String> { 
     private ProgressDialog pDialog; 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      outputText = (TextView) findViewById(R.id.drug_info); 

      pDialog = new ProgressDialog(Search_view.this); 
      pDialog.setMessage("Loading Data ..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
      outputText.setText("Getting Brand Please wait.."); 
     } 

     @Override 
     protected String doInBackground(String... args) { 
      StringBuilder sb = new StringBuilder(); 
      String content = MyHttpUrlConnection.getData(url); 
      try { 
       JSONObject obj = new JSONObject(content); 
       JSONArray drug = obj.getJSONArray("result"); 
       for (int i = 0; i < drug.length(); i++) { 
        JSONObject p = (JSONObject) drug.get(i); 

        String drg = (String) drug.get(i); 
        Log.i("Drug Info", drg); 

        sb.append(i + 1 + " Manufacturer : " + p.getString("manu") + "\n"); 
        sb.append("Drug Info : " + p.getString("details") + "\n"); 
       } 

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

     @Override 
     protected void onPostExecute(String result) { 
      pDialog.dismiss(); 
      outputText.setText(result); 
     } 
    } 
     // End JSON JSON Parsing 
} 

Der folgende Code ist mein Http Url Anschluss:

public class MyHttpUrlConnection { 

    public static String getData(String uri) { 

     BufferedReader reader = null; 

     try { 
      URL url = new URL(uri); 
      HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
      con.setReadTimeout(10000); 
      con.setConnectTimeout(15000); 
      con.setDoInput(true); 
      con.connect(); 
      InputStream is = con.getInputStream(); 
      reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); 
      String data = null; 
      String webPage = ""; 
      while ((data = reader.readLine()) != null) { 
       webPage += data + "\n"; 
      } 
      return webPage; 

     } catch (Exception e) { 
      e.printStackTrace(); 
      return null; 
     } finally { 
      if (reader != null) { 
       try { 
        reader.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
        return null; 
       } 
      } 
     } 
    } 
} 
+0

ist dies eine Anfrage erhalten oder senden? –

+0

Bitte werfen Sie einen Blick auf Volley: http://developer.android.com/training/volley/index.html – Machado

+0

Es ist eine Anfrage erhalten. Ich verwende einen Intent-Wert aus einer vorherigen Aktivität, um die URL abzuschließen: "http://digitraresolutions.com/apps/drugindex/getbrand.php?id=" sowie – Brian

Antwort

0

ich auf diese Weise verwenden.

Erstellen globaler Variablen

InputStream inputStream; 
int res_code; 

erstelle ich eine Klasse, die AsyncTask

public class GetJsonData extends AsyncTask<String, Void, Boolean> { 
    @SuppressWarnings("deprecation") 
    @Override 
    protected Boolean doInBackground(String... arg0) { 

     try { 

      HttpClient client = new DefaultHttpClient(); 
      HttpGet request = new HttpGet("http://digitaresolutions.com/apps/drugindex/getbrand.php?id=bactiflox"); 

      request.setHeader(HTTP.CONTENT_TYPE, "application/json"); 

      HttpResponse response = null; 
      try { 
       response = client.execute(request); 

       Log.d("Response of GET request", response.toString()); 
      } catch (ClientProtocolException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

      inputStream = response.getEntity().getContent(); 
      String result = convertInputStreamToString(inputStream); 
      res_code = response.getStatusLine().getStatusCode(); 
      //Printing server response 
      System.out.println("server response is :" + result + "\n" + inputStream); 


      try { 

       JsonObject jo new JSONObject(result); 


      } catch (Exception e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 

      } 
     } catch (Exception e) { 
      Log.e("ClientServerDemo", "Error:", e); 


     } 

     return true; 
    } 

    protected void onPreExecute() { 

     //display the progress dialog 


    } 

    @Override 
    protected void onPostExecute(Boolean valid) { 

     //dismiss the progress dialog 

     if (inputStream != null){ 

     } 
    } 

} 

erstreckt ich eine Funktion verwende. Bitte geben Sie die Methode hinzufügen, nachdem die Klasse Zugabe

public String convertInputStreamToString(InputStream inputStream) throws IOException{ 

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 
    String line = ""; 
    String result = ""; 
    while((line = bufferedReader.readLine()) != null){ 
     result += line; 
     System.out.println("---->"+line); 
    } 

    inputStream.close(); 
    return result; 

} 

Dies funktioniert für mich ..

ps: wenn Sie nicht die HTTP-Klassen importieren, fügen Sie dann den folgenden in der build.gradle des Moduls

useLibrary 'org.apache.http.legacy' 

nach

compileSdkVersion 23 
buildToolsVersion "23.0.2" 

in der

android{ 

} 

Alles Gute

+0

Hallo Prakhar, etwas stimmt nicht mit diesem Abschnitt: – Brian

+0

inputStream = response.getEntity(). getContent(); Zeichenfolge result = convertInputStreamToString (inputStream); res_code = Antwort.getStatusLine(). GetStatusCode(); // Druckserverantwort System.out.println ("Serverantwort ist:" + Ergebnis + "\ n" + inputStream); – Brian

+0

@BrianOwuoche erhalten Sie einen Fehler? –