2017-04-24 129 views
0

我正在開發和andeoid應用程序,它會消耗一個寧靜的Web服務,從Mysql數據庫中檢索數據。 所以我試圖在我的ListView上顯示webMethode的結果,但列表總是空的。 結果是JSON格式,但是作爲字符串。Android:結果從Restful WS沒有顯示在我的ListView

我犯了一個包含列表視圖佈局

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <TextView 
     android:id="@+id/textView" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:text="La liste des DAB" /> 

    <ListView 
     android:id="@+id/lstdab" 
     style="@style/Widget.AppCompat.ListView.DropDown" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:visibility="visible" /> 
</LinearLayout> 

包含列表視圖的項目佈局

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical" 
    android:padding="10dp" 
    android:paddingLeft="10dp" 
    android:paddingRight="10dp" > 
    <TextView 
     android:id="@+id/id" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:paddingBottom="2dip" 
     android:paddingTop="6dip" 
     android:textColor="#43bd00" 
     android:textSize="16sp" 
     android:textStyle="bold" /> 
    <TextView 
     android:id="@+id/libdab" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:paddingBottom="2dip" 
     android:paddingTop="6dip" 
     android:textColor="#43bd00" 
     android:textSize="16sp" 
     android:textStyle="bold" /> 

    <TextView 
     android:id="@+id/tet" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:paddingBottom="2dip" 
     android:paddingTop="6dip" 
     android:textColor="#43bd00" 
     android:textSize="16sp" 
     android:textStyle="bold" /> 

    <TextView 
     android:id="@+id/libe" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:paddingBottom="2dip" 
     android:textColor="#acacac" /> 
    <TextView 
     android:id="@+id/zone" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:gravity="left" 
     android:textColor="#5d5d5d" 
     android:textStyle="bold" /> 
</LinearLayout> 

這是我的活動,將填補從收到的ListView webMethode在Restful WebService上使用URL:

 package com.example.projetmonitoringapplication; 

import android.os.AsyncTask; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 
import android.widget.TextView; 

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

import java.io.IOException; 
import java.util.ArrayList; 

import cz.msebera.android.httpclient.HttpResponse; 
import cz.msebera.android.httpclient.client.HttpClient; 
import cz.msebera.android.httpclient.client.methods.HttpGet; 
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient; 
import cz.msebera.android.httpclient.util.EntityUtils; 

/** 
* Created by Emel on 24/04/2017. 
*/ 

public class listez extends AppCompatActivity { 

    ListView list; 
    // BaseAdapter2 adapter; 
    ArrayList<Dabl> arrayOfWebData = new ArrayList<Dabl>(); 
    //this is our result object 

