2014-12-16 1 views
0

Это мой LoginActivity.javaНамерение HomeActivity после успеха статуса Логин

Это будет посылать данные для входа в HttpAsyncTask .java

final Button button = (Button) findViewById(R.id.btnLogin); 
    button.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View v) { 

      try { 

       // Get Email Edit View Value 
       String email = emailET.getText().toString(); 
       // Get Password Edit View Value 
       String password = pwdET.getText().toString(); 
       // Instantiate Http Request Param Object 
       //     RequestParams params = new RequestParams(); 
       // When Email Edit View and Password Edit View have values 
       // other than Null 
       if (Utility.isNotNull(email) && Utility.isNotNull(password)) { 
        // When Email entered is Valid 
        if (Utility.validate(email)) { 

         //call the async task 

         JSONObject js = new HttpAsyncTask(getApplicationContext()).execute(email,password).get(); 

         Toast.makeText(getApplicationContext(), "Asynctask started", Toast.LENGTH_SHORT).show(); 

        } 
        // When Email is invalid 
        else { 
         Toast.makeText(getApplicationContext(), 
           "Please enter valid email", 
           Toast.LENGTH_LONG).show(); 
        } 
       } 
       // When any of the Edit View control left blank 
       else { 
        Toast.makeText(
          getApplicationContext(), 
          "Please fill the form, don't leave any field blank", 
          Toast.LENGTH_LONG).show(); 
       } 
      } catch (Exception ex) { 

      } 

     } 
    }); 
    } 
} 

HttpAsyncTask.java

public class HttpAsyncTask extends AsyncTask<String, Integer, JSONObject> { 

private static InputStream stream = null; 
private static String API; 
private JSONObject responseJson = null; 
private Context contxt; 
private Activity activity; 

public HttpAsyncTask(Context context) { 

    // API = apiURL; 
    this.contxt = context; 
} 

// async task to accept string array from context array 
@Override 
protected JSONObject doInBackground(String... params) { 

    String path = null; 
    String response = null; 
    HashMap<String, String> request = null; 
    JSONObject requestJson = null; 
    DefaultHttpClient httpClient = null; 
    HttpPost httpPost = null; 
    StringEntity requestString = null; 
    ResponseHandler<String> responseHandler = null; 

    // get the username and password 
    Log.i("Email", params[0]); 
    Log.i("Password", params[1]); 

    try { 

     path = "http://192.168.XXXXXXX"; 
     new URL(path); 
    } catch (MalformedURLException e) { 

     e.printStackTrace(); 
    } 

    try { 

     // set the API request 
     request = new HashMap<String, String>(); 
     request.put(new String("Email"), params[0]); 
     request.put(new String("Password"), params[1]); 
     request.entrySet().iterator(); 


     requestJson = new JSONObject(request); 
     httpClient = new DefaultHttpClient(); 
     httpPost = new HttpPost(path); 
     requestString = new StringEntity(requestJson.toString()); 


     httpPost.setEntity(requestString); 
     httpPost.setHeader("Content-type", "application/json"); 

     // Handles the response 
     responseHandler = new BasicResponseHandler(); 
     response = httpClient.execute(httpPost, responseHandler); 

     responseJson = new JSONObject(response); 

    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 
    try { 
     responseJson = new JSONObject(response); 
    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
    } 

    return responseJson; 
} 

@Override 
protected void onPostExecute(JSONObject result) { 
    // TODO Auto-generated method stub 
    super.onPostExecute(result); 
    Log.d("MyAsyncTask", "Received result: " + result); //here i get Received result: {"status":"400"} 

} 

Моя проблема заключается хотите знать, как направить его на ActivityHome, когда логин является успешным, если логин является ошибкой, тогда он должен отображать сообщение об ошибке.

Я попробовал это в onPostExecute методе

activity.startActivity(new Intent(activity, ActivityHome.class)); 

, но он не работает, приложение разбился.

+1

Показать код вы пробовали и ошибки вы получите на аварии –

+0

Ваша деятельность не инициализирована –

+0

тека на вашем советуют сначала XML. когда вы пытаетесь выполнить определенную операцию, и вы не инициализировали ее, ваша система сработает – Secondo

ответ

0

Во-первых, вы должны сохранить свой ответ в JSONObject в onPostExecute Метод.

protected void onPostExecute(JSONObject result) { 
    // TODO Auto-generated method stub 
    super.onPostExecute(result); 
    if(responseJson!=null){ 
     try{ 
      JSONObject jObjstatus=new JSONObject(responseJson); 
      String status=jObjstatus.getString("status"); 
      if(status.equals("success"){ 
       startActivity(new Intent(MainActivity.this, SecondActivity.class); 
      } 
     }catch(){ 
     } 
    } 
} 
0

общественный класс HttpAsyncTask расширяет AsyncTask {

private static InputStream stream = null; 
private static String API; 
private JSONObject responseJson = null; 
private Context contxt; 
private Activity activity; 

public HttpAsyncTask(Context context) { 

    // API = apiURL; 
    this.contxt = context; 
} 

// async task to accept string array from context array 
@Override 
protected JSONObject doInBackground(String... params) { 

    String path = null; 
    String response = null; 
    HashMap<String, String> request = null; 
    JSONObject requestJson = null; 
    DefaultHttpClient httpClient = null; 
    HttpPost httpPost = null; 
    StringEntity requestString = null; 
    ResponseHandler<String> responseHandler = null; 

    // get the username and password 
    Log.i("Email", params[0]); 
    Log.i("Password", params[1]); 

    try { 

     path = "http://192.168.XXXXXXX"; 
     new URL(path); 
    } catch (MalformedURLException e) { 

     e.printStackTrace(); 
    } 

    try { 

     // set the API request 
     request = new HashMap<String, String>(); 
     request.put(new String("Email"), params[0]); 
     request.put(new String("Password"), params[1]); 
     request.entrySet().iterator(); 


     requestJson = new JSONObject(request); 
     httpClient = new DefaultHttpClient(); 
     httpPost = new HttpPost(path); 
     requestString = new StringEntity(requestJson.toString()); 


     httpPost.setEntity(requestString); 
     httpPost.setHeader("Content-type", "application/json"); 

     // Handles the response 
     responseHandler = new BasicResponseHandler(); 
     response = httpClient.execute(httpPost, responseHandler); 

     responseJson = new JSONObject(response); 

    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 


    return responseJson; 
} 

@Override 
protected void onPostExecute(JSONObject result) { 
    // TODO Auto-generated method stub 
    super.onPostExecute(result); 
    if (result != null) { 
     String status = result.optString("status"); 
     if (status.equalsIgnoreCas("200")) 
     { 
      ((Activity) context).startActivity(new Intent(context, HomeActivity.class)); 

     }else 
     { 
      //error message 
     } 
    } else { 
     //error message 
    } 
} 
+0

, когда я попробовал этот код, он не сработал и не ответил ни на что, но дал ответ 12-16 12: 50: 07.030: D/dalvikvm (499): GC_FOR_ALLOC освобожден 151K, 3% бесплатно 7831K/8048K, приостановлено 11 мс, всего 11 мс –

+0

Можете ли вы распечатать ответ в log.Add System.out.Println (ответ «+ ответ»); в doinBackground и проверьте – androidbeatz

Смежные вопросы