2014-04-28 29 views
0

我在Android中使用JSON非常新。我已經獲得了基本URL爲 測試服務器的webAPI。在開發過程中,我嘗試使用Web服務器數據庫中的電子郵件和密碼進行登錄。在android中使用webAPI進行登錄會導致FATAL EXCEPTION:AsyncTask#1錯誤

用戶令牌的計算公式如下: 令牌= MD5(email + userId);我不知道這是什麼。我試圖做的是;

JSONParser.java

public class JSONParser { 

static InputStream is = null; 

static JSONObject jObj = null; 

static String json = ""; 

// constructor 
public JSONParser() { 

} 

public JSONObject getJSONFromUrl(String url) { 
    System.out.println("url:: "+url); 
    // Making HTTP request 
    try { 
     // defaultHttpClient 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url); 

     HttpResponse httpResponse = httpClient.execute(httpPost); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     is = httpEntity.getContent(); 
    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 

    } catch (ClientProtocolException e) { 

     e.printStackTrace(); 

    } catch (IOException e) { 

     e.printStackTrace(); 

    } 

    try { 

     // Create a BufferedReader to parse through the inputStream. 
     BufferedReader reader = new BufferedReader(new InputStreamReader(

     is, "iso-8859-1"), 8); 

     // Declare a string builder to help with the parsing. 
     StringBuilder sb = new StringBuilder(); 
     // Declare a string to store the JSON object data in string form. 
     String line = null; 
     // Build the string until null. 
     while ((line = reader.readLine()) != null) { 

      sb.append(line + "\n"); 
     } 
     // Close the input stream. 
     is.close(); 
     // Convert the string builder data to an actual string. 
     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; 

} 

// function get json from url 
// by making HTTP POST or GET method 
public JSONObject makeHttpRequest(String url, String method, 
     List<NameValuePair> params) { 

    //Making HTTP request 
    try{ 
     //check for the request method 
     if(method == "POST"){ 
      //request method to post 
      //default HTTPClient 
      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 to 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; 
} 

} 

Login.java

public class Login extends Activity { 

EditText inputEmail; 
EditText inputPassword; 
Button loginBtn; 

// Progress Dialog 
ProgressDialog pDialog; 

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

// PHP Login Script location 
private static final String LOGIN_URL = "http://www.sthng.com/ws/?c=profile&func=login"; 

// JSON element ids from repsonse of php script: 
private static final String TAG_SUCCESS = "Success"; 
private static final String TAG_MESSAGE = "Message"; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.login); 

    inputEmail = (EditText) findViewById(R.id.email); 
    inputPassword = (EditText) findViewById(R.id.password); 

    loginBtn = (Button) findViewById(R.id.btnLogin); 
    loginBtn.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      new AttemptLogin().execute(); 

     } 

    }); 
} 

// AsyncTask is a seperate thread than the thread that runs the GUI 
// Any type of networking should be done with asynctask. 
class AttemptLogin extends AsyncTask<String, Void, String> { 

    String email = inputEmail.getText().toString(); 
    String password = inputPassword.getText().toString(); 

    /** 
    * Before starting background thread Show Progress Dialog 
    * */ 
    boolean failure = false; 

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

    @Override 
    protected String doInBackground(String... args) { 

     int success; 

     try { 
      // Building Parameters 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 

      params.add(new BasicNameValuePair("email", email)); 
      params.add(new BasicNameValuePair("password", password)); 
      //params.add(new BasicNameValuePair("RegistrationID",)); 
      // Log.d("HERE", email); 
      // Log.d("HERE2", password); 

      Log.d("request!", "starting"); 
      // getting users details by making HTTP request 
      JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "GET", params); 

      Log.d("DEBUG!", "CHECKPOINT"); 

      // json = json.toString(); 
      // check your log for json response 
      Log.d("Login attempt", json.toString()); 

      // json success tag 
      success = json.getInt(TAG_SUCCESS); 
      if (success == 1) { 
       Log.d("Login Successful!", json.toString()); 

      /* Intent i = new Intent(Login.this, Home.class); 
       finish(); 
       startActivity(i);*/ 

       return json.getString(TAG_MESSAGE); 
      } else { 
       Log.d("Login Failure!", json.getString(TAG_MESSAGE)); 
       return json.getString(TAG_MESSAGE); 

      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     return null; 

    } 

    /** 
    * After completing background task Dismiss the progress dialog 
    * **/ 
    protected void onPostExecute(String file_url) { 

     pDialog.dismiss(); 
     if (file_url != null) { 
      Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show(); 
     } 

    } 

} 

}

但我得到錯誤等;

