2013-09-29 3 views
-2

Привет Я в RegisterActivity.java так:Синтаксический Json с помощью AsyncTask

public class RegisterActivity extends Activity{ 
     private static final String TAG = "PostFetcher"; 
     private static String URL = "http://api.example.com/"; 
     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.register); 

      final EditText inputFname = (EditText) findViewById(R.id.registerFname); 
      final EditText inputLname = (EditText) findViewById(R.id.registerLname); 
      final EditText inputEmail = (EditText) findViewById(R.id.registerEmail); 
      Button btnRegister = (Button) findViewById(R.id.btnRegister); 
      Button btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLogin); 
      final TextView loginErrorMsg = (TextView) findViewById(R.id.register_error); 

      // Register Button Click event 
      btnRegister.setOnClickListener(new View.OnClickListener() { 
       Login login2; 
       RadioGroup radioSexGroup = (RadioGroup) findViewById(R.id.sex); 
       public void onClick(View view) { 
        String fname = inputFname.getText().toString(); 
        String lname = inputLname.getText().toString(); 
        String email = inputEmail.getText().toString(); 

        // get selected radio button from radioGroup 
        int selectedId = radioSexGroup.getCheckedRadioButtonId(); 
        RadioButton radioSexButton = (RadioButton) findViewById(selectedId); 
        String gender = radioSexButton.getText().toString(); 
        //System.out.println(fname); 
        //Toast.makeText(RegisterActivity.this, radioSexButton.getText(), Toast.LENGTH_SHORT).show(); 

        String registerURL = URL +"&user_email="+ email /**+"&first_name="+ fname +"&last_name="+ lname*/ +"&gender="+ gender; 
        System.out.println(registerURL); 

        if(email.length() == 0) { 
         loginErrorMsg.setText(R.string.empty); 
         //Toast.makeText(view.getContext(), R.string.empty, Toast.LENGTH_SHORT).show(); 
         return; 
        }else{ 

         try { 
          //Create an HTTP client 
          DefaultHttpClient client = new DefaultHttpClient(); 
          HttpPost post = new HttpPost(registerURL); 

          //Perform the request and check the status code 
          HttpResponse response = client.execute(post); 
          StatusLine statusLine = response.getStatusLine(); 
          if(statusLine.getStatusCode() == 200) { 
           HttpEntity entity = response.getEntity(); 
           InputStream content = entity.getContent(); 

           try { 
            //Read the server response and attempt to parse it as JSON 
            Reader reader = new InputStreamReader(content); 

            Gson gson = new Gson(); 
            this.login2 = gson.fromJson(reader, Login.class); 
            //System.out.println(this.login2); 
            //handlePostsList(posts); 
           } catch (Exception ex) { 
            Log.e(TAG, "Failed to parse JSON due to: " + ex); 
            failedLoading(); 
           } 
          } else { 
           Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode()); 
           failedLoading(); 
          } 
         } catch(Exception ex) { 
          Log.e(TAG, "Failed to send HTTP POST request due to: " + ex); 
          failedLoading(); 
         } 

         //To set register message 
         if(login2.getResult().equals("OK")){ 
          loginErrorMsg.setText(login2.getMessage().toString()); 
         }else if(login2.getResult().equals("KO")){ 
          loginErrorMsg.setText(login2.getMessage().toString()); 
         } 
        } 

       } 
      }); 


      // Link to Login 
      btnLinkToLogin.setOnClickListener(new View.OnClickListener() { 
        public void onClick(View view) { 
         Intent i = new Intent(getApplicationContext(),LoginActivity.class); 
         startActivity(i); 
         finish(); 
        } 
      }); 

     } 

     public void onRadioButtonClicked(View view) { 
      // Is the button now checked? 
      boolean checked = ((RadioButton) view).isChecked(); 

      // Check which radio button was clicked 
      switch(view.getId()) { 
       case R.id.male: 
        if (checked) 
         // Pirates are the best 
        break; 
       case R.id.female: 
        if (checked) 
         // Ninjas rule 
        break; 
      } 
     } 

     private void failedLoading() { 
      runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        Toast.makeText(RegisterActivity.this, "Failed to Register. look at LogCat.", Toast.LENGTH_SHORT).show(); 
       } 
      }); 
     } 
} 

