我正在开发和使用一个宁静的Web服务的应用程序,该服务从Mysql数据库中检索数据。 所以我试图在ListView上显示webMethode的结果,但列表总是为空。 结果是在JSONformat上但是作为字符串。
我制作了一个包含列表视图的布局
<?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>
这是我的Activity,它将使用URL填充从Restful WebService上的webMethode收到的listView:
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();
}
}
}
}
不要注意我的评论或未使用的变量。 所以在排除这个之后,这就是我在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我在相同的应用程序中有一个完美的登录活动,我认为问题在于解析,但我没有看到错误,有人可以探索吗?谢谢!
更新:我添加了asyncTask,如你所说,没有我从日志中的webService接收结果但我仍然无法在ListView上显示它,我更新了我的活动代码,日志也在!
答案 0 :(得分:1)
http连接android.os.NetworkOnMainThreadException
时出错
尝试使用AsyncTask
从HTTP请求中获取JSON
。或者使用Volley
库,因为它易于实现。
解析数据时出错org.json.JSONException:字符0处的输入结束 的
由于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");
<强>更新强>
E / ERROR:代码中的错误:org.json.JSONException
:值{"zone":"Tunis","description":"le DAB fonctionne
correctement.","id_DAB":22,"etat":"En marche","Libelle_DAB":""}
为0 类型java.lang.String
无法转换为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
希望这会有所帮助〜
答案 1 :(得分:0)
您需要添加AsyncTask来运行api调用,否则网络将失败,因为它在UI线程上运行。 请查看this answer以获取示例。
答案 2 :(得分:0)
看起来你在主线程上发出了一个网络请求,这对于android来说是一个很大的禁忌。
尝试在新的Thread
,AsyncTask
或事件IntentService
一些阅读材料 https://developer.android.com/training/articles/perf-anr.html
https://developer.android.com/reference/android/os/AsyncTask.html