2013-12-12 2 views
-1

Пожалуйста, прочитайте так много на этом, (он говорит, что я не должен помещать диалог в doInbackground). Но пытались сделать это некоторое время, на самом деле это мое первое приложение для Android (с java) , Как я могу показать панель загрузки, отключить кнопку (пока не появится ответ) и перенаправить на другую работу на успех.Показать прогресс Android Войти

public class Index extends Activity implements OnClickListener { 

    EditText username, password; 
    Button login; 
    String uname,pass; 
    TextView login_err; 

    HttpClient httpclient; 

    HttpPost htpost; 

    ArrayList <NameValuePair> namearray; 

    HttpResponse response; 
    HttpEntity entity; 
    int Server_response; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 


     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_index); 
     login_err= (TextView) findViewById(R.id.login_err); 
     initialise(); 

    } 



    private void initialise() { 
     username = (EditText) findViewById(R.id.email); 
     password = (EditText) findViewById(R.id.password); 
     login= (Button) findViewById(R.id.login_btn); 
     login.setOnClickListener(this);; 
    } 

    public void onClick(View v) { 
     String umail=username.getText().toString(); 
     String pass= password.getText().toString(); 
     if(umail.length()!=0 && pass.length()!=0){ 
      new MyAsyncTask().execute(); 
     }else{ 
      Toast.makeText(getBaseContext(), "Please provide username and password",Toast.LENGTH_SHORT).show(); 
     } 


    }//END onClick() 

    private static String convertStreamToString(InputStream is) { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
     StringBuilder sb = new StringBuilder(); 

     String line = null; 
     try { 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       is.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     return sb.toString(); 
    }//END convertStreamToString() 



    private class MyAsyncTask extends AsyncTask <Void, Void, Void> { 
     ProgressDialog mProgressDialog; 
     @Override 
     protected void onPostExecute(Void result) { 
      if(Server_response==1){ 
       mProgressDialog.dismiss(); 
      } 
     } 

     protected void onPreExecute() { 

      mProgressDialog = ProgressDialog.show(Index.this, "Loading...", "Logging In..."); 
     } 

     protected Void doInBackground(Void... params) { 

      //Create new default HTTPClient 
      httpclient = new DefaultHttpClient(); 

      //Create new HTTP POST with URL to php file as parameter 
      htpost = new HttpPost("http://10.0.2.2/fanaticmobile/log_in.php"); 

      //Assign input text to strings 
      uname= username.getText().toString(); 
      pass= password.getText().toString(); 



      //Next block of code needs to be surrounded by try/catch block for it to work 
      try { 
       //Create new Array List 
       namearray = new ArrayList<NameValuePair>(); 

       //place them in an array list 
       namearray.add(new BasicNameValuePair("username", uname)); 
       namearray.add(new BasicNameValuePair("password", pass)); 

       //Add array list to http post 
       htpost.setEntity(new UrlEncodedFormEntity(namearray)); 


       //assign executed form container to response 
       response= httpclient.execute(htpost); //response from the PHP file 

       //check status code, need to check status code 200 
       if(response.getStatusLine().getStatusCode()==200){ 


        //assign response entity to http entity 
        entity= response.getEntity(); 

        //check if entity is not null 
        if(entity != null){ 


         //Create new input stream with received data assigned 
         InputStream instream = entity.getContent(); 

         //Create new JSON Object. assign converted data as parameter. 
         JSONObject jresponse = new JSONObject(convertStreamToString(instream)); 

         //assign json responses to local strings 
         String logged= jresponse.getString("logged"); 
         if(logged.equals("true")){ 
          Server_response=1; 
          //Please i want to redirect to a new activity here 
         }else{ 
          Log.d("Error Invalid credentials",logged); 
          Server_response=0; 
         } 


        } 


       } 


      } catch(Exception e){ 
       Toast.makeText(getBaseContext(), "Connection Error", Toast.LENGTH_SHORT).show(); 

       return null; 
      } 



      return null; 
     } 

    } 
} 

ответ

1

Вы должны взглянуть на класс loginActivity из Android SDK есть шаблон, делать то, что вы хотите.

Они есть метод, который показывает анимацию в то время как AsyncTask запущен, вы просто должны называть его перед выполнением вашего AsyncTask как то

showProgress(true); 
mAuthTask = new UserLoginTask();    
mAuthTask.execute(); 

Вот метод:

private void showProgress(final boolean show) { 

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { 
     int shortAnimTime = getResources().getInteger(
       android.R.integer.config_shortAnimTime); 

     mLoginStatusView.setVisibility(View.VISIBLE); 
     mLoginStatusView.animate().setDuration(shortAnimTime) 
       .alpha(show ? 1 : 0) 
       .setListener(new AnimatorListenerAdapter() { 
        @Override 
        public void onAnimationEnd(Animator animation) { 
         mLoginStatusView.setVisibility(show ? View.VISIBLE 
           : View.GONE); 
        } 
       }); 

     mLoginFormView.setVisibility(View.VISIBLE); 
     mLoginFormView.animate().setDuration(shortAnimTime) 
       .alpha(show ? 0 : 1) 
       .setListener(new AnimatorListenerAdapter() { 
        @Override 
        public void onAnimationEnd(Animator animation) { 
         mLoginFormView.setVisibility(show ? View.GONE 
           : View.VISIBLE); 
        } 
       }); 
    } else { 
     mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE); 
     mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); 
    } 
} 

, а затем в вашей асинтете, которую вы используете onPostExecute, которая вызывается после завершения асинтезы, и вы можете остановить анимацию входа и начать новую деятельность оттуда

protected void onPostExecute(String[] userDetails) { 
showProgress(false);    

+0

Большое спасибо, я бы посмотрел на функцию, о которой вы упомянули. Очень ценю. – altoin

+0

Вы также приветствуете, также проверьте xml-файл loginActivity, чтобы у вас была полная вещь –

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