Но я получаю ошибку следующим образом: Failed to send HTTP POST request due to: android.os.NetworkOnMainThreadException Android разработчики форум предложить мне реализовать его с помощью AsyncTask, чтобы решить эту проблему. Но я не знаю, как это изменить. Может кто-нибудь помочь мне решить эту проблему? Я провел несколько часов, но не нашел решения.

+0

Функция поиска является вашим другом: [android.os.NetworkOnMainThreadException] (http://stackoverflow.com/ вопросы/6343166/android-os-networkonmainthreadexception) –

+0

где ваша асинтеза? – Raghunandan

ответ

0

Вы хотите поместить все сети/разбора кода в doInBackground() вашего AsyncTask. Сделайте AsyncTask внутренним классом вашего Activity. После получения результата вы захотите вернуть это значение onPostExecute(), чтобы сделать UI материал, такой как обновление Views.

Создав внутренний класс AsyncTask, вы получите доступ к переменным-членам Activity и его функциям.

This answer даст вам хорошую отправную точку для создания вашего AsyncTask и вызова его.

Read through the AsyncTask Docs понять правила требует

проверить эти ссылки и дать ему попробовать. Затем задайте вопрос с более конкретной проблемой при возникновении проблем (обязательно включите соответствующие ошибки кода и logcat, если вы застряли).

+0

Можете ли вы мне помочь в этом вопросе, пожалуйста: http://stackoverflow.com/questions/19092708/error-parsing-json-to-java-object-com-google-gson-jsonsyntaxexception-expectin – Kabe

0

Самый простой подход, чтобы вы начали, чтобы создать анонимный внутренний класс и выполнить его в вашем onCreate:

// if email length != 0 
new AsyncTask<Void, Void, Void> { 
    protected void doInBackground() { 
     //Create an HTTP client 
     //Update login2 
    } 
}.execute(); 

Там, однако, много тонких нюансов, и я настоятельно рекомендую прочитать все эти 2 страницы: http://developer.android.com/reference/android/os/AsyncTask.html и http://developer.android.com/guide/components/processes-and-threads.html

0

Я честно думаю, что вы бы понять это с некоторым усилием, но здесь вы идете:

public class RegisterActivity extends Activity{ 
private static final String TAG = "PostFetcher"; 
private static String URL = "http://api.example.com/"; 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.register); 

    final EditText inputFname = (EditText) findViewById(R.id.registerFname); 
    final EditText inputLname = (EditText) findViewById(R.id.registerLname); 
    final EditText inputEmail = (EditText) findViewById(R.id.registerEmail); 
    Button btnRegister = (Button) findViewById(R.id.btnRegister); 
    Button btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLogin); 
    final TextView loginErrorMsg = (TextView) findViewById(R.id.register_error); 

    // Register Button Click event 
    btnRegister.setOnClickListener(new View.OnClickListener() { 
     Login login2; 
     RadioGroup radioSexGroup = (RadioGroup) findViewById(R.id.sex); 
     public void onClick(View view) { 
      String fname = inputFname.getText().toString(); 
      String lname = inputLname.getText().toString(); 
      String email = inputEmail.getText().toString(); 

      // get selected radio button from radioGroup 
      int selectedId = radioSexGroup.getCheckedRadioButtonId(); 
      RadioButton radioSexButton = (RadioButton) findViewById(selectedId); 
      String gender = radioSexButton.getText().toString(); 
      //System.out.println(fname); 
      //Toast.makeText(RegisterActivity.this, radioSexButton.getText(), Toast.LENGTH_SHORT).show(); 

      String registerURL = URL +"&user_email="+ email /**+"&first_name="+ fname +"&last_name="+ lname*/ +"&gender="+ gender; 
      System.out.println(registerURL); 

      if(email.length() == 0) { 
       loginErrorMsg.setText(R.string.empty); 
       //Toast.makeText(view.getContext(), R.string.empty, Toast.LENGTH_SHORT).show(); 
       return; 
      }else{ 
       new LoginTask.execute(); 
      } 

     } 
    }); 


    // Link to Login 
    btnLinkToLogin.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View view) { 
       Intent i = new Intent(getApplicationContext(),LoginActivity.class); 
       startActivity(i); 
       finish(); 
      } 
    }); 

} 

