三天来,我正在尝试使用 mySQL 数据来实现我的 ListView。我使用 php 请求成功获取了我的数据,但是我的应用程序需要一些时间才能从网络接收数据这一事实存在一些问题......所以,当我的 listView 应该实现时,arraylist 是空的,它不工作...
我尝试了一些解决方案,例如“AsyncTask”,但我不知道如何以我的方式使用它。
我真的希望有人能帮助我,我迷路了!
我的“repertoire.java”:
package com.example.joignabilite;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import com.example.joignabilite.ContactAdapter.ContactAdapterListener;
public class Repertoire extends Activity implements ContactAdapterListener {
// Mettre l'adresse du script PHP
// Attention localhost ou 127.0.0.1 ne fonctionnent pas. Mettre l'adresse IP local.
public static final String strURL = "http://192.168.0.13/Bouygues/repertoire.php";
static ArrayList<Contact> listP;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_repertoire);
new Thread(new Runnable() {
public void run() {
String infoContact = getServerData(strURL);
System.out.println("1" + infoContact);
}
}).start();
System.out.println("2" + listP);
//Récupération de la liste des Contacts
//listP = Contact.getAListOfContact();
//Création et initialisation de l'Adapter pour les Contacts
ContactAdapter adapter = new ContactAdapter(this, listP);
//Ecoute des évènements sur votre liste
adapter.addListener(this);
//Récupération du composant ListView
ListView list = (ListView)findViewById(R.id.repertoire_nom);
//Initialisation de la liste avec les données
list.setAdapter(adapter);
//Changement d'activité
final Button autreDestinataireButton = (Button) findViewById(R.id.autre_destinataire);
autreDestinataireButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Repertoire.this, ContactManuel.class);
startActivity(intent);
}
});
}
public void onClickNom(Contact item, int position) {
/*Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Personne");
builder.setMessage("Vous avez cliqué sur : " + item.nom + " Son numéro est : 0" + item.numero);
builder.setPositiveButton("Oui", null);
builder.setNegativeButton("Non", null);
builder.show(); */
Intent intent = new Intent(Repertoire.this, ChoixTemps.class);
startActivity(intent);
}
public static void ajouterContact(String nom, long numero){
listP.add(new Contact(nom,numero));
System.out.println(listP);
}
private String getServerData(String strURL) {
InputStream is = null;
String result = "";
String returnString = "";
// Envoie de la commande http
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(strURL);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convertion de la requête en string
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();
result=sb.toString();
System.out.println(result);
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
// Parse les données JSON
try{
JSONArray jArray = new JSONArray(result);
//Suppression de l'url
returnString="";
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
// Affichage ID_ville et Nom_ville dans le LogCat
Log.i("log_tag","Nom: "+json_data.getString("nom")+
", Numero: "+json_data.getLong("numero")
);
listP.add(new Contact(json_data.getString("nom"), json_data.getLong("numero")));
// Résultats de la requête
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data " + e.toString());
}
return returnString;
}
}
我的“activity_repertoire.xml”:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".Repertoire" >
<TableLayout
android:id="@+id/repertoire"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<include android:id="@+id/header"
layout="@layout/header_mobile"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:paddingTop="@dimen/small_padding"
android:text="@string/destinataire"
android:textSize="@dimen/normal_text_size"
android:textStyle="bold" />
<ListView
android:id="@+id/repertoire_nom"
android:layout_width="fill_parent"
android:layout_height="275dp"
android:paddingTop="@dimen/small_padding" >
</ListView>
<Button android:id="@+id/autre_destinataire"
android:layout_width="wrap_content"
android:layout_height="@dimen/button_height"
android:layout_marginTop="@dimen/small_padding"
android:layout_marginLeft="@dimen/small_padding"
android:layout_marginRight="@dimen/small_padding"
android:background="@drawable/buttontype1"
android:text="@string/autre_destinataire" />
</TableLayout>
</RelativeLayout>
我的日志猫:
05-12 02:36:50.625: D/memalloc(2205): /dev/pmem: Mapped buffer base:0x5c58e000 size:3768320 offset:0 fd:66
05-12 02:36:50.795: I/System.out(2205): 2null
05-12 02:36:50.795: D/AndroidRuntime(2205): Shutting down VM
05-12 02:36:50.795: W/dalvikvm(2205): threadid=1: thread exiting with uncaught exception (group=0x40ab2210)
05-12 02:36:50.925: E/AndroidRuntime(2205): FATAL EXCEPTION: main
05-12 02:36:50.925: E/AndroidRuntime(2205): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.joignabilite/com.example.joignabilite.Repertoire}: java.lang.NullPointerException
05-12 02:36:50.925: E/AndroidRuntime(2205): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1967)
05-12 02:36:50.925: E/AndroidRuntime(2205): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
05-12 02:36:50.925: E/AndroidRuntime(2205): at android.app.ActivityThread.access$600(ActivityThread.java:127)
05-12 02:36:50.925: E/AndroidRuntime(2205): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
05-12 02:36:50.925: E/AndroidRuntime(2205): at android.os.Handler.dispatchMessage(Handler.java:99)
05-12 02:36:50.925: E/AndroidRuntime(2205): at android.os.Looper.loop(Looper.java:137)
05-12 02:36:50.925: E/AndroidRuntime(2205): at android.app.ActivityThread.main(ActivityThread.java:4441)
05-12 02:36:50.925: E/AndroidRuntime(2205): at java.lang.reflect.Method.invokeNative(Native Method)
05-12 02:36:50.925: E/AndroidRuntime(2205): at java.lang.reflect.Method.invoke(Method.java:511)
05-12 02:36:50.925: E/AndroidRuntime(2205): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
05-12 02:36:50.925: E/AndroidRuntime(2205): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
05-12 02:36:50.925: E/AndroidRuntime(2205): at dalvik.system.NativeStart.main(Native Method)
05-12 02:36:50.925: E/AndroidRuntime(2205): Caused by: java.lang.NullPointerException
05-12 02:36:50.925: E/AndroidRuntime(2205): at com.example.joignabilite.ContactAdapter.getCount(ContactAdapter.java:33)
05-12 02:36:50.925: E/AndroidRuntime(2205): at android.widget.ListView.setAdapter(ListView.java:464)
05-12 02:36:50.925: E/AndroidRuntime(2205): at com.example.joignabilite.Repertoire.onCreate(Repertoire.java:56)
05-12 02:36:50.925: E/AndroidRuntime(2205): at android.app.Activity.performCreate(Activity.java:4465)
05-12 02:36:50.925: E/AndroidRuntime(2205): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
05-12 02:36:50.925: E/AndroidRuntime(2205): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1931)
05-12 02:36:50.925: E/AndroidRuntime(2205): ... 11 more
05-12 02:36:52.185: I/System.out(2205): [{"nom":"Bob","numero":"243651874"},{"nom":"Alice","numero":"751489525"}]
05-12 02:36:52.225: I/log_tag(2205): Nom: Bob, Numero: 243651874
05-12 02:36:52.235: W/dalvikvm(2205): threadid=11: thread exiting with uncaught exception (group=0x40ab2210)
05-12 02:36:52.245: I/Process(2205): Sending signal. PID: 2205 SIG: 9
05-12 02:36:52.415: D/dalvikvm(2308): GC_FOR_ALLOC freed 35K, 4% free 13167K/13663K, paused 20ms
05-12 02:36:52.415: I/dalvikvm-heap(2308): Grow heap (frag case) to 14.705MB for 1858832-byte allocation
05-12 02:36:52.445: D/dalvikvm(2308): GC_FOR_ALLOC freed 1K, 4% free 14981K/15523K, paused 14ms
05-12 02:36:52.485: D/dalvikvm(2308): GC_CONCURRENT freed 454K, 6% free 14627K/15523K, paused 1ms+2ms
我的 ContactAdapter.java:
package com.example.joignabilite;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
public class ContactAdapter extends BaseAdapter {
// Une liste de Contacts
private List<Contact> mListP;
//Le contexte dans lequel est présent notre adapter
private Context mContext;
//Un mécanisme pour gérer l'affichage graphique depuis un layout XML
private LayoutInflater mInflater;
public ContactAdapter(Context context, List<Contact> aListP) {
mContext = context;
mListP = aListP;
mInflater = LayoutInflater.from(mContext);
}
public int getCount() {
return mListP.size();
}
public Object getItem(int position) {
return mListP.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout layoutItem;
//(1) : Réutilisation des layouts
if (convertView == null) {
//Initialisation de notre item à partir du layout XML "Contact_layout.xml"
layoutItem = (LinearLayout) mInflater.inflate(R.layout.item_contact, parent, false);
} else {
layoutItem = (LinearLayout) convertView;
}
//(2) : Récupération des TextView de notre layout
TextView tv_Nom = (TextView)layoutItem.findViewById(R.id.repertoire_item);
//(3) : Renseignement des valeurs
tv_Nom.setText(mListP.get(position).nom);
//On mémorise la position de la "Contact" dans le composant textview
tv_Nom.setTag(position);
//On ajoute un listener
tv_Nom.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//Lorsque l'on clique sur le nom, on récupère la position de la "Contact"
Integer position = (Integer)v.getTag();
//On prévient les listeners qu'il y a eu un clic sur le TextView "TV_Nom".
sendListener(mListP.get(position), position);
}
});
//On retourne l'item créé.
return layoutItem;
}
/**
* Interface pour écouter les évènements sur le nom d'une Contact
*/
public interface ContactAdapterListener {
public void onClickNom(Contact item, int position);
}
//Contient la liste des listeners
private ArrayList<ContactAdapterListener> mListListener = new ArrayList<ContactAdapterListener>();
/**
* Pour ajouter un listener sur notre adapter
*/
public void addListener(ContactAdapterListener aListener) {
mListListener.add(aListener);
}
private void sendListener(Contact item, int position) {
for(int i = mListListener.size()-1; i >= 0; i--) {
mListListener.get(i).onClickNom(item, position);
}
}
}