本文介绍了Android应用程序连接到外部数据库(phpMyAdmin的)使用JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我的Andr​​oid应用程序连接到外部数据库。我在我的phpmyadmin数据库中的表'产品'。当我尝试打开我的应用程序的活动 AllProductsActivity ,这将粉碎,并显示一个错误。

我用调试模式下运行应用程序,并发现它会死时运行到code Log.d(所有产品,json.toString()); 上的行129 的和的JSONObject的值 JSON是空

我新写的应用程序,我真的感到绝望现在。这将是感激,如果你可以提供帮助。谢谢大家。

FYI:程序首先进入 AllProductsActivity.java 然后调用 JSONParser.java EditProductActivity.java 。的布局 AllProductsActivity.java list_item.xml EditProductActivity.java布局 edit_product.xml 。假设用户可以选择从 LIST_ITEM 选项,并转到页关于

以下是错误:

  03-17 17:17:54.003 1821年至1821年/ com.google.andriod.gms.example.hongkongmedicalapp I /编舞:跳过70帧!
该应用程序可能会做它的主线程的工作太多了。
       03-17 17:17:54.963 1821年至1835年/ com.google.andriod.gms.example.hongkongmedicalapp E / JSON解析器:错误解析数据org.json.JSONException:在字符输入0结束
       03-17 17:17:54.963 1821年至1835年/ com.google.andriod.gms.example.hongkongmedicalapp W / dalvikvm:主题ID = 11:螺纹未捕获的异常退出(组= 0x40a71930)
       03-17 17:17:55.203 1821年至1835年/ com.google.andriod.gms.example.hongkongmedicalapp E / AndroidRuntime:致命的异常:AsyncTask的#1
了java.lang.RuntimeException:执行doInBackground发生错误()
       在android.os.AsyncTask $ 3.done(AsyncTask.java:299)
       在java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
       在java.util.concurrent.FutureTask.setException(FutureTask.java:219)
       在java.util.concurrent.FutureTask.run(FutureTask.java:239)
       在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:230)
       在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
        在java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:573)
        在java.lang.Thread.run(Thread.java:856)
 显示java.lang.NullPointerException:产生的原因
        在com.google.andriod.gms.example.hongkongmedicalapp.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:129)
       在com.google.andriod.gms.example.hongkongmedicalapp.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:102)
       在android.os.AsyncTask $ 2.call(AsyncTask.java:287)
       在java.util.concurrent.FutureTask.run(FutureTask.java:234)
       在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:230)
       在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
       在java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:573)
       在java.lang.Thread.run(Thread.java:856)
03-17 17:17:56.093 1821年至1821年/ com.google.andriod.gms.example.hongkongmedicalapp I /编舞:跳过57帧!该应用程序可能会做太多的工作
03-17 17:17:56.473 1821年至1821年/ com.google.andriod.gms.example.hongkongmedicalapp I /编舞:跳过33帧!该应用程序可能会做它的主线程的工作太多了。
03-17 17:17:57.173 1821年至1821年/ com.google.andriod.gms.example.hongkongmedicalapp I /编舞:跳过73帧!该应用程序可能会做它的主线程的工作太多了。
03-17 17:17:58.083 1821年至1821年/ com.google.andriod.gms.example.hongkongmedicalapp E /窗口管理器:活动com.google.andriod.gms.example.hongkongmedicalapp.AllProductsActivity已泄漏窗口com.android.internal。 policy.impl.PhoneWindow $ {DecorView VE 40db1fe0 .... - [R ..... ID 0,0-729,192},最初这里加入
android.view.WindowLeaked:活动com.google.andriod.gms.example.hongkongmedicalapp.AllProductsActivity渗漏窗口com.android.internal.policy.impl.PhoneWindow $ {DecorView VE 40db1fe0 .... - [R ..... ID 0,0-729,192},最初这里加入
        在android.view.ViewRootImpl<&初始化GT;(ViewRootImpl.java:354)
        在android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
        在android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
        在android.app.Dialog.show(Dialog.java:281)
        在com.google.andriod.gms.example.hongkongmedicalapp.AllProductsActivity$LoadAllProducts.on$p$pExecute(AllProductsActivity.java:114)
        在android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
        在android.os.AsyncTask.execute(AsyncTask.java:534)
        在com.google.andriod.gms.example.hongkongmedicalapp.AllProductsActivity.onCreate(AllProductsActivity.java:57)
        在android.app.Activity.performCreate(Activity.java:5104)
        在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
        在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
        在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
        在android.app.ActivityThread.access $ 600(ActivityThread.java:141)
        在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1234)
        在android.os.Handler.dispatchMessage(Handler.java:99)
        在android.os.Looper.loop(Looper.java:137)
        在android.app.ActivityThread.main(ActivityThread.java:5041)
        在java.lang.reflect.Method.invokeNative(本机方法)
        在java.lang.reflect.Method.invoke(Method.java:511)
        在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:793)
        在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
        在dalvik.system.NativeStart.main(本机方法)

