2

I want to get the Status value GetLoginDetails() method..but i dont know how to do it. Can any one help me to do this? Following is my work done.. LoginScreen.java

            public class LoginScreen extends Activity implements OnClickListener{
            EditText etusername,etpassword;
            public static Integer status= -1;
            private ProgressDialog pDialog;
            // URL to get contacts JSON
            private static String url= "http://xxx.xxx.x.xxx/abc/login.php";
            private static final String LOGIN = "Login";
            private static final String STATUS = "Status";
            // contacts JSONArray
            JSONArray loginjsonarray=null;
            @Override
            protected void onCreate(Bundle savedInstanceState){
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_login_screen);
                initialize();
            }
        //Initialization of components
            private void initialize() {
                //Getting the reference of font from assets folder
                String fontPath = "Font/Arsenal-Regular.otf";
                Typeface tf = Typeface.createFromAsset(getAssets(),fontPath);
              //Getting the reference of EditText
                etusername=(EditText)findViewById(R.id.editTextLoginusernamenumber);
                etpassword=(EditText)findViewById(R.id.editTextLoginpassword);
                //Getting the reference of textView
                TextView textViewloginforgotpassword=(TextView)findViewById(R.id.textViewloginforgotpassword);
                //set font to textView
                textViewloginforgotpassword.setTypeface(tf);
                //set underline TextView
                textViewloginforgotpassword.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
                //Getting references of buttons
                Button buttonlogin=(Button)findViewById(R.id.buttonlogin);
               //set on click listener on buttons
                buttonlogin.setOnClickListener(this);
            }//end of Initialization
            //on click method   
            @Override
            public void onClick(View v) {
                if(v.getId()==R.id.buttonlogin){
                    new GetLoginDetails().execute();
                    if(status==1)**//here I want to check that value**
                    {
                        Intent intent=new Intent(LoginScreen.this,MenuScreen.class);
                        startActivity(intent);
                        finish();
                    }
                 }
                }//end of on click
            @Override
            public void onBackPressed(){
                finish();
                super.onBackPressed();
            }
            private class GetLoginDetails  extends AsyncTask<Void, Void, Integer>
            {
                protected void onPreExecute() {
                    // Showing progress dialog
                    pDialog = new ProgressDialog(LoginScreen.this);
                    pDialog.setMessage("Loading...");
                    pDialog.setCancelable(false);
                    pDialog.show();
                }
                protected Integer doInBackground(Integer... arg) {
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("username",etusername.getText().toString()));
                    params.add(new BasicNameValuePair("userPassword", etpassword.getText().toString()));
                    // Creating service handler class instance
                    ServiceHandler sh = new ServiceHandler();
                     // Making a request to url and getting response
                    String jsonstr = sh.makeServiceCall(url, ServiceHandler.GET, params);
                    Log.d("Response: ", ">"+jsonstr);
                    if(jsonstr!=null){
                        try {
                                JSONObject jsonObj =new JSONObject(jsonstr);
                                loginjsonarray=jsonObj.getJSONArray(LOGIN);
                                for(int i=0;i<loginjsonarray.length();i++){
                                    JSONObject l=loginjsonarray.getJSONObject(i);
                                    status=l.getInt(STATUS);**//how to get this value to login_button onclick scope??**
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                    }else{
                        Log.e("ServiceHandler", "Couldn't get any data from the url");
                    }
                    return status;
                }
                protected void onPostExecute(Integer result) {
                    // Dismiss the progress dialog
                    if(pDialog.isShowing()){
                        pDialog.dismiss();
                    }
                    return result;
                }
            }
        }

