试图遵循基本的如何与And​​roid的PHP连接,MySQL的教程:应用程序崩溃 - 无法导入android.os.StrictMode [英] Attempting to follow basic How to connect Android with PHP, MySQL tutorial: application crashes - cannot import android.os.StrictMode

查看:373
本文介绍了试图遵循基本的如何与And​​roid的PHP连接,MySQL的教程:应用程序崩溃 - 无法导入android.os.StrictMode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确定 - 所以我用下面的教程:

如何使用PHP和MySQL的Andr​​oid连接

由于仅被设计用于在API级别8或更早版本运行应用程序几乎但是大家谁试图教程(从评论来看)是有强制关闭的问题。

有用户开发了这种涉及增加code以下行EditProductActivity.java文件修复

//这部分只以确定在哪里把工作code

 公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.edit_product);

// NB *插入下面的行EditProductActivity.java进口部分
//进口android.os.StrictMode;

//现在code看过那部避免NetworkOnMainThreadException误差

  StrictMode.ThreadPolicy政策=新StrictMode.ThreadPolicy.Builder()
.permitAll()建立()。
StrictMode.setThreadPolicy(政策);

但是我得到的消息,我logcat中陈述StrictMode不能得到解决,StrictMode不能被解析为一个类型。我做了一些研究,这个和StrictMode包含在API 8级及以上。考虑到这我已经提出了在AndroidManifest.xml我的API级别:

 <采用-SDK安卓的minSdkVersion =9
          机器人:targetSdkVersion =9/>

然后清理我的项目 - 但我仍然得到StrictMode不能被解析为一个类型错误

logcat的:

  03-17 14:06:57.924:D / AndroidRuntime(18472):关闭VM
    03-17 14:06:57.924:W / dalvikvm(18472):主题ID = 1:螺纹未捕获的异常(组= 0x41604930)退出
    03-17 14:06:57.924:E / AndroidRuntime(18472):致命异常:主要
    03-17 14:06:57.924:E / AndroidRuntime(18472):java.lang.Error:未解决的编译问题:
    03-17 14:06:57.924:E / AndroidRuntime(18472):进口android.os.StrictMode不能得到解决
   03-17 14:06:57.924:E / AndroidRuntime(18472):StrictMode不能被解析为一个类型
    03-17 14:06:57.924:E / AndroidRuntime(18472):StrictMode不能被解析为一个类型
    03-17 14:06:57.924:E / AndroidRuntime(18472):StrictMode不能得到解决
    。03-17 14:06:57.924:E / AndroidRuntime(18472):在com.example.androidhive.NewProductActivity<&初始化GT;(NewProductActivity.java:10)
    03-17 14:06:57.924:E / AndroidRuntime(18472):在java.lang.Class.newInstanceImpl(本机方法)
    03-17 14:06:57.924:E / AndroidRuntime(18472):在java.lang.Class.newInstance(Class.java:1319)
    03-17 14:06:57.924:E / AndroidRuntime(18472):在android.app.Instrumentation.newActivity(Instrumentation.java:1054)
    03-17 14:06:57.924:E / AndroidRuntime(18472):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
    03-17 14:06:57.924:E / AndroidRuntime(18472):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
    03-17 14:06:57.924:E / AndroidRuntime(18472):在android.app.ActivityThread.access $ 600(ActivityThread.java:141)
    03-17 14:06:57.924:E / AndroidRuntime(18472):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1234)
    03-17 14:06:57.924:E / AndroidRuntime(18472):在android.os.Handler.dispatchMessage(Handler.java:99)
    03-17 14:06:57.924:E / AndroidRuntime(18472):在android.os.Looper.loop(Looper.java:137)
    03-17 14:06:57.924:E / AndroidRuntime(18472):在android.app.ActivityThread.main(ActivityThread.java:5039)
    03-17 14:06:57.924:E / AndroidRuntime(18472):在java.lang.reflect.Method.invokeNative(本机方法)
    03-17 14:06:57.924:E / AndroidRuntime(18472):在java.lang.reflect.Method.invoke(Method.java:511)
    03-17 14:06:57.924:E / AndroidRuntime(18472):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:793)
    03-17 14:06:57.924:E / AndroidRuntime(18472):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    03-17 14:06:57.924:E / AndroidRuntime(18472):在dalvik.system.NativeStart.main(本机方法)

JAVA:

 进口的java.util.ArrayList;