下面是AllProductActivity.Java的code:

 包com.google.andriod.gms.example.hongkongmedicalapp;进口android.app.ListActivity;
进口android.app.ProgressDialog;
进口android.content.Intent;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.util.Log;
进口android.view.View;
进口android.widget.AdapterView;
进口android.widget.AdapterView.OnItemClickListener;
进口android.widget.ListAdapter;
进口android.widget.ListView;
进口android.widget.SimpleAdapter;
进口android.widget.TextView;进口org.apache.http.NameValuePair;
进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;进口的java.util.ArrayList;
进口的java.util.HashMap;
进口的java.util.List;公共类AllProductsActivity扩展ListActivity {    //进度对话框
    私人ProgressDialog pDialog;    //创建JSON解析器对象
    JSONParser jParser =新JSONParser();    ArrayList的<&HashMap的LT;字符串,字符串>>产品列表;    // URL获得所有产品清单
    私人静态字符串url_all_products =htt​​p://101.78.175.101:21280/android_connect/get_all_products.php;    // JSON节点名称
    私有静态最后弦乐TAG_SUCCESS =成功;
    私有静态最后弦乐TAG_PRODUCTS =产品;
    私有静态最后弦乐TAG_PID =PID;
    私有静态最后弦乐TAG_NAME =名;    //产品JSONArray
    JSONArray产品= NULL;    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.all_products);        //为哈希映射的ListView
        产品列表=新的ArrayList<&HashMap的LT;字符串,字符串>>();        //装载产品在后台线程
        新LoadAllProducts()执行();        //获取列表视图
        ListView控件LV = getListView();        //在选课单品
        //启动编辑产品屏幕
        lv.setOnItemClickListener(新OnItemClickListener(){            @覆盖
            公共无效onItemClick(适配器视图<>母公司,观景,INT位置,长的id){
                //从选定的ListItem得到的值
                字符串的pid =((的TextView)view.findViewById(R.id.pid))的getText()的toString()。                //开始新意图
                在意向=新意图(getApplicationContext(),EditProductActivity.class);
                //发送到PID下一个活动
                in.putExtra(TAG_PID,PID);                //开始新的活动,期待一些回响应
                startActivityForResult(在100);
            }
        });    }    //从编辑产品的活动响应
    @覆盖
    保护无效的onActivityResult(INT申请code,INT结果code,意图数据){
        super.onActivityResult(要求code,结果code,数据);
        //如果结果code 100
        如果(结果code == 100){
            //如果结果code 100接收
            //意味着用户编辑/删除产品
            //重新载入该画面
            意向意图= getIntent();
            完();
            startActivity(意向);
        }    }    / **
     *背景异步任务以通过HTTP请求负载的所有产品
     * * /
    类LoadAllProducts扩展的AsyncTask<字符串,字符串,字符串> {        / **
         *启动后台线程显示进度对话框之前
         * * /
        @覆盖
        在preExecute保护无效(){
            super.on preExecute();
            pDialog =新ProgressDialog(AllProductsActivity.this);
            pDialog.setMessage(加载产品请稍候......);
            pDialog.setIndeterminate(假);
            pDialog.setCancelable(假);
            pDialog.show();        }        / **
         *让所有的产品网址
         * * /
        保护字符串doInBackground(字符串参数... args){
            //大厦参数
            清单<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT;();
            // URL从获取JSON字符串
            JSONObject的JSON = jParser.makeHtt prequest(url_all_products,GET,则params);            //检查JSON效应初探日志的猫
            //当我使用调试模式,我发现程序在这条线上和JSON的JSONObject的价值死者为空
            Log.d(所有产品,json.toString());            尝试{
                //检查成功TAG
                INT成功= json.getInt(TAG_SUCCESS);                如果(成功== 1){
                    发现//产品
                    //获取产品阵列
                    产品= json.getJSONArray(TAG_PRODUCTS);                    //产品通过所有循环
                    的for(int i = 0; I< products.length();我++){
                        JSONObject的C = products.getJSONObject(I)                        //存储在变量中的每个JSON项目
                        字符串ID = c.getString(TAG_PID);
                        字符串名称= c.getString(TAG_NAME);                        //创建新的HashMap
                        HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();                        //将每个子节点的HashMap键=>值
                        map.put(TAG_PID,身份证);
                        map.put(TAG_NAME,名);                        //添加HashList到ArrayList的
                        productsList.add(地图);
                    }
                }其他{                }
            }赶上(JSONException E){
                e.printStackTrace();
            }            返回null;
        }        / **
         *在完成后台任务之后辞退进度对话框
         * ** /
        保护无效onPostExecute(字符串FILE_URL){
            //让所有的产品后,关闭该对话框
            pDialog.dismiss();            //从后台线程更新界面
            runOnUiThread(新的Runnable(){
                公共无效的run(){
                    / **
                     *更新解析JSON数据到ListView控件
                     * * /
                    ListAdapter适配器=新SimpleAdapter(
                            AllProductsActivity.this,产品列表,R.layout.list_item,新的String [] {TAG_PID,TAG_NAME},新的INT [] {R.id.pid,R.id.name});
                    //更新列表视图
                    setListAdapter(适配器);
                }
            });        }    }
}

下面是EditProductActivity.java的code

 包com.google.andriod.gms.example.hongkongmedicalapp;进口android.app.Activity;
进口android.app.ProgressDialog;
进口android.content.Intent;
进口android.graphics.Bitmap;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.os.StrictMode;
进口android.util.Log;
进口android.widget.Button;
进口android.widget.EditText;
进口android.widget.TextView;进口org.apache.http.NameValuePair;
进口org.apache.http.message.BasicNameValuePair;
进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;进口的java.util.ArrayList;
进口的java.util.List;公共类EditProductActivity延伸活动{    TextView的txtName的;
    TextView的txtPrice;
    TextView的txtDesc;
    TextView的txtUses;
    TextView的txtSide;
    TextView的TXT precau;
    TextView的txtinterac;
    TextView的txtoverdose;
    串PID;    //进度对话框
    私人ProgressDialog pDialog;// JSON节点名称
    私有静态最后弦乐TAG_SUCCESS =成功;
    私有静态最后弦乐TAG_PRODUCT =产品;
    私有静态最后弦乐TAG_PID =PID;
    私有静态最后弦乐TAG_NAME =名;
    私有静态最后弦乐TAG_PRICE =价格;
    私有静态最后弦乐TAG_DESCRIPTION =说明;
    私有静态最后弦乐TAG_USES =使用;
    私有静态最后弦乐TAG_SIDEEFFECTS =sideeffects;
    私有静态最后弦乐TAG_ preCAUTIONS =precauctions
    私有静态最后弦乐TAG_INTERACTIONS =互动;
    私有静态最后弦乐TAG_OVERDOSE =过量;    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.edit_product);
        如果(android.os.Build.VERSION.SDK_INT> 9){
            。StrictMode.ThreadPolicy政策=新StrictMode.ThreadPolicy.Builder()permitAll()建();
            StrictMode.setThreadPolicy(政策);
        }        //获取来自意图产品的详细信息
        意向I = getIntent();        //从意图获取产品ID(PID)
        PID = i.getStringExtra(TAG_PID);        //获取在后台线程完整的产品细节
        GetProductDetails dproductdetail =新GetProductDetails();
        dproductdetail.execute();    }    / **
     *背景异步任务以获得完整的产品细节
     * * /
    类GetProductDetails扩展的AsyncTask<字符串,字符串,字符串> {
        // JSON解析器类
        JSONParser jsonParser =新JSONParser();
        / **
         *启动后台线程显示进度对话框之前
         * * /
        @覆盖
        在preExecute保护无效(){
            super.on preExecute();
            pDialog =新ProgressDialog(EditProductActivity.this);
            pDialog.setMessage(装载产品的详细信息,请稍候...);
            pDialog.setIndeterminate(假);
            pDialog.setCancelable(真);
            pDialog.show();
        }        / **
         *获取产品的详细信息在后台线程
         * * /
        保护字符串doInBackground(字符串... PARAMS){            //从后台线程更新界面
            runOnUiThread(新的Runnable(){
                公共无效的run(){
                    //检查成功标记
                    诠释成功;
                    尝试{
                        //大厦参数
                        清单<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT;();
                        params.add(新BasicNameValuePair(PID,PID));                        //通过HTTP请求获得产品的详细信息
                        //注意产品的详细信息URL会使用GET请求
                        JSONObject的JSON = jsonParser.makeHtt prequest(http://101.78.175.101:21280/android_connect/get_product_details.php,GET,则params);                        //检查你的日志,JSON响应
                        Log.d(单一产品详细信息,json.toString());                        // JSON的成功标签
                        成功= json.getInt(TAG_SUCCESS);
                        如果(成功== 1){
                            //成功接收产品的详细信息
                            JSONArray productObj = json.getJSONArray(TAG_PRODUCT); // JSON数组                            //从JSON数组的第一个产品对象
                            的JSONObject产物= productObj.getJSONObject(0);                            //与本产品的PID发现
                            //编辑文本
                            txtName的=(的TextView)findViewById(R.id.inputName);
                            txtPrice =(的TextView)findViewById(R.id.inputPrice);
                            txtDesc =(的TextView)findViewById(R.id.inputDesc);
                            txtUses =(的TextView)findViewById(R.id.inputuses);
                            txtSide =(的TextView)findViewById(R.id.inputsideeffects);
                            TXT precau =(的TextView)findViewById(R.id.input precautions);
                            txtinterac =(的TextView)findViewById(R.id.inputinteractions);
                            txtoverdose =(的TextView)findViewById(R.id.inputoverdose);
                            //在显示的EditText产品数据
                            txtName.setText(product.getString(TAG_NAME));
                            txtPrice.setText(product.getString(TAG_PRICE));
                            txtDesc.setText(product.getString(TAG_DESCRIPTION));
                            txtUses.setText(product.getString(TAG_USES));
                            txtSide.setText(product.getString(TAG_SIDEEFFECTS));
                            TXT precau.setText(product.getString(TAG_ preCAUTIONS));
                            txtinterac.setText(product.getString(TAG_INTERACTIONS));
                            txtoverdose .setText(product.getString(TAG_OVERDOSE));                        }其他{
                            //产品具有pid未找到
                        }
                    }赶上(JSONException E){
                        e.printStackTrace();
                    }
                }
            });            返回null;
        }        / **
         *在完成后台任务之后辞退进度对话框
         * ** /
        保护无效onPostExecute(字符串FILE_URL){
            //关闭该对话框一旦得了所有细节
            pDialog.dismiss();
        }
    }}

