Java 使用JSON和MySql使用Android应用程序检索数据

Java 使用JSON和MySql使用Android应用程序检索数据,java,php,android,mysql,json,Java,Php,Android,Mysql,Json,我正在尝试使用WiFi检索数据,但应用程序正在崩溃。当我使用localHost Emulator时,它工作正常,但当我使用移动数据或WiFi时,它会崩溃。我可以使用WiFi将数据保存到本地主机上的MySql,但我无法接收数据。有时我会遇到android.os.NetworkonMainThreadException。我是一个非常新的程序员,只是借用了大部分代码,需要清楚地说明如何解决这个问题 /** * Background Async Task to Get complete User de

我正在尝试使用WiFi检索数据,但应用程序正在崩溃。当我使用localHost Emulator时,它工作正常,但当我使用移动数据或WiFi时,它会崩溃。我可以使用WiFi将数据保存到本地主机上的MySql,但我无法接收数据。有时我会遇到android.os.NetworkonMainThreadException
。我是一个非常新的程序员,只是借用了大部分代码,需要清楚地说明如何解决这个问题

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

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

    /**
     * Getting User 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("user_ID", "2"));

                    // getting User details by making HTTP request
                    // Note that User details url will use GET request
                    JSONObject json = jsonParser.makeHttpRequest(
                            LOGIN_URL, "GET", params);

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

                    // json success tag
                    success = json.getInt(TAG_SUCCESS);
                    if (success == 1) {
                        // successfully received User details
                        JSONArray UserObj = json
                                .getJSONArray(TAG_User); // JSON Array

                        // get first User object from JSON Array
                        JSONObject User = UserObj.getJSONObject(0);

                        // User with this pid found
                        // Edit Text
                        txtlname = (EditText) findViewById(R.id.editText1);
                        txtfname = (EditText) findViewById(R.id.editText2);

                        // display User data in EditText
                        txtfname.setText(User.getString(TAG_FNAME));
                        txtlname.setText(User.getString(TAG_LNAME));

                    }else{
                        // User 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();
    }
}
/**
*获取完整用户详细信息的后台异步任务
* */
类GetUserDetails扩展了AsyncTask{
/**
*在启动后台线程显示进度对话框之前
* */
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=新建进度对话框(MainActivity.this);
pDialog.setMessage(“正在加载详细信息,请稍候…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
}
/**
*在后台线程中获取用户详细信息
* */
受保护的字符串doInBackground(字符串…参数){
//从后台线程更新UI
runOnUiThread(新的Runnable(){
公开募捐{
//检查成功标签
成功;
试一试{
//建筑参数
List params=new ArrayList();
参数添加(新的BasicNameValuePair(“用户ID”,“2”));
//通过发出HTTP请求获取用户详细信息
//请注意,用户详细信息url将使用GET请求
JSONObject json=jsonParser.makeHttpRequest(
登录(URL,“获取”,参数);
//检查日志中的json响应
Log.d(“单用户详细信息”,json.toString());
//json成功标记
success=json.getInt(TAG_success);
如果(成功==1){
//已成功接收用户详细信息
JSONArray UserObj=json
.getJSONArray(TAG_User);//JSON数组
//从JSON数组中获取第一个用户对象
JSONObject User=UserObj.getJSONObject(0);
//找到具有此pid的用户
//编辑文本
txtlname=(EditText)findViewById(R.id.editText1);
txtfname=(EditText)findViewById(R.id.editText2);
//在EditText中显示用户数据
txtfname.setText(User.getString(TAG_FNAME));
txtlname.setText(User.getString(TAG_LNAME));
}否则{
//找不到pid为的用户
}
}捕获(JSONException e){
e、 printStackTrace();
}
}
});
返回null;
}
/**
*完成后台任务后,关闭“进度”对话框
* **/
受保护的void onPostExecute(字符串文件\u url){
//获得所有详细信息后关闭对话框
pDialog.disclose();
}
}

您不应该在doInBackground中执行UI相关代码,您应该将UI相关代码移动到AsyncTask的onPostExecute或onProgressUpdate方法中

这个答案可能会帮助您:


实际上,您不应该在UI线程中连接到internet。 您通过
JSONObject json=jsonParser.makeHttpRequest连接到internet(
登录(URL,“获取”,参数)
runOnUiThread中(新的可运行…

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

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

/**
 * Getting User 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> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("user_ID", "2"));

        // getting User details by making HTTP request
        // Note that User details url will use GET request
        JSONObject json = jsonParser.makeHttpRequest(
                LOGIN_URL, "GET", params);

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

        // json success tag
        success = json.getInt(TAG_SUCCESS);
        if (success == 1) {
            // successfully received User details
            JSONArray UserObj = json
                    .getJSONArray(TAG_User); // JSON Array

            // get first User object from JSON Array
            final JSONObject User = UserObj.getJSONObject(0);
            runOnUiThread(new Runnable() {
                public void run() {
                    // User with this pid found
                    // Edit Text
                    txtlname = (EditText) findViewById(R.id.editText1);
                    txtfname = (EditText) findViewById(R.id.editText2);

                    // display User data in EditText
                    txtfname.setText(User.getString(TAG_FNAME));
                    txtlname.setText(User.getString(TAG_LNAME));
                }
            });

        }else{
            // User 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();
}
}
/**
*获取完整用户详细信息的后台异步任务
* */
类GetUserDetails扩展了AsyncTask{
/**
*在启动后台线程显示进度对话框之前
* */
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=新建进度对话框(MainActivity.this);
pDialog.setMessage(“正在加载详细信息,请稍候…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
}
/**
*在后台线程中获取用户详细信息
* */
受保护的字符串doInBackground(字符串…参数){
//从后台线程更新UI
//检查成功标签
成功;
试一试{
//建筑参数
List params=new ArrayList();
参数添加(新的BasicNameValuePair(“用户ID”,“2”));
//通过发出HTTP请求获取用户详细信息
//请注意,用户详细信息url将使用GET请求
JSONObject json=jsonParser.makeHttpRequest(
登录(URL,“获取”,参数);
//检查日志中的json响应
Log.d(“单用户详细信息”,json.toString());
//json成功标记
success=json.getInt(TAG_success);
如果(成功==1){
//已成功接收用户详细信息
JSONArray UserObj=json
.getJSONArray(TAG_User);//JSON数组
//从JSON数组中获取第一个用户对象
最终JSONObject用户=UserObj.getJSONObject(0);
runOnUiThread(新的Runnable(){
公开募捐{
//找到具有此pid的用户
//编辑文本
txtlname=(EditText)findViewById(R.id.editText1);
txtfname=(EditText)findViewById(R.id.editText2);
//在EditText中显示用户数据
txtfname.setText(User.getString(TAG_FNAME));
txtlname.setText(User.getString(TAG_LNAME));
}
});
}否则{
//找不到pid为的用户
}
}捕获(JSONException e){
e、 printStackTrace();
}
返回null;
}
/**
*完成后台任务后,关闭“进度”对话框
* **/
受保护的void onPostExecute(字符串文件\u url){
//获得所有详细信息后关闭对话框
pD