进口的java.util.List;进口org.apache.http.NameValuePair;
进口org.apache.http.message.BasicNameValuePair;
进口org.json.JSONArray;
进口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;
进口android.os.StrictMode; 公共类EditProductActivity延伸活动{的EditText txtName的;
的EditText txtPrice;
的EditText txtDesc;
的EditText txtCreatedAt;
按钮btnSave;
按钮btnDelete;串PID;//进度对话框
私人ProgressDialog pDialog;// JSON解析器类
JSONParser jsonParser =新JSONParser();//单品链接
私有静态最后弦乐url_product_detials =htt​​p://linkingmanager.zxq.net/get_product_details.php;// URL来更新产品
私有静态最后弦乐url_update_product =htt​​p://linkingmanager.zxq.net/update_product.php;// URL删除产品
私有静态最后弦乐url_delete_product =htt​​p://linkingmanager.zxq.net/delete_product.php;// JSON节点名称
私有静态最后弦乐TAG_SUCCESS =成功;
私有静态最后弦乐TAG_PRODUCT =产品;
私有静态最后弦乐TAG_PID =PID;
私有静态最后弦乐TAG_NAME =名;
私有静态最后弦乐TAG_PRICE =价格;
私有静态最后弦乐TAG_DESCRIPTION =说明;@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.edit_product);    StrictMode.ThreadPolicy政策=新StrictMode.ThreadPolicy.Builder()
    .permitAll()建立()。
    StrictMode.setThreadPolicy(政策);    //保存按钮
    btnSave =(按钮)findViewById(R.id.btnSave);
    btnDelete =(按钮)findViewById(R.id.btnDelete);    //获取来自意图产品的详细信息
    意向I = getIntent();    //从意图获取产品ID(PID)
    PID = i.getStringExtra(TAG_PID);    //获取在后台线程完整的产品细节
    新GetProductDetails()执行();    //保存按钮单击事件
    btnSave.setOnClickListener(新View.OnClickListener(){        @覆盖
        公共无效的onClick(查看为arg0){
            //启动后台任务来更新产品
            新SaveProductDetails()执行();
        }
    });    //删除按钮单击事件
    btnDelete.setOnClickListener(新View.OnClickListener(){        @覆盖
        公共无效的onClick(查看为arg0){
            //在后台线程删除产品
            新DeleteProduct()执行();
        }
    });}/ **
 *背景异步任务以获得完整的产品细节
 * * /
类GetProductDetails扩展的AsyncTask<字符串,字符串,字符串> {    / **
     *启动后台线程显示进度对话框之前
     * * /
    @覆盖
    在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(
                            url_product_detials,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的=(的EditText)findViewById(R.id.inputName);
                        txtPrice =(EditText上)findViewById(R.id.inputPrice);
                        txtDesc =(EditText上)findViewById(R.id.inputDesc);                        //在显示的EditText产品数据
                          txtName.setText(product.getString(TAG_NAME));
                        txtPrice.setText(product.getString(TAG_PRICE));
                        txtDesc.setText(product.getString(TAG_DESCRIPTION));                    }其他{
                        //产品具有pid未找到
                    }
                }赶上(JSONException E){
                    e.printStackTrace();
                }
            }
        });        返回null;
    }
    / **
     *在完成后台任务之后辞退进度对话框
     * ** /
    保护无效onPostExecute(字符串FILE_URL){
        //关闭该对话框一旦得了所有细节
        pDialog.dismiss();
    }
}/ **
 *背景异步任务保存产品详细信息
 * * /