下面是JSONParser.java的code

 包com.google.andriod.gms.example.hongkongmedicalapp;进口android.util.Log;进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.NameValuePair;
进口org.apache.http.client.ClientProtocolException;
进口org.apache.http.client.entity.UrlEn codedFormEntity;
进口org.apache.http.client.methods.HttpGet;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.client.utils.URLEn codedUtils;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.json.JSONException;
进口org.json.JSONObject;进口java.io.BufferedReader中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口java.io.UnsupportedEncodingException;
进口的java.util.List;公共类JSONParser {    静态InputStream为= NULL;
    静态的JSONObject jObj = NULL;
    静态JSON字符串=;    //构造
    公共JSONParser(){    }    //函数得到JSON的网址
    //通过HTTP POST或GET mehtod
    公众的JSONObject makeHtt prequest(URL字符串,字符串的方法,列表与LT;&的NameValuePair GT; PARAMS){        //使HTTP请求
        尝试{            //检查请求的方法
            如果(方法==POST){
                //请求方法是POST
                // defaultHttpClient
                DefaultHttpClient的HttpClient =新DefaultHttpClient();
                HttpPost httpPost =新HttpPost(URL);
                httpPost.setEntity(新UrlEn codedFormEntity(PARAMS));                HTT presponse HTT presponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = HTT presponse.getEntity();
                是= httpEntity.getContent();            }否则如果(方法==GET){
                //请求方法是GET
                DefaultHttpClient的HttpClient =新DefaultHttpClient();
                字符串中的paramString = URLEn codedUtils.format(参数,可以UTF-8);
                网址+ =? +中的paramString;
                HTTPGET HTTPGET =新HTTPGET(URL);                HTT presponse HTT presponse = httpClient.execute(HTTPGET);
                HttpEntity httpEntity = HTT presponse.getEntity();
                是= httpEntity.getContent();
            }
        }赶上(UnsupportedEncodingException五){
            e.printStackTrace();
        }赶上(ClientProtocolException E){
            e.printStackTrace();
        }赶上(IOException异常五){
            e.printStackTrace();
        }        尝试{
            读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
                    是,ISO-8859-1),8);
            StringBuilder的SB =新的StringBuilder();
            串线= NULL;
            而((行= reader.readLine())!= NULL){
                sb.append(行+\\ n);
            }
            is.close();
            JSON = sb.toString();
        }赶上(例外五){
            Log.e(缓冲区错误,错误转换结果+ e.toString());
        }        //尝试分析字符串到一个JSON对象
        尝试{
            jObj =新的JSONObject(JSON);
        }赶上(JSONException E){
            Log.e(JSON解析器,错误分析数据+ e.toString());
        }        //返回JSON字符串
        返回jObj;    }
}

我的PHP脚本get_product_details:

 < PHP/ *
 *继code将得到单品细节
 *一个产品是由产品id标识(PID)
 * ///数组JSON响应
$响应=阵列();
//其中包括DB连接类
require_once __DIR__。 /db_connect.php';//连接到数据库
$ DB =新DB_CONNECT();//检查数据后
如果(使用isset($ _ GET [PID])){
    $ PID = $ _GET ['PID'];    //从产品表中的产品
    $结果= mysql_query(SELECT * FROM产品WHERE PID = $ PID);    如果(!空($结果)){
        //检查空结果
        如果(mysql_num_rows($结果)大于0){            $结果= mysql_fetch_array($结果);            $产品=阵列();
            $产品[PID] = $结果[PID];
            $产品[名称] = $结果[名称];
            $产品[价格] = $结果[价格];
            $产品[说明] = $结果[描述];
            $产品[使用] = $结果[利用];
            $产品[sideeffects] = $结果[sideeffects];
            $产品[precauctions] = $结果[precauctions];
            $产品[互动] = $结果[互动];
            $产品[过量] = $结果[用药过量];
            $产品[created_at] = $结果[created_at];
            $产品[的updated_at] = $结果[的updated_at];
            //成功
            $响应[成功] = 1;            //用户节点
            $响应[产品] =阵列();            array_push($响应[产品],$产品);            //呼应JSON响应
            回声json_en code($响应);
        }其他{
            //没有产品找到
            $响应[成功] = 0;
            $响应[消息] =没有产品找到了;            //回声没有用户JSON
            回声json_en code($响应);
        }
    }其他{
        //没有产品找到
        $响应[成功] = 0;
        $响应[消息] =没有产品找到了;        //回声没有用户JSON
        回声json_en code($响应);
    }
}其他{
    //必填字段缺失
    $响应[成功] = 0;
    $响应[消息] =必填字段(s)是失踪;    //呼应JSON响应
    回声json_en code($响应);
}
?>


解决方案

我认为错误的主要原因是,您的服务器不返回JSON。

我试图打开在浏览器中,不幸的是,我得到了一个空白页。

有关有效的JSON它应该至少返回 {}

您可以手动验证JSON这个流行的工具

所以,首先,你必须让你的服务器返回有效JSON,然后我们可以看到,如果一切工作正常。

I'm trying to connect my android application to an external database. I have a table 'products' in my phpmyadmin database. when I try to open the activity AllProductsActivity in my app, it will crush and show an error.

I have used debug mode to run the app and find that it will dead when runs to the code Log.d("All Products: ", json.toString()); on line 129 and the value of JSONObject json is null.

I am new to write app and I really feel desperate right now. It would be thankful if you can help. thank you to everyone.

FYI:The program first goes to AllProductsActivity.java and then it calls JSONParser.java and EditProductActivity.java. The layout of the AllProductsActivity.java is list_item.xml and the layout of EditProductActivity.java is edit_product.xml. User suppose can choose the option from the list_item and go to regarding page.

Below is the error:

       03-17 17:17:54.003    1821-1821/com.google.andriod.gms.example.hongkongmedicalapp I/Choreographer﹕ Skipped 70 frames!
The application may be doing too much work on its main thread.
       03-17 17:17:54.963    1821-1835/com.google.andriod.gms.example.hongkongmedicalapp E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
       03-17 17:17:54.963    1821-1835/com.google.andriod.gms.example.hongkongmedicalapp W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x40a71930)
       03-17 17:17:55.203    1821-1835/com.google.andriod.gms.example.hongkongmedicalapp E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
       at android.os.AsyncTask$3.done(AsyncTask.java:299)
       at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
       at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
       at java.util.concurrent.FutureTask.run(FutureTask.java:239)
       at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
        at java.lang.Thread.run(Thread.java:856)
 Caused by: java.lang.NullPointerException
        at com.google.andriod.gms.example.hongkongmedicalapp.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:129)
       at com.google.andriod.gms.example.hongkongmedicalapp.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:102)
       at android.os.AsyncTask$2.call(AsyncTask.java:287)
       at java.util.concurrent.FutureTask.run(FutureTask.java:234)
       at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
       at java.lang.Thread.run(Thread.java:856)
03-17 17:17:56.093    1821-1821/com.google.andriod.gms.example.hongkongmedicalapp I/Choreographer﹕ Skipped 57 frames!  The application may be doing too much work on its
03-17 17:17:56.473    1821-1821/com.google.andriod.gms.example.hongkongmedicalapp I/Choreographer﹕ Skipped 33 frames!  The application may be doing too much work on its main thread.
03-17 17:17:57.173    1821-1821/com.google.andriod.gms.example.hongkongmedicalapp I/Choreographer﹕ Skipped 73 frames!  The application may be doing too much work on its main thread.
03-17 17:17:58.083    1821-1821/com.google.andriod.gms.example.hongkongmedicalapp E/WindowManager﹕ Activity com.google.andriod.gms.example.hongkongmedicalapp.AllProductsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40db1fe0 V.E..... R.....ID 0,0-729,192} that was originally added here
android.view.WindowLeaked: Activity com.google.andriod.gms.example.hongkongmedicalapp.AllProductsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40db1fe0 V.E..... R.....ID 0,0-729,192} that was originally added here
        at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
        at android.app.Dialog.show(Dialog.java:281)
        at com.google.andriod.gms.example.hongkongmedicalapp.AllProductsActivity$LoadAllProducts.onPreExecute(AllProductsActivity.java:114)
        at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
        at android.os.AsyncTask.execute(AsyncTask.java:534)
        at com.google.andriod.gms.example.hongkongmedicalapp.AllProductsActivity.onCreate(AllProductsActivity.java:57)
        at android.app.Activity.performCreate(Activity.java:5104)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
        at android.app.ActivityThread.access$600(ActivityThread.java:141)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5041)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
        at dalvik.system.NativeStart.main(Native Method)

Below is the code of AllProductActivity.Java:

package com.google.andriod.gms.example.hongkongmedicalapp;

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.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

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;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> productsList;

    // url to get all products list
    private static String url_all_products = "http://101.78.175.101:21280/android_connect/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_PID = "pid";
    private static final String TAG_NAME = "name";

    // products JSONArray
    JSONArray products = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_products);

        // Hashmap for ListView
        productsList = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadAllProducts().execute();

        // Get listview
        ListView lv = getListView();

        // on seleting single product
        // launching Edit Product Screen
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
                // getting values from selected ListItem
                String pid = ((TextView) view.findViewById(R.id.pid)).getText().toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),EditProductActivity.class);
                // sending pid to next activity
                in.putExtra(TAG_PID, pid);

                // starting new activity and expecting some response back
                startActivityForResult(in, 100);
            }
        });

    }

    // Response from Edit Product Activity
    @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
         * */
        @Override
        protected void onPreExecute() {
            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
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

            // Check your log cat for JSON reponse
            //When I use debug mode, I find the program dead on this line and the value of JSONObject json is null
            Log.d("All Products: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_PRODUCTS);

                    // looping through All Products
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_PID);
                        String name = c.getString(TAG_NAME);

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

                        // adding each child node to HashMap key => value
                        map.put(TAG_PID, id);
                        map.put(TAG_NAME, name);

                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {

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

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();

            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            AllProductsActivity.this, productsList,R.layout.list_item, new String[] { TAG_PID,TAG_NAME},new int[] { R.id.pid, R.id.name });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }

    }
}

Below is the code of EditProductActivity.java

package com.google.andriod.gms.example.hongkongmedicalapp;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

public class EditProductActivity extends Activity {

    TextView txtName;
    TextView txtPrice;
    TextView txtDesc;
    TextView txtUses;
    TextView txtSide;
    TextView txtPrecau;
    TextView txtinterac;
    TextView txtoverdose;
    String pid;

