如何从AsyncTask获取int值

时间:2014-02-08 10:08:20

标签: android json android-asynctask

我想获取状态值GetLoginDetails()方法..但我不知道该怎么做。 任何人都可以帮我这样做吗?以下是我完成的工作.. 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;
                    }
            }

请尽早帮助我

2 个答案:

答案 0 :(得分:0)

在你的onPostExecute ......

在//关闭进度对话框之前

            //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)                   
 }

答案 1 :(得分:0)

您有多种选择:

  • 使用Handler。您可以在Activity中对其进行定义,然后通过AsyncTask等新功能将其传递给setHandler(Handler my_handler),并向其发送消息。

  • 使用本地BroadcastReceiver。如果你不知道如何去做,check this link,这是一个很好的例子并且得到了很好的解释。

----编辑----

这是Handler的一个例子。在Activity中定义如下内容:

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

定义该Handler的实例。将其另存为类范围的实例,以便您可以在需要时访问它:

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

AsyncTask中,添加公开方法来设置处理程序,以便AsyncTask知道用于发送邮件的处理程序。

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

当然,这意味着您还需要将Handler存储在AsyncTask中。以这种方式声明:Handler myHandler;

您必须先调用此方法之前来调用execute(),因此在调用MyRcvData之前必须先初始化您的execute()

现在您只需发送&#34;消息&#34;。在AsyncTask,只要您需要将Integer发送到Activity,就可以执行以下操作:

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

这将触发你的handleMessage()以上。我强烈建议您查看Message classHandler class以获取更多信息。

相关问题