类SaveProductDetails扩展的AsyncTask<字符串,字符串,字符串> {    / **
     *启动后台线程显示进度对话框之前
     * * /
    @覆盖
    在preExecute保护无效(){
        super.on preExecute();
        pDialog =新ProgressDialog(EditProductActivity.this);
        pDialog.setMessage(节能产品......);
        pDialog.setIndeterminate(假);
        pDialog.setCancelable(真);
        pDialog.show();
    }    / **
     *节能产品
     * * /
    保护字符串doInBackground(字符串参数... args){        //获得从EditTexts更新数据
        字符串名称= txtName.getText()的toString()。
        串价格= txtPrice.getText()的toString()。
        。字符串描述= txtDesc.getText()的toString();        //大厦参数
        清单<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT;();
        params.add(新BasicNameValuePair(TAG_PID,PID));
        params.add(新BasicNameValuePair(TAG_NAME,名));
        params.add(新BasicNameValuePair(TAG_PRICE,价格));
        params.add(新BasicNameValuePair(TAG_DESCRIPTION,描述));        //通过发送HTTP请求修改的数据
        //注意,更新的产品网址接受POST方法
        JSONObject的JSON = jsonParser.makeHtt prequest(url_update_product,
                POST,则params);        //检查JSON的成功标签
        尝试{
            INT成功= json.getInt(TAG_SUCCESS);            如果(成功== 1){
                //成功更新
                意向I = getIntent();
                //发送结果code 100,通知有关产品更新
                的setResult(100,i)的;
                完();
            }其他{
                //无法更新产品
            }
        }赶上(JSONException E){
            e.printStackTrace();
        }        返回null;
    }
    / **
     *在完成后台任务之后辞退进度对话框
     * ** /
    保护无效onPostExecute(字符串FILE_URL){
        //关闭该对话框一旦产品uupdated
        pDialog.dismiss();
    }
}/ ******************* ****************
 *背景异步任务删​​除产品
 * * /
类DeleteProduct扩展的AsyncTask<字符串,字符串,字符串> {    / **
     *启动后台线程显示进度对话框之前
     * * /
    @覆盖
    在preExecute保护无效(){
        super.on preExecute();
        pDialog =新ProgressDialog(EditProductActivity.this);
        pDialog.setMessage(删除产品......);
        pDialog.setIndeterminate(假);
        pDialog.setCancelable(真);
        pDialog.show();
    }    / **
     *删除产品
     * * /
    保护字符串doInBackground(字符串参数... args){        //检查成功标记
        诠释成功;
        尝试{
            //大厦参数
            清单<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT; ();
            params.add(新BasicNameValuePair(PID,PID));            //通过HTTP请求获得产品的详细信息
            JSONObject的JSON = jsonParser.makeHtt prequest(
                    url_delete_product,POST,则params);            //检查你的日志,JSON响应
            Log.d(删除产品,json.toString());            // JSON的成功标签
            成功= json.getInt(TAG_SUCCESS);
            如果(成功== 1){
                //产品成功删除
                //通过发送code 100通知previous活动
                意向I = getIntent();
                //发送结果code 100,通知有关产品缺失
                的setResult(100,i)的;
                完();
            }
        }赶上(JSONException E){
            e.printStackTrace();
        }        返回null;
    }    / **
     *在完成后台任务之后辞退进度对话框
     * ** /
    保护无效onPostExecute(字符串FILE_URL){
        //关闭该对话框一旦产品被删除
        pDialog.dismiss();    }}
}


解决方案

  StrictMode.ThreadPolicy政策=新StrictMode.ThreadPolicy.Builder()
.permitAll()建立()。
StrictMode.setThreadPolicy(政策);

由于您使用的的AsyncTask 就没有必要设置 ThreadPolicy 。而且不要忘记,StrictMode是开始提供2.3版本。

更新:

您的应用程序不被指定很好。看看这个

 保护字符串doInBackground(字符串... PARAMS){        runOnUiThread(新的Runnable(){
           ...
           txtName的=(的EditText)findViewById(R.id.inputName);
           txtPrice =(EditText上)findViewById(R.id.inputPrice);
           txtDesc =(EditText上)findViewById(R.id.inputDesc);           //在显示的EditText产品数据
           txtName.setText(product.getString(TAG_NAME));
           txtPrice.setText(product.getString(TAG_PRICE));
           txtDesc.setText(product.getString(TAG_DESCRIPTION));
           ...
        }
}

为什么你这样做? doInBackground()直接设计用于执行后台操作也已经在后台线程上运行,你不应该从中进行UI更新。你不应该混合。

如果您想更新UI,的AsyncTask 提供了实现的方法得当:


  • 在preExecute()

  • onProgressUpdate()

  • onPostExecute()

因此​​,如果你想与有关后台任务调用 publishProgress进度的一些信息来更新你的UI(lt;数据>)方法自动调用 onProgressUpdate()方法并从其更新UI。

在你的情况,你正在执行 UI 元素doInBackground()方法的初始化,你不应该。

我建议你做这样的:


  1. 在初始化的onCreate()方法您的小工具。

  2. 当你想从获取的数据对其进行更新
    doInBackground()方法,调用 publishProgress()的调用
    onProgressUpdate()方法在这里进行更新

下面是例子:

  @覆盖
保护无效onProgressUpdate(字符串... PARAMS){
   txtName.setText(小于值>);
   ...
}

根据提到的事情上面,我猜你需要阅读的AsyncTask教程:

Ok - so I'm using the following tutorial: "How to connect Android with PHP, MySQL"

However almost everyone who attempts the tutorial (judging from the comments) is having force close issues due to the application only being designed to run on API level 8 or earlier.

Several users have developed a fix for this involving adding the following lines of code in EditProductActivity.java file

// this part only to identify where to put the working code

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_product);