    class Dabl { 
     int id ; 
     String libdab; 
     String etat; 
     String des ; 
     String zone ; 

    } 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.listezonelayout); 
     list = (ListView) findViewById(R.id.lstdab); 
     new TheTask().execute(); 
    } 
    adapter aa ; 

    class adapter extends ArrayAdapter<listez.Dabl> { 
     adapter() { 
      super(listez.this, android.R.layout.simple_list_item_1, arrayOfWebData); 
     } 

     public View getView(int position, View convertView, 
          ViewGroup parent) { 
      ViewHolder holder; 

      if (convertView==null) { 
       LayoutInflater inflater=getLayoutInflater(); 
       convertView=inflater.inflate(R.layout.listdabzitem, null); 

       holder=new listez.ViewHolder(convertView); 

       convertView.setTag(holder); 
      } 
      else 
      { 
       holder=(ViewHolder)convertView.getTag(); 
      } 
      holder.populateFrom(arrayOfWebData.get(position)); 

      return(convertView); 
     } 
    } 

    class ViewHolder { 
     public TextView idd=null; 
     public TextView lib=null; 
     public TextView et=null; 
     public TextView des=null; 
     public TextView zone=null; 

     ViewHolder(View row) { 
      idd=(TextView)row.findViewById(R.id.id); 
      lib=(TextView)row.findViewById(R.id.libdab); 
      et=(TextView)row.findViewById(R.id.tet); 
      des=(TextView)row.findViewById(R.id.libe); 
      zone=(TextView)row.findViewById(R.id.zone); 
     } 
     //notice we had to change our populate from to take an arguement of type person 
     void populateFrom(Dabl r) { 
      idd.setText(r.id); 
      lib.setText(r.libdab); 
      et.setText(r.etat); 
      des.setText(r.des); 
      zone.setText(r.zone); 
     } 
    } 

    class TheTask extends AsyncTask<Void, Void, String> { 

     @Override 
     protected String doInBackground(Void... params) { 
      String str = null; 
      try { 
       HttpClient httpclient = new DefaultHttpClient(); 
       HttpGet httppost = new HttpGet(
         "http://10.0.2.2:8180/ProjetMonitoring/RestApp/DA/RechercherDABzTunis"); 
       HttpResponse response = httpclient.execute(httppost); 
       str = EntityUtils.toString(response.getEntity()); 
       Log.e("test", "----" + str); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

      return str; 

     } 


     @Override 
     protected void onPostExecute(String result) { 

      super.onPostExecute(result); 

      String response = result.toString(); 
      try { 


       JSONArray jArray = new JSONArray(response); 

       for (int i = 0, count = jArray.length(); i < count; i++) { 
        //get our object, this is one person's worth of data 
        JSONObject json_data = jArray.getJSONObject(i); 
        Log.i("try jaaray ob ",json_data.toString()); 

        //create a new person 
        Dabl resultRow = new Dabl(); 
        //set that person's attributes 
        resultRow.id = json_data.getInt("id_DAB"); 
        resultRow.libdab = json_data.getString("Libelle_DAB"); 
        resultRow.etat = json_data.getString("etat"); 
        resultRow.des= json_data.getString("description"); 
        resultRow.zone= json_data.getString("zone"); 

        //this is our arrayList object, we add our Person object to it 
        arrayOfWebData.add(resultRow); 
       } 
       ListView myListView = (ListView)findViewById(R.id.lstdab); 

       aa=new adapter(); 

       myListView.setAdapter(aa); 
String s=myListView.getItemAtPosition(1).toString(); 
       Log.i("ITEM",s); 
      } catch (JSONException e) { 
       // TODO Auto-genrror2"); 
       Log.e("ERROR", "ERROR IN CODE: " + e.toString()); 
       e.printStackTrace(); 
      } 

     } 
    } 


} 

不關注我的通訊ents或未使用的變量。 所以excuting這之後這就是我得到我的logcat的,即使我是顯示給測試沒有出現log.e:

04-24 20:51:29.355 20374-20636/com.example.projetmonitoringapplication E/test: ----["{\"zone\":\"Tunis\",\"description\":\"le DAB fonctionne correctement.\",\"id_DAB\":22,\"etat\":\"En marche\",\"Libelle_DAB\":\"\"}","{\"zone\":\"Tunis\",\"description\":\"le DAB fonctionne correctement.\",\"id_DAB\":26,\"etat\":\"En marche\",\"Libelle_DAB\":\"ooo\"}","{\"zone\":\"Tunis\",\"description\":\"le DAB fonctionne correctement.\",\"id_DAB\":27,\"etat\":\"En marche\",\"Libelle_DAB\":\"\"}","{\"zone\":\"Tunis\",\"description\":\"le DAB fonctionne correctement.\",\"id_DAB\":6660,\"etat\":\"En marche\",\"Libelle_DAB\":\"yyy\"}"] 
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication E/ERROR: ERROR IN CODE: org.json.JSONException: Value {"zone":"Tunis","description":"le DAB fonctionne correctement.","id_DAB":22,"etat":"En marche","Libelle_DAB":""} at 0 of type java.lang.String cannot be converted to JSONObject 
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err: org.json.JSONException: Value {"zone":"Tunis","description":"le DAB fonctionne correctement.","id_DAB":22,"etat":"En marche","Libelle_DAB":""} at 0 of type java.lang.String cannot be converted to JSONObject 
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:  at org.json.JSON.typeMismatch(JSON.java:100) 
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:  at org.json.JSONArray.getJSONObject(JSONArray.java:514) 
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:  at com.example.projetmonitoringapplication.listez$TheTask.onPostExecute(listez.java:141) 
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:  at com.example.projetmonitoringapplication.listez$TheTask.onPostExecute(listez.java:106) 
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:  at android.os.AsyncTask.finish(AsyncTask.java:632) 
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:  at android.os.AsyncTask.access$600(AsyncTask.java:177) 
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645) 
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:  at android.os.Handler.dispatchMessage(Handler.java:102) 
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:  at android.os.Looper.loop(Looper.java:136) 
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:  at android.app.ActivityThread.main(ActivityThread.java:5021) 
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:  at java.lang.reflect.Method.invokeNative(Native Method) 
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:  at java.lang.reflect.Method.invoke(Method.java:515) 
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827) 
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643) 
04-24 20:51:29.365 20374-20374/com.example.projetmonitoringapplication W/System.err:  at dalvik.system.NativeStart.main(Native Method) 