public void onRadioButtonClicked(View view) { 
    // Is the button now checked? 
    boolean checked = ((RadioButton) view).isChecked(); 

    // Check which radio button was clicked 
    switch(view.getId()) { 
     case R.id.male: 
      if (checked) 
       // Pirates are the best 
      break; 
     case R.id.female: 
      if (checked) 
       // Ninjas rule 
      break; 
    } 
} 

private void failedLoading() { 
    runOnUiThread(new Runnable() { 
     @Override 
     public void run() { 
      Toast.makeText(RegisterActivity.this, "Failed to Register. look at LogCat.", Toast.LENGTH_SHORT).show(); 
     } 
    }); 

private class LoginTask extends 
     AsyncTask<Void, Void, Void> { 

      ProgressDialog progressDialog; 

    // Before running code in separate thread 
    @Override 
    protected void onPreExecute() { 
     // Create a new progress dialog. 
     progressDialog = new ProgressDialog(context); 
     // Set the progress dialog to display a horizontal bar . 
     // progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
     // Set the dialog title to 'Loading...'. 
     // progressDialog.setTitle("Loading..."); 
     // Set the dialog message to 'Loading application View, please 
     // wait...'. 
     progressDialog.setMessage("Loading..."); 
     // This dialog can't be canceled by pressing the back key. 
     progressDialog.setCancelable(false); 
     // This dialog isn't indeterminate. 
     progressDialog.setIndeterminate(true); 
     // The maximum number of progress items is 100. 
     // progressDialog.setMax(100); 
     // Set the current progress to zero. 
     // progressDialog.setProgress(0); 
     // Display the progress dialog. 
     progressDialog.show(); 

    } 

    // The code to be executed in a background thread. 
    @Override 
    protected VoiddoInBackground(Void... arg) { 
     try { 
        //Create an HTTP client 
        DefaultHttpClient client = new DefaultHttpClient(); 
        HttpPost post = new HttpPost(registerURL); 

        //Perform the request and check the status code 
        HttpResponse response = client.execute(post); 
        StatusLine statusLine = response.getStatusLine(); 
        if(statusLine.getStatusCode() == 200) { 
         HttpEntity entity = response.getEntity(); 
         InputStream content = entity.getContent(); 

         try { 
          //Read the server response and attempt to parse it as JSON 
          Reader reader = new InputStreamReader(content); 

          Gson gson = new Gson(); 
          this.login2 = gson.fromJson(reader, Login.class); 
          //System.out.println(this.login2); 
          //handlePostsList(posts); 
         } catch (Exception ex) { 
          Log.e(TAG, "Failed to parse JSON due to: " + ex); 
          failedLoading(); 
         } 
        } else { 
         Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode()); 
         failedLoading(); 
        } 
       } catch(Exception ex) { 
        Log.e(TAG, "Failed to send HTTP POST request due to: " + ex); 
        failedLoading(); 
       } 

    } 


    // after executing the code in the thread 
    @Override 
    protected void onPostExecute() { 
     // close the progress dialog 
     progressDialog.dismiss(); 
            //To set register message 
       if(login2.getResult().equals("OK")){ 
        loginErrorMsg.setText(login2.getMessage().toString()); 
       }else if(login2.getResult().equals("KO")){ 
        loginErrorMsg.setText(login2.getMessage().toString()); 
       } 

    } 
} 

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