簡體   English   中英

如何在Android中將接口用作響應偵聽器?

[英]How to use interface as a Response Listener in android?

我有這段代碼正在使用,我對控制流程感到困惑。

該接口在這里如何用作響應偵聽器? LoginActivity類中的重寫方法responseObject(JSONObject resp,String type)如何觸發?

並在調用AsyncTask之后將控件移至何處?

 public class LoginActivity extends Activity implements ResponseListener{

       login = (Button) findViewById(R.id.btnLogin);

       login.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v)
            {
                 String username = mUsernameField.getText().toString();
                 String password = mPasswordField.getText().toString();
                 String[] param = {username, password};
                 new ServerRequests.LoginUserAsyncTask(LoginActivity.this,this).execute(param);

            }

    @Override
    public void responseObject(JSONObject resp, String type) {
        try{
            if (resp.has("api_key")) {
                String api_key = resp.getString("api_key");
                String user_id = resp.getString("user");
                Log.i("api_key", api_key);
                SharedPreferences settings =     LoginActivity.this.getSharedPreferences(Constants.NADA_SP_KEY, 0);
                final SharedPreferences.Editor editor = settings.edit();
                editor.putString(Constants.NADA_API_KEY, api_key);
                editor.putString(Constants.NADA_USER_ID, user_id);
                editor.putBoolean(Constants.NADA_IS_LOGGED_IN, true);
                editor.commit();
                Log.i("first Visit", "False");
                String should_show_questions_screen = resp.getString("should_set_basic_questions");
                if (should_show_questions_screen.compareToIgnoreCase("true")==0){

                    Intent intent=new Intent(LoginActivity.this,RegistrationSuccessfulScreen.class);
                    startActivity(intent);
                    finish();


                }else {
                    Intent intent = new Intent(LoginActivity.this, UserNavigationActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        }catch (JSONException e){
            e.printStackTrace();
        }
    }




//Heres my ServerRequest Class which uses AsyncTask

    public class ServerRequests {

      public static class LoginUserAsyncTask extends AsyncTask<String, Void, String> {

        static JSONObject udetails;

        Context mContext;
        ResponseListener mResponseListener;
        SweetAlertDialog progressDialog;

        public LoginUserAsyncTask(Context mContext,ResponseListener listener) {
            this.mContext = mContext;
            this.mResponseListener = listener;

        }

        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog =new SweetAlertDialog(mContext, SweetAlertDialog.PROGRESS_TYPE);
            progressDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
            progressDialog.setTitleText("please wait connecting..");
            progressDialog.setCancelable(false);
            progressDialog.show();


        }

        @Override
        protected String doInBackground(String... params) {

            HttpClient client = new DefaultHttpClient();
            HttpPost post = null;
            udetails = new JSONObject();
            String response_data = "";
            if (params.length == 2) {
                try {
                    post = new HttpPost(Config.SERVER_BASE_URL + "/login");
                    udetails.put("username", params[0]);
                    udetails.put("password", params[1]);
                    SharedPreferences settings = mContext.getSharedPreferences(Constants.NADA_SP_KEY, 0);
                    final SharedPreferences.Editor editor = settings.edit();
                    editor.putString(Config.USER_NAME, params[0]).commit();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    post = new HttpPost(Config.SERVER_BASE_URL + "/login_with_fb");
                    udetails.put("fb_id", params[0]);
                    udetails.put("fb_auth_token", params[1]);
                    SharedPreferences settings = mContext.getSharedPreferences(Constants.NADA_SP_KEY, 0);
                    final SharedPreferences.Editor editor = settings.edit();
                    editor.putString(Config.USER_NAME, params[0]).commit();

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
            try {
                StringEntity se = new StringEntity(udetails.toString());
                se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                post.setEntity(se);
                HttpResponse response = client.execute(post);
                int response_code = response.getStatusLine().getStatusCode();
                response_data = EntityUtils.toString(response.getEntity());
                Log.i("api_token", response_data);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();

            }

            return response_data;
        }

        @Override
        protected void onPostExecute(String response) {

            progressDialog.dismiss();
            JSONObject resp = new JSONObject();
            try {
                resp = new JSONObject(response);
                if (resp.has("status")) {
                    if (resp.getString("status").compareToIgnoreCase("unauthorised")==0){

                        AppMsg appMsg = AppMsg.makeText((Activity)mContext, resp.getString("message"), style);
                        appMsg.show();

                    }
                }
                mResponseListener.responseObject(resp,"LOGIN");

            } catch (JSONException e) {
                AppMsg appMsg = AppMsg.makeText((Activity)mContext, "Something went wrong", style);
                appMsg.show();
                e.printStackTrace();
            }

        }
}


//Here's Interface Which has this method


    public interface ResponseListener {
        public void responseObject(JSONObject data,String type);
    }

您的LoginActivity實現了ResponseListener 在這一行: new ServerRequests.LoginUserAsyncTask(LoginActivity.this,this).execute(param); ,您將活動兩次傳遞到LoginUserAsyncTask構造函數中。 請注意,構造函數接受ContextResponseListener 您可以執行此操作,因為您的活動實現了ResponseListener

現在LoginUserAsyncTask可以在您的活動上調用responseObject方法,因為它具有作為ResponseListener的引用。 它在AsyncTaskonPostExecute方法中執行此AsyncTask 活動是一種列出任務完成時間的清單,然后調用該方法的responseObject方法。

因為AsyncTask的工作是異步完成的,所以它返回“立即消失”並執行下一條語句。

我也認為您缺少第一種方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM