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

626

我的申请中有注册活动。它具有用户名,电子邮件,密码和手机号码的输入。我已经创建了一个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", "[email protected]");
        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的事件。谢谢你。

Earthw0rmjim

不知道我是否正确理解了您的问题,但是要执行AsyncTask,您只需创建一个实例RegisterAsyncTaskexecute()在其上调用该方法。

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

或者,如果您不需要保留实例:

new RegisterAsyncTask().execute(yourMap);

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

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

来自分类Dev

如何在Android源代码中添加Android Studio创建的应用程序?

来自分类Dev

如何在 React 应用程序中执行 Python 代码?

来自分类Dev

如何在Rails应用程序中添加Timer?

来自分类Dev

如何在闪亮的应用程序中动态添加inputText?

来自分类Dev

如何在GWT应用程序中添加静态资源?

来自分类Dev

如何在D应用程序中添加图标?

来自分类Dev

如何在整个应用程序中添加彩色胶片

来自分类Dev

如何在Android固件中添加应用程序?

来自分类Dev

如何在Shopify公共应用程序中添加JavaScript

来自分类Dev

如何在“应用程序”菜单中添加项目?

来自分类Dev

如何在QT应用程序中添加新表格

来自分类Dev

如何在Arch Linux中添加启动应用程序

来自分类Dev

如何在启动应用程序中添加PCloud?

来自分类Dev

如何在Android固件中添加应用程序?

来自分类Dev

如何在应用程序中添加App Indexing概念?

来自分类Dev

如何在 MFC 应用程序中添加文档菜单?

来自分类Dev

如何在建议的应用程序中添加应用程序以在IOS 8中自定义位置?

来自分类Dev

PHP-如何在PHP中为PHP应用程序编写代码修补程序?

来自分类Dev

如何在JNLP应用程序中修复“缺少代码库,权限和应用程序名称清单属性”?

来自分类Dev

Xamarin Android添加按钮全部大写-如何在整个应用程序中应用样式?

来自分类Dev

从 c# 应用程序添加账单时如何在 QuickBooks 中添加帐户参考

来自分类Dev

如何在Windows Phone 7应用程序开发的应用程序栏中添加超过4个图标

来自分类Dev

如何在通用应用程序中添加MAT(多语言应用程序工具包)

来自分类Dev

如何在RHEL 7的“使用其他应用程序打开”下的下拉菜单中添加应用程序

来自分类常见问题

如何在AngularJS应用程序中添加一些小的实用程序函数?

来自分类Dev

如何在WPF项目中将应用程序设置添加到安装程序中?

来自分类Dev

如何在Windows Vista / 7的“设置默认程序”列表中添加新的应用程序?

来自分类Dev

如何在Windows ARP中控制已安装的应用程序(添加或删除程序)

Related 相关文章

  1. 1

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

  2. 2

    如何在Android源代码中添加Android Studio创建的应用程序?

  3. 3

    如何在 React 应用程序中执行 Python 代码?

  4. 4

    如何在Rails应用程序中添加Timer?

  5. 5

    如何在闪亮的应用程序中动态添加inputText?

  6. 6

    如何在GWT应用程序中添加静态资源?

  7. 7

    如何在D应用程序中添加图标?

  8. 8

    如何在整个应用程序中添加彩色胶片

  9. 9

    如何在Android固件中添加应用程序?

  10. 10

    如何在Shopify公共应用程序中添加JavaScript

  11. 11

    如何在“应用程序”菜单中添加项目?

  12. 12

    如何在QT应用程序中添加新表格

  13. 13

    如何在Arch Linux中添加启动应用程序

  14. 14

    如何在启动应用程序中添加PCloud?

  15. 15

    如何在Android固件中添加应用程序?

  16. 16

    如何在应用程序中添加App Indexing概念?

  17. 17

    如何在 MFC 应用程序中添加文档菜单?

  18. 18

    如何在建议的应用程序中添加应用程序以在IOS 8中自定义位置?

  19. 19

    PHP-如何在PHP中为PHP应用程序编写代码修补程序?

  20. 20

    如何在JNLP应用程序中修复“缺少代码库,权限和应用程序名称清单属性”?

  21. 21

    Xamarin Android添加按钮全部大写-如何在整个应用程序中应用样式?

  22. 22

    从 c# 应用程序添加账单时如何在 QuickBooks 中添加帐户参考

  23. 23

    如何在Windows Phone 7应用程序开发的应用程序栏中添加超过4个图标

  24. 24

    如何在通用应用程序中添加MAT(多语言应用程序工具包)

  25. 25

    如何在RHEL 7的“使用其他应用程序打开”下的下拉菜单中添加应用程序

  26. 26

    如何在AngularJS应用程序中添加一些小的实用程序函数?

  27. 27

    如何在WPF项目中将应用程序设置添加到安装程序中?

  28. 28

    如何在Windows Vista / 7的“设置默认程序”列表中添加新的应用程序?

  29. 29

    如何在Windows ARP中控制已安装的应用程序(添加或删除程序)

热门标签

归档