2015-10-05 37 views
1
package com.example.editartist; 

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.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 

public class MainActivity extends Activity { 

EditText txtArtistType; 
EditText txtPhoneNo; 
EditText txtDescription; 
Button btnSave; 
Button btnDelete; 

String uid="1"; 

// Progress Dialog 
private ProgressDialog pDialog; 

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


private static final String url_profile_details = "http://10.0.2.2/android_main/get_profile_details.php"; 


private static final String url_update_profile = "http://10.0.2.2/android_main/update_profile.php"; 


private static final String url_delete_profile = "http://10.0.2.2/android_main/delete_profile.php"; 

// JSON Node names 
private static final String TAG_SUCCESS = "success"; 
private static final String TAG_PROFILE = "profile"; 
private static final String TAG_UID = "uid"; 
private static final String TAG_ARTIST_TYPE = "artist_type"; 
private static final String TAG_PHONE_NO = "phone_no"; 
private static final String TAG_DESCRIPTION = "description"; 

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

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

    new GetProfileDetails().execute(); 

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

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

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

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

} 

class GetProfileDetails extends AsyncTask<String, String, String> { 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(MainActivity.this); 
     pDialog.setMessage("Loading profile details. Please wait..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(true); 
     pDialog.show(); 
    } 

    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("uid", uid)); 

        JSONObject json = jsonParser.makeHttpRequest(
          url_profile_details, "GET", params); 

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

        // json success tag 
        success = json.getInt(TAG_SUCCESS); 
        if (success == 1) { 
         // successfully received profile details 
         JSONArray profileObj = json 
           .getJSONArray(TAG_PROFILE); // JSON Array 

         // get first profile object from JSON Array 
         JSONObject profile = profileObj.getJSONObject(0); 

         // profile with this uid found 
         // Edit Text 
         txtArtistType = (EditText) findViewById(R.id.inputArtistType); 
         txtPhoneNo = (EditText) findViewById(R.id.inputPhoneNo); 
         txtDescription = (EditText) findViewById(R.id.inputDescription); 

         // display profile data in EditText 
         txtArtistType.setText(profile.getString(TAG_ARTIST_TYPE)); 
         txtPhoneNo.setText(profile.getString(TAG_PHONE_NO)); 
         txtDescription.setText(profile.getString(TAG_DESCRIPTION)); 

        }else{ 
         // profile with uid not found 
        } 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 

     return null; 
    } 

    protected void onPostExecute(String file_url) { 
     // dismiss the dialog once got all details 
     pDialog.dismiss(); 
    } 
} 

/** 
* Background Async Task to Save profile Details 
* */ 
class SaveProfileDetails 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("Saving profile ..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(true); 
     pDialog.show(); 
    } 

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

     // getting updated data from EditTexts 
     String artistType = txtArtistType.getText().toString(); 
     String phoneNo = txtPhoneNo.getText().toString(); 
     String description = txtDescription.getText().toString(); 

     // Building Parameters 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     params.add(new BasicNameValuePair(TAG_UID, uid)); 
     params.add(new BasicNameValuePair(TAG_ARTIST_TYPE, artistType)); 
     params.add(new BasicNameValuePair(TAG_PHONE_NO, phoneNo)); 
     params.add(new BasicNameValuePair(TAG_DESCRIPTION, description)); 

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

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

      if (success == 1) { 
       Log.d("UPDATE","Successfully updated"); 
      } else { 
       // failed to update profile 
      } 
     } 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 profile updated 
     pDialog.dismiss(); 
    } 
} 

class DeleteProfile extends AsyncTask<String, String, String> { 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(MainActivity.this); 
     pDialog.setMessage("Deleting Profile..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(true); 
     pDialog.show(); 
    } 

    protected String doInBackground(String... args) { 

     int success; 
     try { 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 
      params.add(new BasicNameValuePair("uid", uid)); 

      JSONObject json = jsonParser.makeHttpRequest(
        url_delete_profile, "POST", params); 

      Log.d("Delete Profile", json.toString()); 

      success = json.getInt(TAG_SUCCESS); 
      if (success == 1) { 
       Log.d("DELETE","Successfully deleted"); 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 

    protected void onPostExecute(String file_url) { 
     pDialog.dismiss(); 

    } 

} 
} 



package com.example.editartist; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.util.List; 

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 android.util.Log; 

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; 

} 
} 

該應用程序將顯示加載配置文件對話框兩秒鐘,然後它簡單地關閉,如:EditArtist已停止工作。有開始Android應用程序未正確處理JSON

10-05 10:53:33.000: E/AndroidRuntime(1057): FATAL EXCEPTION: main 
10-05 10:53:33.000:E/AndroidRuntime(1057): android.os.NetworkOnMainThreadException 

我採取的uid =「1」爲方便起見,這裏只等與UID = 1的用戶可以編輯的日誌中的錯誤一長串。

+0

你不能在主線程中調用網絡請求 –

+0

@UdiI運行什麼我應該改變我的代碼嗎? – Strinzy

+0

從'GetProfileDetails'類的'doInBackground'中刪除'runOnUIThread()'部分並將代碼移動到'onPostExecute()' –

回答

1

刪除

runOnUiThread(new Runnable() { 
      public void run() {} 
}); 

從asynctask`s doInBackground()。

的AsyncTask本身是在其中操作。如果你寫runonUiThread()上doinBackground那麼網絡操作將在主線程只能執行,它會遇到你是facing.Hence例外你正在做網絡線程寫作一個asynctask是沒有意義的。

0

您不能運行在主UI線程網絡的請求......處理JSON正常,你已經在不同的線程使用new Thread或使用AsynTask