0

我需要从 MySQL 数据库中收集数据并显示在 Listview 中,因此我创建了一个 Web 服务并将其托管在服务器上。然后我开始开发应用程序,但我无法得到结果,我的应用程序在哪里崩溃并且错误日志上没有错误。

这是我显示结果的代码

package com.hotelapp.test;

import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class AllProductsActivity extends ListActivity {

    //Progress Dialog

    private ProgressDialog pDialog;


    //JSONPraser
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String,String>> productsList;

//url to get records
private static String url_all_products = "http://54.243.58.156/get_all_products.php";

//Json Node Names
private static final String TAG_SUCCESS="success";
private static final String TAG_PRODUCTS="products";
private static final String TAG_HID="hid";
private static final String TAG_NAME="name";

JSONArray products = null;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_products);

    //Hashmap for List

    productsList = new ArrayList<HashMap<String, String>>();

    //Load Products In Backgound
    new LoadAllProducts().execute();

    //GEt Listview
    ListView lv = getListView();

    // on seleting single product
    // launching Edit Product Screen
  lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // getting values from selected ListItem
            String hid = ((TextView) view.findViewById(R.id.hid)).getText().toString();
            //Starting new Intnet
            Intent in = new Intent(getApplicationContext(),EditProductActivity.class);
            in.putExtra(TAG_HID,hid);
            startActivityForResult(in,100);
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if result code 100
    if (resultCode == 100) {
        // if result code 100 is received
        // means user edited/deleted product
        // reload this screen again
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

}

/**
 * Background Async Task to Load all product by making HTTP Request
 * */

class LoadAllProducts extends AsyncTask<String,String,String>{

    /**
     * Before starting background thread Show Progress Dialog
     * */

    protected void onPerExecute(){
        super.onPreExecute();
        pDialog = new ProgressDialog(AllProductsActivity.this);
        pDialog.setMessage("Loading Products...Please Wait");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }


    /**
     * getting All products from url
     * */
    @Override
    protected String doInBackground(String... strings) {
       // Building Parameters
        List<NameValuePair> param = new ArrayList<NameValuePair>();

        JSONObject json = jParser.makeHttpRequest(url_all_products,"GET",param);

        Log.d("All Products: ",json.toString());

        try {
            //Cehck for SUCCESS TAG


            int success = json.getInt(TAG_SUCCESS);

            if(success ==1){
               //Get Product Arra

                products = json.getJSONArray(TAG_PRODUCTS);

                //Looping arrays
                for(int i=0; i<products.length();i++){
                    JSONObject c = products.getJSONObject(i);

                    String id = c.getString(TAG_HID);
                    String name = c.getString(TAG_NAME);

                    //creating new Hashmap
                    HashMap<String, String>map = new HashMap<String, String>();

                    map.put(TAG_HID,id);
                    map.put(TAG_NAME,name);

                    productsList.add(map);

                }
            }  else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        NewProductActivity.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }

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

    protected void onPostExecute (String file_url){
        //dismiss the dialog after getting all products
        pDialog.dismiss();

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ListAdapter adapter = new SimpleAdapter(
                        AllProductsActivity.this,productsList,R.layout.list_item,new String[]{TAG_HID,TAG_NAME},
                        new int[]{R.id.hid,R.id.name}
                );

                setListAdapter(adapter);
            }
        });
    }
}
}

这是我的 Json 解析器

  package com.hotelapp.test;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;



  import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
                                  List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

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

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            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 {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
}
4

2 回答 2

3

我的猜测是您的问题是因为 AsyncTask 中的方法之一未正确命名:

protected void onPerExecute(){

它应该是:

protected void onPreExecute(){

您可能会得到一个 NULL 指针,因为您要在此方法中创建的资源实际上并未被创建。

于 2013-03-27T14:20:56.187 回答
0

要检测此类拼写错误,最好使用注解@overwrite。如果名称不正确会产生编译错误。它似乎是被不小心删除了

于 2013-11-10T19:21:20.950 回答