// NB * insert the line below in import section of EditProductActivity.java // import android.os.StrictMode;

// Now the code thaat avoid the NetworkOnMainThreadException error

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);

However I'm getting messages in my logcat stating StrictMode cannot be resolved and StrictMode cannot be resolved to a type. I've done a bit of research into this and StrictMode is included in API level 8 and above. Taking that into consideration I've raised my API levels in AndroidManifest.xml to:

 <uses-sdk android:minSdkVersion="9"
          android:targetSdkVersion="9"/>

Then cleaned my project - however I still get StrictMode cannot be resolved to a type errors.

LOGCAT:

    03-17 14:06:57.924: D/AndroidRuntime(18472): Shutting down VM
    03-17 14:06:57.924: W/dalvikvm(18472): threadid=1: thread exiting with uncaught exception (group=0x41604930)
    03-17 14:06:57.924: E/AndroidRuntime(18472): FATAL EXCEPTION: main
    03-17 14:06:57.924: E/AndroidRuntime(18472): java.lang.Error: Unresolved compilation problems: 
    03-17 14:06:57.924: E/AndroidRuntime(18472):    The import android.os.StrictMode cannot be resolved
   03-17 14:06:57.924: E/AndroidRuntime(18472):     StrictMode cannot be resolved to a type
    03-17 14:06:57.924: E/AndroidRuntime(18472):    StrictMode cannot be resolved to a type
    03-17 14:06:57.924: E/AndroidRuntime(18472):    StrictMode cannot be resolved
    03-17 14:06:57.924: E/AndroidRuntime(18472):    at com.example.androidhive.NewProductActivity.<init>(NewProductActivity.java:10)
    03-17 14:06:57.924: E/AndroidRuntime(18472):    at java.lang.Class.newInstanceImpl(Native Method)
    03-17 14:06:57.924: E/AndroidRuntime(18472):    at java.lang.Class.newInstance(Class.java:1319)
    03-17 14:06:57.924: E/AndroidRuntime(18472):    at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
    03-17 14:06:57.924: E/AndroidRuntime(18472):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
    03-17 14:06:57.924: E/AndroidRuntime(18472):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
    03-17 14:06:57.924: E/AndroidRuntime(18472):    at android.app.ActivityThread.access$600(ActivityThread.java:141)
    03-17 14:06:57.924: E/AndroidRuntime(18472):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 
    03-17 14:06:57.924: E/AndroidRuntime(18472):    at android.os.Handler.dispatchMessage(Handler.java:99)
    03-17 14:06:57.924: E/AndroidRuntime(18472):    at android.os.Looper.loop(Looper.java:137)
    03-17 14:06:57.924: E/AndroidRuntime(18472):    at android.app.ActivityThread.main(ActivityThread.java:5039)
    03-17 14:06:57.924: E/AndroidRuntime(18472):    at java.lang.reflect.Method.invokeNative(Native Method)
    03-17 14:06:57.924: E/AndroidRuntime(18472):    at java.lang.reflect.Method.invoke(Method.java:511)
    03-17 14:06:57.924: E/AndroidRuntime(18472):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    03-17 14:06:57.924: E/AndroidRuntime(18472):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    03-17 14:06:57.924: E/AndroidRuntime(18472):    at dalvik.system.NativeStart.main(Native Method)

JAVA:

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

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
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;
import android.os.StrictMode;

 public class EditProductActivity extends Activity {

EditText txtName;
EditText txtPrice;
EditText txtDesc;
EditText txtCreatedAt;
Button btnSave;
Button btnDelete;

String pid;

// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();

// single product url
private static final String url_product_detials =  "http://linkingmanager.zxq.net/get_product_details.php";

// url to update product
private static final String url_update_product = "http://linkingmanager.zxq.net/update_product.php";

// url to delete product
private static final String url_delete_product = "http://linkingmanager.zxq.net/delete_product.php";

// 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";

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

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
    .permitAll().build();
    StrictMode.setThreadPolicy(policy);

    // save button
    btnSave = (Button) findViewById(R.id.btnSave);
    btnDelete = (Button) findViewById(R.id.btnDelete);

    // 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
    new GetProductDetails().execute();

    // save button click event
    btnSave.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // starting background task to update product
            new SaveProductDetails().execute();
        }
    });

    // Delete button click event
    btnDelete.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // deleting product in background thread
            new DeleteProduct().execute();
        }
    });

}

