android - 调用网络服务时应用程序崩溃

标签 android mysql json

我需要从 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;

}
}

最佳答案

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

protected void onPerExecute(){

应该是:

protected void onPreExecute(){

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

关于android - 调用网络服务时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15661162/

相关文章:

android - 使用 Retrofit2 发送图像

java - 随机排列 Gridview 项目而不重复尝试了多种方法

C# 和 MySQL - 语法不正确?

php - 按金额返回前三笔交易?

json - 喷雾 json 对双子的 Seq 失败

javascript - 正则表达式删除 json 属性

java - Gson 转换为具有两种日期格式的 Json 不起作用

java - 检索手机上已安装应用程序所需功能的列表

android - 如何使用 x264 和 libfdk-aac 为 Android 编译 FFmpeg

php - Docker 暴露端口疯狂