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

标签 java android android-asynctask

我的应用程序中有一个注册 Activity 。输入用户名、电子邮件、密码和手机号码。我已经创建了一个用户界面。

代码:

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 与服务器同步。

为此,我在另一个 Activity 中创建了 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", "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86f3f5e3f4b7c6e1ebe7efeaa8e5e9eb" rel="noreferrer noopener nofollow">[email protected]</a>");
        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 的事件。谢谢。

最佳答案

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

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

或者,如果您不需要获取实例:

new RegisterAsyncTask().execute(yourMap);

关于java - 如何在应用程序中添加asyncTask代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37762241/

相关文章:

java - 来自另一个类的 Android Interface 类显示空指针异常

java - Hibernate的SequenceStyleGenerator生成序列下面得到的序列值

java - 插入时删除重复值

Android ImageView ,图像在左上角被截断,如何避免 id?

Android动画在重复后停止工作

javascript - Android - Webview Javascript 调用特定 DIV 类的函数

java - 当互联网连接失败时,AsyncTask doInBackground 返回空指针异常

java - 设置点击按钮时显示广告

java - 用于运行最新版本文件的 Bash 脚本?

android - 在 Android 中的 UI 线程操作期间显示 ProgressDialog