/**
 * Background Async Task to Get complete product details
 * */
class GetProductDetails extends AsyncTask<String, String, String> {

    /**
     * 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(
                            url_product_detials, "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 = (EditText) findViewById(R.id.inputName);
                        txtPrice = (EditText) findViewById(R.id.inputPrice);
                        txtDesc = (EditText)  findViewById(R.id.inputDesc);

                        // display product data in EditText
                          txtName.setText(product.getString(TAG_NAME));
                        txtPrice.setText(product.getString(TAG_PRICE));
                        txtDesc.setText(product.getString(TAG_DESCRIPTION));

                    }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();
    }
}

/**
 * Background Async Task to  Save product Details
 * */
class SaveProductDetails extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(EditProductActivity.this);
        pDialog.setMessage("Saving product ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Saving product
     * */
    protected String doInBackground(String... args) {

        // getting updated data from EditTexts
        String name = txtName.getText().toString();
        String price = txtPrice.getText().toString();
        String description = txtDesc.getText().toString();

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(TAG_PID, pid));
        params.add(new BasicNameValuePair(TAG_NAME, name));
        params.add(new BasicNameValuePair(TAG_PRICE, price));
        params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));

        // sending modified data through http request
        // Notice that update product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_update_product,
                "POST", params);

        // check json success tag
        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // successfully updated
                Intent i = getIntent();
                // send result code 100 to notify about product update
                setResult(100, i);
                finish();
            } else {
                // failed to update 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 product uupdated
        pDialog.dismiss();
    }
}

/*****************************************************************
 * Background Async Task to Delete Product
 * */
class DeleteProduct extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(EditProductActivity.this);
        pDialog.setMessage("Deleting Product...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Deleting product
     * */
    protected String doInBackground(String... args) {

        // 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
            JSONObject json = jsonParser.makeHttpRequest(
                    url_delete_product, "POST", params);

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

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                // product successfully deleted
                // notify previous activity by sending code 100
                Intent i = getIntent();
                // send result code 100 to notify about product deletion
                setResult(100, i);
                finish();
            }
        } 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 product deleted
        pDialog.dismiss();

    }

}
}

解决方案

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);

Since you are using AsyncTask there is no need to setting ThreadPolicy.And don't forget that StrictMode is available starting with 2.3 version.

Update:

Your app is not designated very well. Look at this

protected String doInBackground(String... params) {

        runOnUiThread(new Runnable() { 
           ...
           txtName = (EditText) findViewById(R.id.inputName);
           txtPrice = (EditText) findViewById(R.id.inputPrice);
           txtDesc = (EditText)  findViewById(R.id.inputDesc);

           // display product data in EditText
           txtName.setText(product.getString(TAG_NAME));
           txtPrice.setText(product.getString(TAG_PRICE));
           txtDesc.setText(product.getString(TAG_DESCRIPTION));
           ...
        }
}

Why you're doing that? doInBackground() is directly designed for performing background operations also already runs on background Thread and you shouldn't perform UI update from it. You shouldn't mix it.

If you want to update UI, AsyncTask offers proper methods for achieve it:

  • onPreExecute()
  • onProgressUpdate()
  • onPostExecute()

Hence if you want to update your UI with some information about progress of background task call publishProgress(<data>) method that automatic invokes onProgressUpdate() method and from its update UI.

In your case you are performing initialisation of UI elements in doInBackground() method that you shouldn't.

I suggest you to make this:

  1. Initialise your widgets in onCreate() method.
  2. When you want to update them with data retrieved from doInBackground() method, call publishProgress() that invoke onProgressUpdate() method and here perform updating

Here is example:

@Override
protected void onProgressUpdate(String... params) {
   txtName.setText(<value>);
   ...
}

Based on things mentioned above i guess that you need to read AsyncTask tutorial:

这篇关于试图遵循基本的如何与And​​roid的PHP连接,MySQL的教程:应用程序崩溃 - 无法导入android.os.StrictMode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