ServiceHandler.java

                public class ServiceHandler {
                    static String response = null;
                    public final static int GET = 1;
                    public final static int POST = 2;
                    public String makeServiceCall(String url, int method) {
                        return this.makeServiceCall(url, method, null);
                    }
                    /**
                     * Making service call
                     * @url - url to make request
                     * @method - http request method
                     * @params - http request params
                     * */
                    public String makeServiceCall(String url, int method, List<NameValuePair> params)  {
                        try {
                                DefaultHttpClient httpClient=new DefaultHttpClient();
                                HttpEntity httpEntity=null;
                                HttpResponse httpResponse=null;
                                // Checking http request method type
                                if(method==POST){
                                    HttpPost httpPost=new HttpPost(url);
                                    if(params!=null)
                                    {
                                        //adding post params
                                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                                    }
                                    httpResponse=httpClient.execute(httpPost);
                                }
                                else if(method==GET)
                                {
                                    // appending params to url
                                    if(params!=null)
                                    {
                                        String paramString=URLEncodedUtils.format(params, "utf-8");
                                        url +="?"+paramString;
                                    }
                                    HttpGet httpGet=new HttpGet(url);
                                    httpResponse=httpClient.execute(httpGet);
                                }
                                httpEntity=httpResponse.getEntity();
                                response=EntityUtils.toString(httpEntity);
                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (ClientProtocolException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        return response;
                    }
            }

please help me as early as possible

Akshay
  • 6,029
  • 7
  • 40
  • 59

2 Answers2

0

In your onPostExecute...

Before the // Dismiss the progress dialog

            //compare your status/integer value over here and depending on that, while dismissing the dialog
                    if(pDialog.isShowing() && compareValue()){
                        pDialog.dismiss();
                    //show a custom dialog maybe or depending on your requirement carry on with your implementation
                    } else {
                      //show the message to the user (not signed in or invalid credentials dialog etc)                   
 }
Pararth
  • 8,114
  • 4
  • 34
  • 51
  • yes so why are you writing the "if(status).." separately. Check the condition and either dismiss pd or launch Menu...http://stackoverflow.com/questions/9118015/how-to-correctly-start-activity-from-postexecute-in-android – Pararth Feb 08 '14 at 10:24
0

You have several choices:

  • Use a Handler. You define it within your Activity, pass it to your AsyncTask via a new function like setHandler(Handler my_handler) and send a message from it.

  • Use a local BroadcastReceiver. If you don't know how to do it, check this link, it's a great example and well explained.

---- EDIT ----

This would be an example of a Handler. In your Activity define something like this:

public class MyRcvData extends Handler {
  @Override
  public void handleMessage(Message msg) {
    Integer your_int = msg.arg1;
    Log.d("MyClass", "My Integer is: " + your_int);
  }
}

Define an instance of that Handler. Save it as a class-wide instance, so you can access it whenever you need:

public class LoginScreen extends Activity implements OnClickListener {
  ... Declarations ...
  MyRcvData myHandler = new MyRcvData();

In your AsyncTask, add a public method to set the handler, so the AsyncTask knows which handler to use to send messages.

  public void setHandler(Handler h) { myHandler = h; }

Of course, that means you need to store the Handler in your AsyncTask as well. Declare it that way: Handler myHandler;

You have to call this method prior to calling execute(), so your MyRcvData has to be initialized prior to calling execute() too.

Now you just have to send your "message". In your AsyncTask, whenever you need to send your Integer to your Activity, you would do something like this:

Message msg = Message.obtain();
msg.arg1 = your_integer;
msg.sendMessage();

That will fire your handleMessage() above. I strongly recommend having a look at both the Message class and Handler class for further info.

nKn
  • 13,691
  • 9
  • 45
  • 62
  • Sorry, but it will be great if you help me with example, as I'm at beginners level I don't get it easily.. – Akshay Feb 08 '14 at 10:26
  • Thank you so much for your efforts for me..but method from @user2450263 was to short and easy so I tried that one.. – Akshay Feb 08 '14 at 11:08
  • In the last line, it's not `msg.sendMessage();` but `myHandler.sendMessage(msg);` But it works well, ty ! – GtN May 16 '20 at 16:39