Java 异步任务中的Android崩溃
当我从显示项目所有内容的活动中运行projent并运行AsyncTask时,应用程序崩溃显示以下错误消息:Java 异步任务中的Android崩溃,java,android,android-activity,android-asynctask,progressdialog,Java,Android,Android Activity,Android Asynctask,Progressdialog,当我从显示项目所有内容的活动中运行projent并运行AsyncTask时,应用程序崩溃显示以下错误消息: 06-17 20:56:52.856 418-428/? E/art﹕ Failed sending reply to debugger: Broken pipe 06-17 20:57:07.391 418-767/com.example.user.project_test E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #3
06-17 20:56:52.856 418-428/? E/art﹕ Failed sending reply to debugger: Broken pipe
06-17 20:57:07.391 418-767/com.example.user.project_test E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #3
Process: com.example.user.project_test, PID: 418
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:304)
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: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6357)
at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:909)
at android.view.ViewGroup.invalidateChild(ViewGroup.java:4690)
at android.view.View.invalidateInternal(View.java:11801)
at android.view.View.invalidate(View.java:11765)
at android.view.View.invalidate(View.java:11749)
at android.widget.TextView.checkForRelayout(TextView.java:6858)
at android.widget.TextView.setText(TextView.java:4057)
at android.widget.TextView.setText(TextView.java:3915)
at android.widget.TextView.setText(TextView.java:3890)
at com.example.user.project.itemActivity$getitem.doInBackground(itemActivity.java:132)
at com.example.user.project.itemActivity$getitem.doInBackground(itemActivity.java:84)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
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)
06-17 20:57:07.612 418-418/com.example.user.project_test E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.user.project.itemActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{19feb64d 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:271)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.Dialog.show(Dialog.java:298)
at com.example.user.project.itemActivity$getitem.onPreExecute(itemActivity.java:96)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:591)
at android.os.AsyncTask.execute(AsyncTask.java:539)
at com.example.user.project.itemActivity.onCreate(itemActivity.java:71)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.description.invoke(Native description)
at java.lang.reflect.description.invoke(description.java:372)
at com.android.internal.os.ZygoteInit$descriptionAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
您不能在后台线程中触摸UI元素(如setText),您可能希望在runOnUIThread()中包装,或者在onPre/onPost execute中执行这些操作(它们在UI线程中)并阅读有关android线程的内容您不能在后台线程中触摸UI元素(如setText),您可能希望在runOnUIThread()中包装或者在onPre/onPost execute中执行这些操作(它们在UI线程上)并阅读有关android线程的内容您的问题在于以下两行:
itemname.setText(item.getString(TAG_ITEM_NAME));
itemdescription.setText(item.getString(TAG_ITEM_DESCRIPTION));
2种选择:
onPostExecute
并从那里更新编辑文本RunOnUiThread
并更新其中的两个编辑文本您的问题是以下两行:
itemname.setText(item.getString(TAG_ITEM_NAME));
itemdescription.setText(item.getString(TAG_ITEM_DESCRIPTION));
2种选择:
onPostExecute
并从那里更新编辑文本RunOnUiThread
并更新其中的两个编辑文本尝试将此添加到
doInBackground()
或者将这两行放在onPostExecute()
这是你的全班同学
public class itemActivity extends AppCompatActivity {
private static final String TAG_SUCCESS = "success";
private static final String TAG_item = "item";
private static final String TAG_item_NAME = "name";
private static final String TAG_item_description = "description";
Integer item_id;
String name;
String username;
String description;
TextView itemname;
TextView itemdescription;
ProgressDialog pDialog;
JSONParser jParser;
RecyclerView recycler;
ActionBar actionBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item);
Intent i = getIntent();
if (i.hasExtra("item_id")) {
Bundle bd = getIntent().getExtras();
/*if ((!bd.getString("name").equals(null) || bd.getString("name").trim().length() > 0) && (!bd.getString("username").equals(null) || bd.getString("username").trim().length() > 0) && (!bd.getString("description").equals(null) || bd.getString("description").trim().length() > 0)) {
name = bd.getString("name");
username = bd.getString("username");
description = bd.getString("description");
}*/
item_id = bd.getInt("item_id");
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setTitle(R.string.app_name);
itemname = (TextView) findViewById(R.id.itemName);
itemdescription = (TextView) findViewById(R.id.itemdescription);
new getitem().execute();
/*recycler = (RecyclerView) findViewById(R.id.recycler);
recycler.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recycler.setLayoutManager(layoutManager);*/
}
/**
* Background Async Task to Get complete item details
*/
class getitem extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
if (pDialog != null) {
pDialog = null;
}
pDialog = new ProgressDialog(itemActivity.this);
pDialog.setMessage(getResources().getString(R.string.loadingitem));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Getting item details in background thread
*/
protected String doInBackground(String... params) {
// updating UI from Background Thread
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> myParameters = new ArrayList<NameValuePair>();
myParameters.add(new BasicNameValuePair("item_id", Integer.toString(item_id)));
// getting item details by making HTTP request
// Note that item details url will use GET request
jParser = new JSONParser();
JSONObject json = jParser.makeHttpRequest(AppConfig.URL_GET_item, "GET", myParameters);
// check your log for json response
Log.d("Single item Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received item details
JSONArray itemObj = json.getJSONArray(TAG_item); // JSON Array
// get first item object from JSON Array
JSONObject item = itemObj.getJSONObject(0);
// item with this pid found
// Edit Text
runOnUiThread(new Runnable() {
@Override
public void run() {
itemname.setText(item.getString(TAG_item_NAME));
itemdescription.setText(item.getString(TAG_item_description));
}
});
} else {
// item 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();
}
}
}
公共类itemActivity扩展了AppCompative活动{
私有静态最终字符串标记_SUCCESS=“SUCCESS”;
私有静态最终字符串标记\u item=“item”;
私有静态最终字符串标记\u项\u NAME=“NAME”;
私有静态最终字符串标记\u item\u description=“description”;
整型项目标识;
字符串名;
字符串用户名;
字符串描述;
TextView项目名称;
文本视图项目描述;
ProgressDialog;
JSONParser-jParser;
回收者查看回收者;
ActionBar ActionBar;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_项);
Intent i=getIntent();
如果(i.hasExtra(“项目id”)){
Bundle bd=getIntent().getExtras();
/*如果((!bd.getString(“name”).equals(null)| | bd.getString(“name”).trim().length()>0)和(!bd.getString(“用户名”).equals(null)| | | bd.getString(“用户名”).trim().length()>0)和(!bd.getString(“说明”).equals(null)| | bd.getString(“说明”).trim().length()>0)){
name=bd.getString(“name”);
用户名=bd.getString(“用户名”);
description=bd.getString(“description”);
}*/
item_id=bd.getInt(“item_id”);
}
Toolbar Toolbar=(Toolbar)findViewById(R.id.Toolbar);
设置支持操作栏(工具栏);
actionBar=getSupportActionBar();
actionBar.setTitle(R.string.app_name);
itemname=(TextView)findViewById(R.id.itemname);
itemdescription=(TextView)findViewById(R.id.itemdescription);
新建getitem().execute();
/*recycler=(RecyclerView)findViewById(R.id.recycler);
回收商。setHasFixedSize(真);
LinearLayoutManager布局管理器=新的LinearLayoutManager(getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
回收器。setLayoutManager(layoutManager)*/
}
/**
*获取完整项目详细信息的后台异步任务
*/
类getitem扩展了异步任务{
/**
*在启动后台线程显示进度对话框之前
*/
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
如果(pDialog!=null){
pDialog=null;
}
pDialog=newprogressdialog(itemActivity.this);
setMessage(getResources().getString(R.string.loadingitem));
pDialog.setUndeterminate(假);
pDialog.setCancelable(假);
pDialog.show();
}
/**
*在后台线程中获取项目详细信息
*/
受保护的字符串doInBackground(字符串…参数){
//从后台线程更新UI
//检查成功标签
成功;
试一试{
//建筑参数
List myParameters=new ArrayList();
添加(新的BasicNameValuePair(“item_id”,Integer.toString(item_id));
//通过发出HTTP请求获取项目详细信息
//请注意,项目详细信息url将使用GET请求
jParser=newjsonparser();
JSONObject json=jParser.makeHttpRequest(AppConfig.URL_GET_item,“GET”,myParameters);
//检查日志中的json响应
Log.d(“单个项目详细信息”,json.toString());
//json成功标记
success=json.getInt(TAG_success);
如果(成功==1){
//已成功接收项目详细信息
JSONArray itemObj=json.getJSONArray(TAG_item);//json数组
//从JSON数组中获取第一个项对象
JSONObject item=itemObj.getJSONObject(0);
//找到具有此pid的项
//编辑文本
runOnUiThread(新的Runnable(){
@凌驾
公开募捐{
itemname.setText(item.getString(TAG_item_NAME));
itemsdescription.setText(item.getString(TAG_item_description));
}
});
}否则{
//找不到具有pid的项
}
}捕获(JSONException e){
e、 printStackTrace();
}
返回null;
}
/**
*完成后台任务后,关闭“进度”对话框
* *
*/
受保护的void onPostExecute(字符串文件\u url){
//获得所有详细信息后关闭对话框
pDialog.disclose();
}
}
}
尝试将此添加到doInBackground()中。
或者将这两行放在onPostExecute()
这是你的全班同学
public class itemActivity extends AppCompatActivity {
private static final String TAG_SUCCESS = "success";
private static final String TAG_item = "item";
private static final String TAG_item_NAME = "name";
private static final String TAG_item_description = "description";
Integer item_id;
String name;
String username;
String description;
TextView itemname;
TextView itemdescription;
ProgressDialog pDialog;
JSONParser jParser;
RecyclerView recycler;
ActionBar actionBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item);
Intent i = getIntent();
if (i.hasExtra("item_id")) {
Bundle bd = getIntent().getExtras();
/*if ((!bd.getString("name").equals(null) || bd.getString("name").trim().length() > 0) && (!bd.getString("username").equals(null) || bd.getString("username").trim().length() > 0) && (!bd.getString("description").equals(null) || bd.getString("description").trim().length() > 0)) {
name = bd.getString("name");
username = bd.getString("username");
description = bd.getString("description");
}*/
item_id = bd.getInt("item_id");
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setTitle(R.string.app_name);
itemname = (TextView) findViewById(R.id.itemName);
itemdescription = (TextView) findViewById(R.id.itemdescription);
new getitem().execute();
/*recycler = (RecyclerView) findViewById(R.id.recycler);
recycler.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recycler.setLayoutManager(layoutManager);*/
}
/**
* Background Async Task to Get complete item details
*/
class getitem extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
if (pDialog != null) {
pDialog = null;
}
pDialog = new ProgressDialog(itemActivity.this);
pDialog.setMessage(getResources().getString(R.string.loadingitem));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Getting item details in background thread
*/
protected String doInBackground(String... params) {
// updating UI from Background Thread
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> myParameters = new ArrayList<NameValuePair>();
myParameters.add(new BasicNameValuePair("item_id", Integer.toString(item_id)));
// getting item details by making HTTP request
// Note that item details url will use GET request
jParser = new JSONParser();
JSONObject json = jParser.makeHttpRequest(AppConfig.URL_GET_item, "GET", myParameters);
// check your log for json response
Log.d("Single item Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received item details
JSONArray itemObj = json.getJSONArray(TAG_item); // JSON Array
// get first item object from JSON Array
JSONObject item = itemObj.getJSONObject(0);
// item with this pid found
// Edit Text
runOnUiThread(new Runnable() {
@Override
public void run() {
itemname.setText(item.getString(TAG_item_NAME));
itemdescription.setText(item.getString(TAG_item_description));
}
});
} else {
// item 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();
}
}
}
公共类itemActivity扩展了AppCompative活动{
私有静态最终字符串标记_SUCCESS=“SUCCESS”;
私有静态最终字符串标记\u item=“item”;
私有静态最终字符串标记\u项\u NAME=“NAME”;
私有静态最终字符串标记\项目\说明
runOnUiThread(new Runnable() {
@Override
public void run() {
itemname.setText(item.getString(TAG_item_NAME));
itemdescription.setText(item.getString(TAG_item_description));
}
});
itemname.setText(item.getString(TAG_item_NAME));
itemdescription.setText(item.getString(TAG_item_description));
public class itemActivity extends AppCompatActivity {
private static final String TAG_SUCCESS = "success";
private static final String TAG_item = "item";
private static final String TAG_item_NAME = "name";
private static final String TAG_item_description = "description";
Integer item_id;
String name;
String username;
String description;
TextView itemname;
TextView itemdescription;
ProgressDialog pDialog;
JSONParser jParser;
RecyclerView recycler;
ActionBar actionBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item);
Intent i = getIntent();
if (i.hasExtra("item_id")) {
Bundle bd = getIntent().getExtras();
/*if ((!bd.getString("name").equals(null) || bd.getString("name").trim().length() > 0) && (!bd.getString("username").equals(null) || bd.getString("username").trim().length() > 0) && (!bd.getString("description").equals(null) || bd.getString("description").trim().length() > 0)) {
name = bd.getString("name");
username = bd.getString("username");
description = bd.getString("description");
}*/
item_id = bd.getInt("item_id");
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setTitle(R.string.app_name);
itemname = (TextView) findViewById(R.id.itemName);
itemdescription = (TextView) findViewById(R.id.itemdescription);
new getitem().execute();
/*recycler = (RecyclerView) findViewById(R.id.recycler);
recycler.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recycler.setLayoutManager(layoutManager);*/
}
/**
* Background Async Task to Get complete item details
*/
class getitem extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
if (pDialog != null) {
pDialog = null;
}
pDialog = new ProgressDialog(itemActivity.this);
pDialog.setMessage(getResources().getString(R.string.loadingitem));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Getting item details in background thread
*/
protected String doInBackground(String... params) {
// updating UI from Background Thread
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> myParameters = new ArrayList<NameValuePair>();
myParameters.add(new BasicNameValuePair("item_id", Integer.toString(item_id)));
// getting item details by making HTTP request
// Note that item details url will use GET request
jParser = new JSONParser();
JSONObject json = jParser.makeHttpRequest(AppConfig.URL_GET_item, "GET", myParameters);
// check your log for json response
Log.d("Single item Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received item details
JSONArray itemObj = json.getJSONArray(TAG_item); // JSON Array
// get first item object from JSON Array
JSONObject item = itemObj.getJSONObject(0);
// item with this pid found
// Edit Text
runOnUiThread(new Runnable() {
@Override
public void run() {
itemname.setText(item.getString(TAG_item_NAME));
itemdescription.setText(item.getString(TAG_item_description));
}
});
} else {
// item 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();
}
}
}