我该如何纠正严重异常 - 异步任务 [英] How can I correct Fatal Exception - Async Task
问题描述
我已经尝试按照下面的教程使用PHP,MySQL连接的Android:
HTTP://www.androidhive .INFO / 2012/05 /如何做连接,Android的使用的PHP,MySQL的/
不过我和下面的教程大部分用户直接从本教程下载的源运行的应用程序,然后单击任一按钮时,收到部队密切错误。
(看看评论部分 - 几乎每个人都具有本教程的一个问题)
logcat的:
03-17 14:40:10.064:D / dalvikvm(2936):GC_CONCURRENT释放177K,5%的游离7488K / 7812K,暂停2MS + 11毫秒,总为33ms
03-17 14:40:16.294:D / dalvikvm(2936):GC_CONCURRENT释放80K,4%免费7856K / 8140K,暂停3毫秒+ 2ms的,总26ms
03-17 14:40:16.784:E / JSON解析器(2936):错误分析数据org.json.JSONException:值< BR java.lang.String类型的,不能被转换为JSONObject的
03-17 14:40:16.794:W / dalvikvm(2936):主题ID = 15:螺纹未捕获的异常退出(组= 0x41d42930)
03-17 14:40:16.794:E / AndroidRuntime(2936):致命异常:AsyncTask的#5
03-17 14:40:16.794:E / AndroidRuntime(2936):了java.lang.RuntimeException:执行doInBackground发生错误()
03-17 14:40:16.794:E / AndroidRuntime(2936):在android.os.AsyncTask $ 3.done(AsyncTask.java:299)
03-17 14:40:16.794:E / AndroidRuntime(2936):在java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
03-17 14:40:16.794:E / AndroidRuntime(2936):在java.util.concurrent.FutureTask.setException(FutureTask.java:219)
03-17 14:40:16.794:E / AndroidRuntime(2936):在java.util.concurrent.FutureTask.run(FutureTask.java:239)
03-17 14:40:16.794:E / AndroidRuntime(2936):在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
03-17 14:40:16.794:E / AndroidRuntime(2936):在java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:573)
03-17 14:40:16.794:E / AndroidRuntime(2936):在java.lang.Thread.run(Thread.java:856)
03-17 14:40:16.794:E / AndroidRuntime(2936):因:显示java.lang.NullPointerException
03-17 14:40:16.794:E / AndroidRuntime(2936):在com.example.androidhive.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:98)
03-17 14:40:16.794:E / AndroidRuntime(2936):在com.example.androidhive.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:1)
03-17 14:40:16.794:E / AndroidRuntime(2936):在android.os.AsyncTask $ 2.call(AsyncTask.java:287)
03-17 14:40:16.794:E / AndroidRuntime(2936):在java.util.concurrent.FutureTask.run(FutureTask.java:234)
03-17 14:40:16.794:E / AndroidRuntime(2936):... 3个
03-17 14:40:17.284:E /窗口管理器(2936):活动com.example.androidhive.NewProductActivity渗漏窗口com.android.internal.policy.impl.PhoneWindow $ {DecorView VE 42488ea0 .... - [R .. ... ID 0,0-296,153},最初这里加入
03-17 14:40:17.284:E /窗口管理器(2936):android.view.WindowLeaked:活动com.example.androidhive.NewProductActivity渗漏窗口com.android.internal.policy.impl.PhoneWindow $ {DecorView VE 42488ea0。 ... - [R ..... ID 0,0-296,153},最初这里加入
03-17 14:40:17.284:E /窗口管理器(2936):在android.view.ViewRootImpl<&初始化GT;(ViewRootImpl.java:354)
03-17 14:40:17.284:E /窗口管理器(2936):在android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
03-17 14:40:17.284:E /窗口管理器(2936):在android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
03-17 14:40:17.284:E /窗口管理器(2936):在android.app.Dialog.show(Dialog.java:281)
03-17 14:40:17.284:E /窗口管理器(2936):在com.example.androidhive.NewProductActivity$CreateNewProduct.on$p$pExecute(NewProductActivity.java:75)
03-17 14:40:17.284:E /窗口管理器(2936):在android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
03-17 14:40:17.284:E /窗口管理器(2936):在android.os.AsyncTask.execute(AsyncTask.java:534)
03-17 14:40:17.284:E /窗口管理器(2936):在com.example.androidhive.NewProductActivity $ 1.onClick(NewProductActivity.java:55)
03-17 14:40:17.284:E /窗口管理器(2936):在android.view.View.performClick(View.java:4204)
03-17 14:40:17.284:E /窗口管理器(2936):在android.view.View $ PerformClick.run(View.java:17355)
03-17 14:40:17.284:E /窗口管理器(2936):在android.os.Handler.handleCallback(Handler.java:725)
03-17 14:40:17.284:E /窗口管理器(2936):在android.os.Handler.dispatchMessage(Handler.java:92)
03-17 14:40:17.284:E /窗口管理器(2936):在android.os.Looper.loop(Looper.java:137)
03-17 14:40:17.284:E /窗口管理器(2936):在android.app.ActivityThread.main(ActivityThread.java:5041)
03-17 14:40:17.284:E /窗口管理器(2936):在java.lang.reflect.Method.invokeNative(本机方法)
03-17 14:40:17.284:E /窗口管理器(2936):在java.lang.reflect.Method.invoke(Method.java:511)
03-17 14:40:17.284:E /窗口管理器(2936):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:793)
03-17 14:40:17.284:E /窗口管理器(2936):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-17 14:40:17.284:E /窗口管理器(2936):在dalvik.system.NativeStart.main(本机方法)
JAVA:NewProductActivity.java
包com.example.androidhive;进口的java.util.ArrayList;
进口的java.util.List;进口org.apache.http.NameValuePair;
进口org.apache.http.message.BasicNameValuePair;
进口org.json.JSONException;
进口org.json.JSONObject;
进口android.app.Activity;
进口android.app.ProgressDialog;
进口android.content.Intent;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.util.Log;
进口android.view.View;
进口android.widget.Button;
进口android.widget.EditText;公共类NewProductActivity延伸活动{//进度对话框
私人ProgressDialog pDialog;JSONParser jsonParser =新JSONParser();
的EditText inputName;
的EditText inputPrice;
的EditText inputDesc;// URL创建新产品
私人静态字符串url_create_product =http://linkingmanager.zxq.net/create_product.php;// JSON节点名称
私有静态最后弦乐TAG_SUCCESS =成功;@覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.add_product); //编辑文本
inputName =(EditText上)findViewById(R.id.inputName);
inputPrice =(EditText上)findViewById(R.id.inputPrice);
inputDesc =(EditText上)findViewById(R.id.inputDesc); //创建按钮
按钮btnCreateProduct =(按钮)findViewById(R.id.btnCreateProduct); //按钮单击事件
btnCreateProduct.setOnClickListener(新View.OnClickListener(){ @覆盖
公共无效的onClick(查看视图){
//创建在后台线程的新产品
新CreateNewProduct()执行();
}
});
}/ **
*背景异步任务来创建新产品
* * /
类CreateNewProduct扩展的AsyncTask<字符串,字符串,字符串> { / **
*启动后台线程显示进度对话框之前
* * /
@覆盖
在preExecute保护无效(){
super.on preExecute();
pDialog =新ProgressDialog(NewProductActivity.this);
pDialog.setMessage(创建产品..);
pDialog.setIndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
} / **
*创建产品
* * /
保护字符串doInBackground(字符串参数... args){
字符串名称= inputName.getText()的toString()。
串价格= inputPrice.getText()的toString()。
。字符串描述= inputDesc.getText()的toString(); //大厦参数
清单<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT;();
params.add(新BasicNameValuePair(姓名,名字));
params.add(新BasicNameValuePair(价格,价格));
params.add(新BasicNameValuePair(说明,说明)); //获取JSON对象
//注意,创建产品网址接受POST方法
JSONObject的JSON = jsonParser.makeHtt prequest(url_create_product,
POST,则params); //检查日志猫来回响应
Log.d(创建回应,json.toString()); //检查成功标记
尝试{
INT成功= json.getInt(TAG_SUCCESS); 如果(成功== 1){
//创建成功产品
意图I =新意图(getApplicationContext(),AllProductsActivity.class);
startActivity(ⅰ); //关闭此屏幕
完();
}其他{
//创建失败产品
}
}赶上(JSONException E){
e.printStackTrace();
} 返回null;
} / **
*在完成后台任务之后辞退进度对话框
* ** /
保护无效onPostExecute(字符串FILE_URL){
//辞退做一次对话
pDialog.dismiss();
}}
}
XML:add_product.xml
< XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=http://schemas.android.com/apk/res/android
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:方向=垂直><! - 名称标签 - >
<的TextView的android:layout_width =FILL_PARENT
机器人:layout_height =WRAP_CONTENT
机器人:文字=产品名称
机器人:paddingLeft =10dip
机器人:paddingRight =10dip
机器人:paddingTop =10dip
机器人:TEXTSIZE =17dip/><! - 输入名称 - >
< EditText上机器人:ID =@ + ID / inputName
机器人:layout_width =FILL_PARENT
机器人:layout_height =WRAP_CONTENT
机器人:layout_margin =5dip
机器人:layout_marginBottom =15dip
机器人:单线=真/><! - 价格标签 - >
<的TextView的android:layout_width =FILL_PARENT
机器人:layout_height =WRAP_CONTENT
机器人:文字=价
机器人:paddingLeft =10dip
机器人:paddingRight =10dip
机器人:paddingTop =10dip
机器人:TEXTSIZE =17dip/><! - 输入价格 - >
< EditText上机器人:ID =@ + ID / inputPrice
机器人:layout_width =FILL_PARENT
机器人:layout_height =WRAP_CONTENT
机器人:layout_margin =5dip
机器人:layout_marginBottom =15dip
机器人:单线=真
安卓的inputType =numberDecimal/><! - 描述标签 - >
<的TextView的android:layout_width =FILL_PARENT
机器人:layout_height =WRAP_CONTENT
机器人:文字=说明
机器人:paddingLeft =10dip
机器人:paddingRight =10dip
机器人:paddingTop =10dip
机器人:TEXTSIZE =17dip/><! - 输入描述 - >
< EditText上机器人:ID =@ + ID / inputDesc
机器人:layout_width =FILL_PARENT
机器人:layout_height =WRAP_CONTENT
机器人:layout_margin =5dip
机器人:layout_marginBottom =15dip
机器人:行=4
机器人:重力=顶/><! - 按钮创建产品 - >
<按钮机器人:ID =@ + ID / btnCreateProduct
机器人:layout_width =FILL_PARENT
机器人:layout_height =WRAP_CONTENT
机器人:文字=创建产品/> < / LinearLayout中>JAVA:AllProductsActivity.java
包com.example.androidhive;进口的java.util.ArrayList;
进口的java.util.HashMap;
进口的java.util.List;进口org.apache.http.NameValuePair;
进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;进口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;
公共类AllProductsActivity扩展ListActivity { //进度对话框
私人ProgressDialog pDialog; //创建JSON解析器对象
JSONParser jParser =新JSONParser(); ArrayList的<&HashMap的LT;字符串,字符串>>产品列表; // URL获得所有产品清单
私人静态字符串url_all_products =http://linkingmanager.zxq.net/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效应初探日志的猫
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(地图);
}
}其他{
//没有发现产品
//启动添加新产品活动
意图I =新意图(getApplicationContext()
NewProductActivity.class);
//关闭所有previous活动
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(ⅰ);
}
}赶上(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(适配器);
}
}); } }
}
XML:all_products.xml< XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=http://schemas.android.com/apk/res/android
机器人:layout_width =FILL_PARENT
机器人:layout_height =FILL_PARENT
机器人:方向=垂直>
<! - 主要的ListView
总是给值id作为列表(@android:ID /列表)
- >
< ListView控件
机器人:ID =@机器人:ID /列表
机器人:layout_width =FILL_PARENT
机器人:layout_height =WRAP_CONTENT/>< / LinearLayout中>
显示java.lang.NullPointerException:
产生的原因
03-17 14:40:16.794:E / AndroidRuntime(2936):在com.example.androidhive.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:98)
在这条线,如果我不是错
Log.d(创建回应,json.toString());
所以这意味着由于某种原因,你得到空此处
JSONObject的JSON = jsonParser.makeHtt prequest(url_create_product,
POST,则params);
也许您的网址是不正确。
I've attempted to follow the following tutorial on connecting Android with PHP, MySQL:
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
However myself and most users following the tutorial are getting force close errors when running the application directly from the downloaded source for the tutorial and clicking either button.
(take a look at the comments section - almost everyone is having an issue with this tutorial)
LOGCAT:
03-17 14:40:10.064: D/dalvikvm(2936): GC_CONCURRENT freed 177K, 5% free 7488K/7812K, paused 2ms+11ms, total 33ms
03-17 14:40:16.294: D/dalvikvm(2936): GC_CONCURRENT freed 80K, 4% free 7856K/8140K, paused 3ms+2ms, total 26ms
03-17 14:40:16.784: E/JSON Parser(2936): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
03-17 14:40:16.794: W/dalvikvm(2936): threadid=15: thread exiting with uncaught exception (group=0x41d42930)
03-17 14:40:16.794: E/AndroidRuntime(2936): FATAL EXCEPTION: AsyncTask #5
03-17 14:40:16.794: E/AndroidRuntime(2936): java.lang.RuntimeException: An error occured while executing doInBackground()
03-17 14:40:16.794: E/AndroidRuntime(2936): at android.os.AsyncTask$3.done(AsyncTask.java:299)
03-17 14:40:16.794: E/AndroidRuntime(2936): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
03-17 14:40:16.794: E/AndroidRuntime(2936): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
03-17 14:40:16.794: E/AndroidRuntime(2936): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
03-17 14:40:16.794: E/AndroidRuntime(2936): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
03-17 14:40:16.794: E/AndroidRuntime(2936): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
03-17 14:40:16.794: E/AndroidRuntime(2936): at java.lang.Thread.run(Thread.java:856)
03-17 14:40:16.794: E/AndroidRuntime(2936): Caused by: java.lang.NullPointerException
03-17 14:40:16.794: E/AndroidRuntime(2936): at com.example.androidhive.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:98)
03-17 14:40:16.794: E/AndroidRuntime(2936): at com.example.androidhive.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:1)
03-17 14:40:16.794: E/AndroidRuntime(2936): at android.os.AsyncTask$2.call(AsyncTask.java:287)
03-17 14:40:16.794: E/AndroidRuntime(2936): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
03-17 14:40:16.794: E/AndroidRuntime(2936): ... 3 more
03-17 14:40:17.284: E/WindowManager(2936): Activity com.example.androidhive.NewProductActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42488ea0 V.E..... R.....ID 0,0-296,153} that was originally added here
03-17 14:40:17.284: E/WindowManager(2936): android.view.WindowLeaked: Activity com.example.androidhive.NewProductActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42488ea0 V.E..... R.....ID 0,0-296,153} that was originally added here
03-17 14:40:17.284: E/WindowManager(2936): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
03-17 14:40:17.284: E/WindowManager(2936): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
03-17 14:40:17.284: E/WindowManager(2936): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
03-17 14:40:17.284: E/WindowManager(2936): at android.app.Dialog.show(Dialog.java:281)
03-17 14:40:17.284: E/WindowManager(2936): at com.example.androidhive.NewProductActivity$CreateNewProduct.onPreExecute(NewProductActivity.java:75)
03-17 14:40:17.284: E/WindowManager(2936): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
03-17 14:40:17.284: E/WindowManager(2936): at android.os.AsyncTask.execute(AsyncTask.java:534)
03-17 14:40:17.284: E/WindowManager(2936): at com.example.androidhive.NewProductActivity$1.onClick(NewProductActivity.java:55)
03-17 14:40:17.284: E/WindowManager(2936): at android.view.View.performClick(View.java:4204)
03-17 14:40:17.284: E/WindowManager(2936): at android.view.View$PerformClick.run(View.java:17355)
03-17 14:40:17.284: E/WindowManager(2936): at android.os.Handler.handleCallback(Handler.java:725)
03-17 14:40:17.284: E/WindowManager(2936): at android.os.Handler.dispatchMessage(Handler.java:92)
03-17 14:40:17.284: E/WindowManager(2936): at android.os.Looper.loop(Looper.java:137)
03-17 14:40:17.284: E/WindowManager(2936): at android.app.ActivityThread.main(ActivityThread.java:5041)
03-17 14:40:17.284: E/WindowManager(2936): at java.lang.reflect.Method.invokeNative(Native Method)
03-17 14:40:17.284: E/WindowManager(2936): at java.lang.reflect.Method.invoke(Method.java:511)
03-17 14:40:17.284: E/WindowManager(2936): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-17 14:40:17.284: E/WindowManager(2936): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-17 14:40:17.284: E/WindowManager(2936): at dalvik.system.NativeStart.main(Native Method)
JAVA: NewProductActivity.java
package com.example.androidhive;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
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.Button;
import android.widget.EditText;
public class NewProductActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;
// url to create new product
private static String url_create_product = "http://linkingmanager.zxq.net/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
// Edit Text
inputName = (EditText) findViewById(R.id.inputName);
inputPrice = (EditText) findViewById(R.id.inputPrice);
inputDesc = (EditText) findViewById(R.id.inputDesc);
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("description", description));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} 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 done
pDialog.dismiss();
}
}
}
XML: add_product.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- Name Label -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Product Name"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:textSize="17dip"/>
<!-- Input Name -->
<EditText android:id="@+id/inputName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:singleLine="true"/>
<!-- Price Label -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Price"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:textSize="17dip"/>
<!-- Input Price -->
<EditText android:id="@+id/inputPrice"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:singleLine="true"
android:inputType="numberDecimal"/>
<!-- Description Label -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Description"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:textSize="17dip"/>
<!-- Input description -->
<EditText android:id="@+id/inputDesc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:lines="4"
android:gravity="top"/>
<!-- Button Create Product -->
<Button android:id="@+id/btnCreateProduct"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Create Product"/>
</LinearLayout>
JAVA: AllProductsActivity.java
package com.example.androidhive;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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;
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://linkingmanager.zxq.net/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
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 {
// 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;
}
/**
* 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);
}
});
}
}
}
XML: all_products.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(@android:id/list)
-->
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Caused by: java.lang.NullPointerException
03-17 14:40:16.794: E/AndroidRuntime(2936): at com.example.androidhive.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:98)
it is this line if im not wrong
Log.d("Create Response", json.toString());
so it means for some reason You get null here
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
maybe Your url is incorrect.
这篇关于我该如何纠正严重异常 - 异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!