這是我WebMethode:

// DAB zone Tunis 
     @GET 
     @Path("/RechercherDABzTunis") 
     @Produces(MediaType.APPLICATION_JSON) 
    // @Consumes(MediaType.APPLICATION_JSON) 
     public String DABtunis() 
       throws SQLException, JSONException { 
      JSONObject obj = new JSONObject(); 
      JSONArray array=new JSONArray(); 


     dbCoN = new DBConnection(); 
     query = "SELECT dab.id_DAB, dab.libelle_DAB , etat.titre_etat , etat.libelle,zone.nom_zone FROM dab, agence,zone,etat where dab.id_agence=agence.id_agence and agence.id_zone=zone.id_zone and zone.nom_zone='Tunis' GROUP by dab.id_DAB;"; 

      try { 
       conn = (Connection) DBConnection.createConnection(); 
       rslt = dbCoN.getResutlSet(query, conn); 
       System.out.println("try here ! ! ! "); 

       if (rslt.next()) { 
       while (rslt.next()){ 
        obj = DAB.DABzoneToJson(rslt.getInt("id_DAB"),rslt.getString("libelle_DAB"),rslt.getString("titre_etat"),rslt.getString("libelle"),rslt.getString("nom_zone")); 
        array.put(obj.toString()); 


        System.out.println(rslt.getString(1).toString()); 
        } 
       } 
       else { 
        obj=DAB.DABToJsonFaux(); 
        array.put(obj.toString()); 

        System.out.println(""); 

        } 

       } catch (SQLException e){ 
        System.out.println("exception here sql! ! "+e); 
       } catch (Exception ex){ 
        System.out.println("exception here ! ! "+ex); 
       } finally { 
        if (conn != null) { 
         conn.close(); 
            } 
       } 
      //JSONObject jobj=new JSONObject(); 
     // jobj.put("array", array.toString()); 

      return array.toString(); 

     } 

我認爲問題在於這兩個例外,但我沒有看到任何錯誤。 這是我webMethodeØ郵遞員的結果:

[ 
    "{\"zone\":\"Tunis\",\"description\":\"le DAB fonctionne correctement.\",\"id_DAB\":22,\"etat\":\"En marche\",\"Libelle_DAB\":\"\"}", 
    "{\"zone\":\"Tunis\",\"description\":\"le DAB fonctionne correctement.\",\"id_DAB\":26,\"etat\":\"En marche\",\"Libelle_DAB\":\"ooo\"}", 
    "{\"zone\":\"Tunis\",\"description\":\"le DAB fonctionne correctement.\",\"id_DAB\":27,\"etat\":\"En marche\",\"Libelle_DAB\":\"\"}", 
    "{\"zone\":\"Tunis\",\"description\":\"le DAB fonctionne correctement.\",\"id_DAB\":6660,\"etat\":\"En marche\",\"Libelle_DAB\":\"yyy\"}" 
] 
i'm using Android Studio , and wildfly 8 as a server, my web Service is a r 

estful我有完美的作品相同的應用程序登錄的活動,我覺得probleme是在解析,但我看不出錯誤,有人可以請一下嗎?謝謝!

更新:我添加asyncTask,如你所說,沒有即時從日誌中的webService接收結果,但我仍然無法顯示它在ListView上,我更新了我的活動代碼,日誌也!

+0

嘗試使用凌空用於檢索數據 – theSereneRebel

回答

1

Error in http connection android.os.NetworkOnMainThreadException

嘗試使用AsyncTask從HTTP請求得到JSON。或者使用Volley庫作爲它的易於實現。

Error parsing data org.json.JSONException: End of input at character 0 of

你得到JSON解析錯誤,json_data.getString("id_DAB")id_DAB是包含int值。

試試這個:

//create a new person 
Dabl resultRow = new Dabl(); 

//set that person's attributes 
resultRow.id = json_data.getInt("id_DAB"); 
resultRow.libdab = json_data.getString("Libelle_DAB"); 
resultRow.etat = json_data.getString("etat"); 
resultRow.des= json_data.getString("description"); 
resultRow.zone= json_data.getString("zone"); 

UPDATE:

E/ERROR: ERROR IN CODE: org.json.JSONException : Value {"zone":"Tunis","description":"le DAB fonctionne correctement.","id_DAB":22,"etat":"En marche","Libelle_DAB":""} at 0 of type java.lang.String cannot be converted to JSONObject

這裏是工作代碼:

public void parseJson(){ 

    // Your JSON 
    String result = "[\n" + 
      " \"{\\\"zone\\\":\\\"Tunis\\\",\\\"description\\\":\\\"le DAB fonctionne correctement.\\\",\\\"id_DAB\\\":22,\\\"etat\\\":\\\"En marche\\\",\\\"Libelle_DAB\\\":\\\"\\\"}\",\n" + 
      " \"{\\\"zone\\\":\\\"Tunis\\\",\\\"description\\\":\\\"le DAB fonctionne correctement.\\\",\\\"id_DAB\\\":26,\\\"etat\\\":\\\"En marche\\\",\\\"Libelle_DAB\\\":\\\"ooo\\\"}\",\n" + 
      " \"{\\\"zone\\\":\\\"Tunis\\\",\\\"description\\\":\\\"le DAB fonctionne correctement.\\\",\\\"id_DAB\\\":27,\\\"etat\\\":\\\"En marche\\\",\\\"Libelle_DAB\\\":\\\"\\\"}\",\n" + 
      " \"{\\\"zone\\\":\\\"Tunis\\\",\\\"description\\\":\\\"le DAB fonctionne correctement.\\\",\\\"id_DAB\\\":6660,\\\"etat\\\":\\\"En marche\\\",\\\"Libelle_DAB\\\":\\\"yyy\\\"}\"\n" + 
      "]"; 

    String response = result.toString(); 

    try { 
     JSONArray jArray = new JSONArray(response); 

     for (int i = 0; i < jArray.length(); i++) { 
      String string = jArray.getString(i); 
      Log.i("try jaaray ob ", string.toString()); 

      JSONObject json_data = new JSONObject(string); 
      int id = json_data.getInt("id_DAB"); 
      String libdab = json_data.getString("Libelle_DAB"); 
      String etat = json_data.getString("etat"); 
      String des= json_data.getString("description"); 
      String zone= json_data.getString("zone"); 

      Log.d("Success", "id: " + id + "\nlibdab: " + libdab + "\netat: " + etat + 
      "\ndes: " + des + "\nzone: " + zone); 
     } 
    } catch (JSONException e) { 
     Log.e("ERROR", "ERROR IN CODE: " + e.toString()); 
     e.printStackTrace(); 
    } 
} 

輸出日誌:

I/try jaaray ob: {"zone":"Tunis","description":"le DAB fonctionne correctement.","id_DAB":22,"etat":"En marche","Libelle_DAB":""} 
D/Success: id: 22 
      libdab: 
      etat: En marche 
      des: le DAB fonctionne correctement. 
      zone: Tunis 

I/try jaaray ob: {"zone":"Tunis","description":"le DAB fonctionne correctement.","id_DAB":26,"etat":"En marche","Libelle_DAB":"ooo"} 
D/Success: id: 26 
      libdab: ooo 
      etat: En marche  
      des: le DAB fonctionne correctement.  
      zone: Tunis 

I/try jaaray ob: {"zone":"Tunis","description":"le DAB fonctionne correctement.","id_DAB":27,"etat":"En marche","Libelle_DAB":""} 
D/Success: id: 27 
      libdab: 
      etat: En marche 
      des: le DAB fonctionne correctement. 
      zone: Tunis 

I/try jaaray ob: {"zone":"Tunis","description":"le DAB fonctionne correctement.","id_DAB":6660,"etat":"En marche","Libelle_DAB":"yyy"} 
D/Success: id: 6660 
      libdab: yyy 
      etat: En marche 
      des: le DAB fonctionne correctement. 
      zone: Tunis 

希望這將有助於〜

+0

謝謝!它的工作原理,但我仍然拋出一個jsonException –

+0

它是什麼?張貼在這裏 – FAT

+0

做的,我更新的日誌 –

0

您需要添加一個AsyncTask來運行您的api調用,否則網絡將因爲在UI線程上運行而失敗。 檢查this answer爲例。

+0

是的,謝謝!現在我可以看到結果我的日誌,但我stiill不能在我的ListView顯示它 –

0

看起來像你在主線程上發出一個網絡請求,這是一個很大的不得不在android上。

嘗試做一個新的ThreadAsyncTask或活動IntentService

一些閱讀材料 https://developer.android.com/training/articles/perf-anr.html

https://developer.android.com/reference/android/os/AsyncTask.html

+0

是感謝youit與asynkTask工作!現在我可以看到我日誌中的結果,但我stiill不能在我的ListView –

+0

顯示它這樣做,在onPostExecute – pantos27

+0

但它已經在onPostExecute了Methode,我更新的問題的代碼。 –