ListView с AsyncTask не работает

Я хочу отобразить в моем приложении для Android ListView. Этот ListView содержит две вещи: заголовок и изображение.

Отображать заголовок и изображение, я называю базу данных MySQL с Php. Код Php отправьте мне JSONObject. Я использую JSON для отображения обеих данных в моем ListView.

Проблема в том, что у меня возникает ошибка AsyncTask и исключение NullPointerException при запуске проекта, и я не понимаю, почему.

Поэтому я даю вам свой код и надеюсь, что вы мне поможете.

ListViewMovies.java

      public class ListViewMovies extends Activity {

// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> arraylist;

//php server
private static final String MOVIES_URL = "http://10.0.0.35/BD_Internet_Security_Movies/list_movies.php";

// variables
ListView listview;
ListViewAdapter adapter;
public JSONArray jsonarray;
//String mail ="null";

static String TITLE = "title";
static String IMAGE = "image";

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

// Execute AttemptListMovie AsyncTask
new AttemptListMovie().execute();

}

class AttemptListMovie extends AsyncTask<Void, Void, Void> {

/**
* Before starting background thread Show Progress Dialog
*/
// boolean failure = false;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ListViewMovies.this);
pDialog.setMessage("Attempting for List of movies...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub

/*List<NameValuePair> args = new ArrayList<NameValuePair>();
args.add(new BasicNameValuePair("mail", mail));*/

//Use php to create the JSONObject that we want
JSONObject json = jsonParser.getJSONFromUrl(MOVIES_URL);

// Log.d("json : ", json.toString());

// Create an array
arraylist = new ArrayList<HashMap<String, String>>();

try {
// Locate the array name in JSON
jsonarray = json.getJSONArray("ListMovies");

// checking  log for json response
//  Log.d("JsonArray : ", jsonarray.toString());

for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonobject = jsonarray.getJSONObject(i);
// Choose elem in the JSON Objects
map.put("title", jsonobject.getString("title"));
map.put("image", jsonobject.getString("image"));

// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}@Override
protected void onPostExecute(Void args) {
// Locate the listView in listViewMovies.xml
listview = (ListView) findViewById(R.id.listView);

// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(ListViewMovies.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the pDialog
pDialog.dismiss();
}
}

}

Теперь мой JSONParser.java

    public class JSONParser {
static InputStream is = null;
static JSONObject jsonObj ;
static String json = "";

// default no argument constructor for jsonparser class
public JSONParser() {

}public JSONObject getJSONFromUrl(String url) {

// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);

HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
jsonObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jsonObj;

}

Мой ListeViewAdapter для отображения в listView каждый элемент в каждом элементе

    public class ListViewAdapter extends BaseAdapter {

// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
ImageLoader imageLoader;public ListViewAdapter(Context context, ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
}

/* Permet de savoir le nombre d'item à afficher dans le liste view */
@Override
public int getCount() {
return data.size();
}

@Override
public Object getItem(int position) {
return null;
}

@Override
public long getItemId(int position) {
return 0;
}

public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView title;
ImageView image;

inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View itemView = inflater.inflate(R.layout.activity_list_view_adapter, parent, false);
// Get the position
resultp = data.get(position);

// Locate the TextView in listView.xml
title = (TextView) itemView.findViewById(R.id.title);
// Locate the ImageView in listeView.xml
image = (ImageView) itemView.findViewById(R.id.image);
// Capture position and set results to the TextViews
title.setText(resultp.get(ListViewMovies.TITLE));
imageLoader.DisplayImage(resultp.get(ListViewMovies.IMAGE), image);

return itemView;
}

}

И, наконец, мой PHP-код

    <?php

include ('config.php');

// query the application data
$query = $handler->prepare('select title, image from Movies');

//execute the prepared statement
$query->execute();

// an array to save the application data
$result = array();
// iterate to query result and add every rows into array
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result["ListMovies"][] = $row;
}

echo json_encode($result);
exit;

?>

И моя ошибка в logcat:

        03-19 14:27:17.823  14263-14626/com.enterprisemobility.michael.ca2enterprisemobilitymysqlkozamichael E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null
03-19 14:27:17.823  14263-14626/com.enterprisemobility.michael.ca2enterprisemobilitymysqlkozamichael E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
03-19 14:27:17.827  14263-14626/com.enterprisemobility.michael.ca2enterprisemobilitymysqlkozamichael E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.enterprisemobility.michael.ca2enterprisemobilitymysqlkozamichael, PID: 14263
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
at com.enterprisemobility.michael.ca2enterprisemobilitymysqlkozamichael.ListViewMovies$AttemptListMovie.doInBackground(ListViewMovies.java:82)
at com.enterprisemobility.michael.ca2enterprisemobilitymysqlkozamichael.ListViewMovies$AttemptListMovie.doInBackground(ListViewMovies.java:49)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
03-19 14:27:18.167  14263-14318/com.enterprisemobility.michael.ca2enterprisemobilitymysqlkozamichael D/OpenGLRenderer﹕ endAllStagingAnimators on 0xaf13f400 (RippleDrawable) with handle 0xafd17aa0
03-19 14:27:18.270  14263-14263/com.enterprisemobility.michael.ca2enterprisemobilitymysqlkozamichael E/WindowManager﹕ android.view.WindowLeaked: Activity com.enterprisemobility.michael.ca2enterprisemobilitymysqlkozamichael.ListViewMovies has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{19504f24 V.E..... R......D 0,0-1026,348} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:298)
at com.enterprisemobility.michael.ca2enterprisemobilitymysqlkozamichael.ListViewMovies$AttemptListMovie.onPreExecute(ListViewMovies.java:62)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.enterprisemobility.michael.ca2enterprisemobilitymysqlkozamichael.ListViewMovies.onCreate(ListViewMovies.java:45)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Большое спасибо за Вашу помощь.

Майкл

1

Решение

Задача ещё не решена.

Другие решения

Других решений пока нет …