如何在应用程序中添加asyncTask代码?

时间:2016-06-11 09:44:31

标签: java android android-asynctask

我的申请表中有注册活动。这有用户ID,电子邮件,密码和手机号码的输入。我创建了一个UI。

代码:

public class RegisterActivity extends AppCompatActivity {

    TextView already;
    Button signUp;
    RelativeLayout parent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        parent = (RelativeLayout)findViewById(R.id.parentPanel);

        setupUI(parent);

        already = (TextView)findViewById(R.id.alreadyRegistered);
        signUp = (Button) findViewById(R.id.sign_up_button);

        already.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startActivity(new Intent(RegisterActivity.this,LoginActivity.class));

            }
        });


        signUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startActivity(new Intent(RegisterActivity.this,LoginActivity.class));

            }
        });


    }
    public static void hideSoftKeyboard(Activity activity) {
        InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
    }
    public void setupUI(View view) {

        //Set up touch listener for non-text box views to hide keyboard.
        if(!(view instanceof EditText)) {

            view.setOnTouchListener(new View.OnTouchListener() {

                public boolean onTouch(View v, MotionEvent event) {
                    hideSoftKeyboard(RegisterActivity.this);
                    return false;
                }

            });
        }

        //If a layout container, iterate over children and seed recursion.
        if (view instanceof ViewGroup) {

            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {

                View innerView = ((ViewGroup) view).getChildAt(i);

                setupUI(innerView);
            }
        }
    }
}

现在我想将此UI与服务器同步。

为此,我在另一个活动中创建了一个asyncTask代码。如何调用此代码或使用UI实现此代码?

AsyncTask代码:RegisterActivity

public class RegisterActivity extends AppCompatActivity {
    Context context;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        context = this;

        RegisterAsyncTask task = new RegisterAsyncTask();
        String userPhoto = "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlwSFlLBAIHAGdIMrN7hH1jKkmZz+d7MPu15md6PtCyrHmqvsgNVjY7Djh69OgwEaU1pkVwanKK0NLSsgvA8Vk=";

        HashMap<String, String> params = new HashMap<String, String>();
        params.put("userUsername", "user1");
        params.put("userPassword", "user1");
        params.put("gender", "M");
        params.put("birthDate", "1986/7/12");
        params.put("religion", "Hindu");
        params.put("nationality", "Indian");
        params.put("motherTongue", "Marathi");
        params.put("birthPlace", "Pune");
        params.put("userCountry", "India");
        params.put("userState", "Maharashtra");
        params.put("userCity", "Nashik");
        params.put("userPincode", "422101");
        params.put("userEmailid", "user1@gmail.com");
        params.put("userMobileNo", "9696323252");
        params.put("userPhoto", userPhoto);
    }
   public class RegisterAsyncTask extends AsyncTask<Map<String, String>, Void, JSONObject>{
       @Override
       protected JSONObject doInBackground(Map<String, String>... params) {
           try {
               String api = context.getResources().getString(R.string.server_url) + "api/user/register.php";
               Map2JSON mjs = new Map2JSON();
               JSONObject jsonParams = mjs.getJSON(params[0]);
               ServerRequest request = new ServerRequest(api, jsonParams);
               return request.sendRequest();
           } catch(JSONException je) {
               return Excpetion2JSON.getJSON(je);
           }
       }

       @Override
       protected void onPostExecute(JSONObject jsonObject) {
           super.onPostExecute(jsonObject);

           Log.d("ServerResponse", jsonObject.toString());
           try {
               int result = jsonObject.getInt("result");
               String message = jsonObject.getString("message");
               if ( result == 1 ) {
                   Toast.makeText(context, message, Toast.LENGTH_LONG).show();
                   //Code for having successful result for register api goes here
               } else {
                   Toast.makeText(context, message, Toast.LENGTH_LONG).show();
                   //Code when api fails goes here
               }

           } catch(JSONException je) {
               je.printStackTrace();
               Toast.makeText(context, je.getMessage(), Toast.LENGTH_LONG).show();
           }
       }
   }
}

我该如何同步?请帮忙。谢谢。

编辑:

getEventsAsyncTask:

public class GetEventsAsyncTask extends AsyncTask<Void, Void, JSONObject> {
    String api;
    private Context context;

    public GetEventsAsyncTask(Context context) {
        this.context = context;
    }


    @Override
    protected JSONObject doInBackground(Void... params) {
        try {
            api = context.getResources().getString(R.string.server_url) + "api/event/getEvents.php";
            ServerRequest request = new ServerRequest(api);
            return request.sendGetRequest();
        } catch(Exception e) {
            return Excpetion2JSON.getJSON(e);
        }
        }  //end of doInBackground

        @Override
        protected void onPostExecute(JSONObject response) {
            super.onPostExecute(response);
            Log.e("ServerResponse", response.toString());
            try {
                int result = response.getInt("result");
                String message = response.getString("message");
                if (result == 1 ) {
                    Toast.makeText(context, message, Toast.LENGTH_LONG).show();
                    //code after getting profile details goes here
                } else {
                    Toast.makeText(context, message, Toast.LENGTH_LONG).show();
                    //code after failed getting profile details goes here
                }
            } catch(JSONException je) {
                je.printStackTrace();
                Toast.makeText(context, je.getMessage(), Toast.LENGTH_LONG).show();
            }
        } //end of onPostExecute
}

对话框:

    @Override
    protected Dialog onCreateDialog(int id) {

        Dialog dialog = null;
        String[] listContent = {"Wedding",
        "Anniversary",
        "Naming Ceremony/Baptism",
        "Thread Ceremony",
        "Engagement",
        "Birthday",
        "Friends and Family Meet",
        "Funeral",
        "Movie",
        "Play"};

        switch(id) {
            case CUSTOM_DIALOG_ID:
                dialog = new Dialog(PlanEventActivity.this);
                dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                dialog.setContentView(R.layout.choose_event_dialog);
                dialog.setCancelable(true);
                dialog.setCanceledOnTouchOutside(true);
                dialog.setOnCancelListener(new DialogInterface.OnCancelListener(){

                    @Override
                    public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub

                    }});

                dialog.setOnDismissListener(new DialogInterface.OnDismissListener(){

                    @Override
                    public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub

                    }});

//Prepare ListView in dialog
                dialog_ListView = (ListView)dialog.findViewById(R.id.dialoglist);
                ArrayAdapter<String> adapter
                        = new ArrayAdapter<String>(this,
                        android.R.layout.simple_list_item_1, listContent);
                dialog_ListView.setAdapter(adapter);
                dialog_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {

                        chooseEventText.setText(parent.getItemAtPosition(position).toString());

                        dismissDialog(CUSTOM_DIALOG_ID);
                    }});

                break;
        }

        return dialog;
    }

在此对话框中想要显示来自asyncTask的事件。谢谢。

2 个答案:

答案 0 :(得分:3)

不确定我是否正确理解您的问题,但要执行AsyncTask,您只需要创建RegisterAsyncTask的实例并在其上调用execute()方法。

RegisterAsyncTask task = new RegisterAsyncTask();
task.execute(yourMap);
// you can pass multiple params to the execute() method

或者,如果您不需要获得该实例的支持:

new RegisterAsyncTask().execute(yourMap);

答案 1 :(得分:0)

您只需将您的hashmap对象与AsyncTask一起放入登录活动代码中,然后按以下方式调用AsyncTask。

HashMap<String, String> params = new HashMap<String, String>();
        params.put("userUsername", "user1");
        params.put("userPassword", "user1");
        params.put("gender", "M");
        params.put("birthDate", "1986/7/12");
        params.put("religion", "Hindu");
        params.put("nationality", "Indian");
        params.put("motherTongue", "Marathi");
        params.put("birthPlace", "Pune");
        params.put("userCountry", "India");
        params.put("userState", "Maharashtra");
        params.put("userCity", "Nashik");
        params.put("userPincode", "422101");
        params.put("userEmailid", "user1@gmail.com");
        params.put("userMobileNo", "9696323252");
        params.put("userPhoto", userPhoto);


//call asynctask like this.
RegisterAsyncTask task = new RegisterAsyncTask();
        task.execute(params);