    // Progress Dialog
    private ProgressDialog pDialog;

// JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCT = "product";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";
    private static final String TAG_PRICE = "price";
    private static final String TAG_DESCRIPTION = "description";
    private static final String TAG_USES = "uses";
    private static final String TAG_SIDEEFFECTS = "sideeffects";
    private static final String TAG_PRECAUTIONS= "precauctions";
    private static final String TAG_INTERACTIONS = "interactions";
    private static final String TAG_OVERDOSE = "overdose";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_product);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        // getting product details from intent
        Intent i = getIntent();

        // getting product id (pid) from intent
        pid = i.getStringExtra(TAG_PID);

        // Getting complete product details in background thread
        GetProductDetails dproductdetail = new GetProductDetails();
        dproductdetail.execute();

    }

    /**
     * Background Async Task to Get complete product details
     * */
    class GetProductDetails extends AsyncTask<String, String, String> {
        // JSON parser class
        JSONParser jsonParser = new JSONParser();
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EditProductActivity.this);
            pDialog.setMessage("Loading product details. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Getting product details in background thread
         * */
        protected String doInBackground(String... params) {

            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    // Check for success tag
                    int success;
                    try {
                        // Building Parameters
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("pid", pid));

                        // getting product details by making HTTP request
                        // Note that product details url will use GET request
                        JSONObject json = jsonParser.makeHttpRequest("http://101.78.175.101:21280/android_connect/get_product_details.php", "GET", params);

                        // check your log for json response
                        Log.d("Single Product Details", json.toString());

                        // json success tag
                        success = json.getInt(TAG_SUCCESS);
                        if (success == 1) {
                            // successfully received product details
                            JSONArray productObj = json.getJSONArray(TAG_PRODUCT); // JSON Array

                            // get first product object from JSON Array
                            JSONObject product = productObj.getJSONObject(0);

                            // product with this pid found
                            // Edit Text
                            txtName = (TextView) findViewById(R.id.inputName);
                            txtPrice = (TextView) findViewById(R.id.inputPrice);
                            txtDesc = (TextView) findViewById(R.id.inputDesc);
                            txtUses = (TextView) findViewById(R.id.inputuses);
                            txtSide = (TextView) findViewById(R.id.inputsideeffects);
                            txtPrecau = (TextView) findViewById(R.id.inputprecautions);
                            txtinterac= (TextView) findViewById(R.id.inputinteractions);
                            txtoverdose = (TextView) findViewById(R.id.inputoverdose);


                            // display product data in EditText
                            txtName.setText(product.getString(TAG_NAME));
                            txtPrice.setText(product.getString(TAG_PRICE));
                            txtDesc.setText(product.getString(TAG_DESCRIPTION));
                            txtUses.setText(product.getString(TAG_USES));
                            txtSide.setText(product.getString(TAG_SIDEEFFECTS));
                            txtPrecau.setText(product.getString(TAG_PRECAUTIONS));
                            txtinterac.setText(product.getString(TAG_INTERACTIONS));
                            txtoverdose .setText(product.getString(TAG_OVERDOSE));

                        }else{
                            // product with pid not found
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once got all details
            pDialog.dismiss();
        }
    }



}

Below is the code of JSONParser.java

package com.google.andriod.gms.example.hongkongmedicalapp;

import android.util.Log;

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 java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

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 mehtod
    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;

    }
}

My php script get_product_details:

<?php

/*
 * Following code will get single product details
 * A product is identified by product id (pid)
 */

// array for JSON response
$response = array();


// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// check for post data
if (isset($_GET["pid"])) {
    $pid = $_GET['pid'];

    // get a product from products table
    $result = mysql_query("SELECT *FROM products WHERE pid = $pid");

    if (!empty($result)) {
        // check for empty result
        if (mysql_num_rows($result) > 0) {

            $result = mysql_fetch_array($result);

            $products = array();
            $products["pid"] = $result["pid"];
            $products["name"] = $result["name"];
            $products["price"] = $result["price"];
            $products["description"] = $result["description"];
            $products["uses"] = $result["uses"];
            $products["sideeffects"] = $result["sideeffects"];
            $products["precauctions"] = $result["precauctions"];
            $products["interactions"] = $result["interactions"];
            $products["overdose"] = $result["overdose"];
            $products["created_at"] = $result["created_at"];
            $products["updated_at"] = $result["updated_at"];
            // success
            $response["success"] = 1;

            // user node
            $response["products"] = array();

            array_push($response["products"], $products);

            // echoing JSON response
            echo json_encode($response);
        } else {
            // no product found
            $response["success"] = 0;
            $response["message"] = "No product found";

            // echo no users JSON
            echo json_encode($response);
        }
    } else {
        // no product found
        $response["success"] = 0;
        $response["message"] = "No product found";

        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?>
解决方案

I think that the main reason of error is that your server doesn't return json.

I tried to open http://101.78.175.101:21280/android_connect/get_all_products.php in the browser, and, unfortunately, I got an empty page.

For valid JSON it should return at least {}.

You can manually validate JSON with this popular tool http://jsonlint.com/

So, firstly, you have to make your server return valid JSON, and then we can see if everything else is working fine.

这篇关于Android应用程序连接到外部数据库(phpMyAdmin的)使用JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 23:12