04-29 19:03:22.691: D/request!(15060): starting 
04-29 19:03:22.736: D/dalvikvm(15060): GC_CONCURRENT freed 222K, 14% free 9575K/11015K, paused 13ms+22ms, total 82ms 
04-29 19:03:22.781: W/dalvikvm(15060): threadid=11: thread exiting with uncaught exception (group=0x41d082a0) 
04-29 19:03:22.791: E/AndroidRuntime(15060): FATAL EXCEPTION: AsyncTask #1 
04-29 19:03:22.791: E/AndroidRuntime(15060): java.lang.RuntimeException: An error occured while executing doInBackground() 
04-29 19:03:22.791: E/AndroidRuntime(15060): at android.os.AsyncTask$3.done(AsyncTask.java:299) 
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) 
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask.setException(FutureTask.java:124) 
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) 
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask.run(FutureTask.java:137) 
04-29 19:03:22.791: E/AndroidRuntime(15060): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.lang.Thread.run(Thread.java:856) 
04-29 19:03:22.791: E/AndroidRuntime(15060): Caused by: java.lang.IllegalArgumentException: Host name may not be null 
04-29 19:03:22.791: E/AndroidRuntime(15060): at org.apache.http.HttpHost.<init>(HttpHost.java:83) 
04-29 19:03:22.791: E/AndroidRuntime(15060): at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:519) 
04-29 19:03:22.791: E/AndroidRuntime(15060): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509) 
04-29 19:03:22.791: E/AndroidRuntime(15060): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 
04-29 19:03:22.791: E/AndroidRuntime(15060): at com.example.sthng.JSONParser.makeHttpRequest(JSONParser.java:125) 
04-29 19:03:22.791: E/AndroidRuntime(15060): at com.example.sthng.Login$AttemptLogin.doInBackground(Login.java:106) 
04-29 19:03:22.791: E/AndroidRuntime(15060): at com.example.sthng.Login$AttemptLogin.doInBackground(Login.java:1) 
04-29 19:03:22.791: E/AndroidRuntime(15060): at android.os.AsyncTask$2.call(AsyncTask.java:287) 
04-29 19:03:22.791: E/AndroidRuntime(15060): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 
04-29 19:03:22.791: E/AndroidRuntime(15060): ... 5 more 
04-29 19:03:32.686: I/Choreographer(15060): Skipped 589 frames! The application may be doing too much work on its main thread. 
04-29 19:03:33.256: E/WindowManager(15060): Activity com.example.sthng.Login has leaked window [email protected] that was originally added here 
04-29 19:03:33.256: E/WindowManager(15060): android.view.WindowLeaked: Activity com.example.clipme.Login has leaked window [email protected] that was originally added here 
04-29 19:03:33.256: E/WindowManager(15060):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:403) 
04-29 19:03:33.256: E/WindowManager(15060):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:311) 
04-29 19:03:33.256: E/WindowManager(15060):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224) 
04-29 19:03:33.256: E/WindowManager(15060):  at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149) 
04-29 19:03:33.256: E/WindowManager(15060):  at android.view.Window$LocalWindowManager.addView(Window.java:554) 
04-29 19:03:33.256: E/WindowManager(15060):  at android.app.Dialog.show(Dialog.java:277) 
04-29 19:03:33.256: E/WindowManager(15060):  at com.example.sthng.Login$AttemptLogin.onPreExecute(Login.java:87) 
04-29 19:03:33.256: E/WindowManager(15060):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586) 
04-29 19:03:33.256: E/WindowManager(15060):  at android.os.AsyncTask.execute(AsyncTask.java:534) 
04-29 19:03:33.256: E/WindowManager(15060):  at com.example.sthng.Login$1.onClick(Login.java:61) 
04-29 19:03:33.256: E/WindowManager(15060):  at android.view.View.performClick(View.java:4232) 
04-29 19:03:33.256: E/WindowManager(15060):  at android.view.View$PerformClick.run(View.java:17298) 
04-29 19:03:33.256: E/WindowManager(15060):  at android.os.Handler.handleCallback(Handler.java:615) 
04-29 19:03:33.256: E/WindowManager(15060):  at android.os.Handler.dispatchMessage(Handler.java:92) 
04-29 19:03:33.256: E/WindowManager(15060):  at android.os.Looper.loop(Looper.java:137) 
04-29 19:03:33.256: E/WindowManager(15060):  at android.app.ActivityThread.main(ActivityThread.java:4921) 
04-29 19:03:33.256: E/WindowManager(15060):  at java.lang.reflect.Method.invokeNative(Native Method) 
04-29 19:03:33.256: E/WindowManager(15060):  at java.lang.reflect.Method.invoke(Method.java:511) 
04-29 19:03:33.256: E/WindowManager(15060):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027) 
04-29 19:03:33.256: E/WindowManager(15060):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794) 
04-29 19:03:33.256: E/WindowManager(15060):  at dalvik.system.NativeStart.main(Native Method) 

我相信我做了一些愚蠢的錯誤,但請不要把它壞的方式。我希望我能得到一些提示和解決方案。

+0

什麼是行號106? – duggu

+0

請有人指導我:S? – bShah

回答

0

您上doInBackground()訪問UI元素doInBackground()

  Intent i = new Intent(Login.this, Home.class); 
      finish(); 
      startActivity(i); 

上述方法。你必須調用這個方法onPostExecute

您正在發送電子郵件和密碼兩次。

你讓網址與https:sthng.com/ws?function=login&email=" + email+ "&password=" + password

JSONObject json = jsonParser.makeHttpRequest(
        "https:sthng.com/ws?function=login&email=" + email 
          + "&password=" + password, "POST", params); 

現在你讓下面PARAM。

List<NameValuePair> params = new ArrayList<NameValuePair>(); 

      params.add(new BasicNameValuePair("email", email)); 
      params.add(new BasicNameValuePair("password", password)); 
      params.add(new BasicNameValuePair("androidToken", androidToken));// your token 

,並再次通過

DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 
      httpPost.setEntity(new UrlEncodedFormEntity(params));// passing again 
+0

哥們我無法登錄。我現在評論意圖部分,仍然有相同的錯誤。 Ö) – bShah

+0

@bShah不明白你爲什麼發送電子郵件nd密碼兩次 – duggu

+0

你是完全正確的。我再次編輯我的問題,讓我們看看你是否得到我。 – bShah

相關問題