Как применить диалог индикатора выполнения для входа в систему Проверка в Android? - PullRequest
0 голосов
/ 31 декабря 2011

Хай хотел бы отображать прогресс после начала проверки формы входа в систему.Я не могу понять, как это отобразить.Я перечислил часть моего кода ниже.Пожалуйста, дайте совет.Спасибо. И пытаюсь следовать этому уроку урок .

Обновление

package com.android.cdtech;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
 import android.util.Log;
 import android.view.View;
import android.widget.Button;
 import android.widget.TextView;
 import android.widget.Toast;
  public class loginForm extends Activity implements Runnable {
private TextView txt;
private ProgressDialog progDailog;
private TextView username;
private TextView password;
private Button sButton;
SoapObject request = null;
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
        SoapEnvelope.VER11);
private static final String HostUrl = "xxxx";
private static final String NAMESPACE = "yyyy/";
private static final String methodname = "InsertCustomerInformation";
private HttpTransportSE httpTransport = new HttpTransportSE(HostUrl);
private String check;
private Intent loginFormIntent;
 AlertDialog.Builder builder = new AlertDialog.Builder(this);

final ProgressDialog pd = null;
Thread thread = null;
Handler handler = new Handler() {
    public void handleMessage(Message msg) {
         pd.dismiss();
         if (msg.what == 11) {
            sButton.setBackgroundColor(Color.CYAN);
            sButton.setText("Login");
            TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            String getImeNumber = telephonyManager.getDeviceId();
            String methodname = "CheckLoginRoles";
            String user = username.getText().toString();
            String pword = password.getText().toString();

            if (user.equals("") || pword.equals("")) {
                Toast.makeText(getBaseContext(),
                        "Your Field is Emptry Please Fill all Fields ",
                        Toast.LENGTH_LONG).show();

            }

            if (check.equals("Authenticated")) {
                try {


                    startActivity(loginFormIntent);
                } catch (Exception e) {
                    Toast.makeText(getBaseContext(), "Exception" + e.toString(),
                            Toast.LENGTH_LONG).show();

                }
            } else {
                Toast.makeText(getBaseContext(), "" + check + "", Toast.LENGTH_LONG).show();
            }


            // Your code (for ex Toasting Message or passing
            // intents or displaying somthing....)
        } else if (msg.what == 0) {
            Toast.makeText(getBaseContext(), "" + check + "", Toast.LENGTH_LONG).show();
        } else {
            showNetworkAlert();
        }
    }

public void onCreate(Bundle icicle) {
    //super.onCreate(icicle);
    loginFormIntent = new Intent();
    setContentView(R.layout.main);
    username = (TextView) findViewById(R.id.username);
    password = (TextView) findViewById(R.id.password);
    sButton = (Button) findViewById(R.id.login);

    sButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            {
                if (isOnline(this)){//The method isOnline(Context) in the type new Handler(){} is not applicable for the arguments (new View.OnClickListener(){})here i got Error
   {
                    pd = ProgressDialog.show(this, "",
                            "Loading...", true, false);(Error)The method show(Context, CharSequence, CharSequence, boolean, boolean) in the type ProgressDialog is not applicable for the arguments (new 
   View.OnClickListener(){}, String, String, boolean, boolean)//
                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            try {

                                calWeb();
                                handler.sendEmptyMessage(11);
                            } catch (Exception e) {
                                System.out.println("In Cache :");
                                handler.sendEmptyMessage(1);
                            }
                        }
                    }).start();
                } else {
                    messages.showNetworkAlert();//messages cannot be resolved
                }
            }
        }
    });
}

private void showNetworkAlert() {

    builder
            .setMessage(
                    "Please check your internet connection.")
            .setPositiveButton(
                    "Ok",
                    new DialogInterface.OnClickListener() {
                        public void onClick(
                                DialogInterface dialog,
                                int id) {
                            dialog.dismiss();
                        }
                    });
    builder.setTitle("Connection Problem");
    builder.show();

}

public Boolean isOnline(Context context)        ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

public void run() {
    calWeb();

}

private void calWeb() {
    SoapPrimitive response = null;
    request = new SoapObject(NAMESPACE, methodname);
    envelope.dotNet = true;
    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    String getImeNumber = telephonyManager.getDeviceId();
    String methodname = "CheckLoginRoles";
    String user = username.getText().toString();
    String pword = password.getText().toString();
    request.addProperty("UserName", user);
    request.addProperty("Password", pword);
    request.addProperty("IMEINumber", getImeNumber);
    envelope.setOutputSoapObject(request);

    try {
        httpTransport.call(NAMESPACE + "IService/" + methodname, envelope);
        response = (SoapPrimitive) envelope.getResponse();
        check = response.toString();
                } catch (Exception e) {
                    handler.sendEmptyMessage(0);
                }
    }

};


@Override
public void run() {
    // TODO Auto-generated method stub

}}

Ответы [ 3 ]

4 голосов
/ 31 декабря 2011

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

private ProgressDialog pd;
Thread thread = null;
private Handler handler = new Handler() {
    public void handleMessage(Message msg) {
        pd.dismiss();
        if (msg.what == 11) {
            Your code (for ex Toasting Message or passing intents or displaying somthing....)

        } else if (msg.what == 0) {

        } else {
            showNetworkAlert();
        }
    }
};

затем Диалог создания прогресса в методе onCreate

    if (isOnline(Your class.this)) {
        pd = ProgressDialog.show(Your Class.this, "", "Loading...", true,
                false);
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Calling your parsing method ....
                    handler.sendEmptyMessage(11);
                } catch (Exception e) {
                    System.out.println("In Cache :");
                    handler.sendEmptyMessage(1);
                }
            }
        }).start();
    } else {
        showNetworkAlert();
    }

Создать этот метод для проверки интернета

public static Boolean isOnline(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

Отображение оповещения, если Интернет отсутствует

public void showNetworkAlert() {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setMessage("Please check your internet connection.")
            .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.dismiss();
                }
            });

    builder.setTitle("Connection Problem");
    builder.show();

}
1 голос
/ 31 декабря 2011

Я думаю, что эта модель может вам помочь:

Вы можете использовать:

  • Async Task
  • Обработчики

1. Асинхронное задание

      class WebTask extends AsyncTask<Void, Void, Void >{

            @Override
            protected void onPreExecute() {
                webProgressDialog.setTitle("Please Wait");
                webProgressDialog.setMessage("Authenticating...");
                if (!webProgressDialog.isShowing())
                    webProgressDialog.show();
                Log.i(TAG, "Progress Showing" +  webProgressDialog.isShowing());
                super.onPreExecute();
            }

            @Override
            protected Void doInBackground(Void... params) {
                  //Your Web request comes here make sure no ui operations coming here
            }

            @Override
            protected void onPostExecute(Void result) {
                if (webProgressDialog.isShowing())
                    webProgressDialog.dismiss();
                Log.i(TAG, "Progress Dismiss" + webProgressDialog.isShowing());
            }
    }

    //Calling task inside your coding..
     WebTask mywebTask = new WebTask();
     mywebTask.execute();

2. Обработчики:

        Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        if (msg.what == PROGRESS_SHOW) {
            progressDialog.show();

        } else if (msg.what == PROGRESS_CANCEL) {
            progressDialog.cancel();
        }
        };};


     private static final int PROGRESS_SHOW = 22, PROGRESS_CANCEL = 21 ;
     //  PROGRESS_SHOW, PROGRESS_CANCEL are just have to be distinct int values


  .....this have to insert in your request part
    handler.sendEmptyMessage(PROGRESS_SHOW);
    new Thread(){
    public void run(){
      // <--------Here web request coming ---->
       handler.sendEmptyMessage(PROGRESS_CANCEL); // This should be here 
       //if not send message to handler progressdialog wont dismiss
       }
    }.run();
0 голосов
/ 31 декабря 2011

Пожалуйста, попробуйте следующий код,

thisAct = this;  // onCreate Method , 
    ProgressDialog progressDialog = ProgressDialog.show( thisAct, "Login", "Success..." , true, false );

                new Thread ( new Runnable()
                {
                    public void run()
                    {
                        try
                        {

                            Thread.sleep(2000);
                            handler.sendMessage(handler.obtainMessage());
                        }
                        catch ( Exception e ) 
                        {  
                            Toast.makeText(thisAct, "DB Saving Error: " + e.toString(),Toast.LENGTH_LONG).show();
                        }
                    }
                }).start();

    private Handler handler = new Handler()
    {
        @Override
        public void handleMessage ( Message message )
        {
            progressDialog.dismiss();
        }
    };
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...