2016-06-11 3 views
2

신청서에 등록 활동이 있습니다. 이것은 사용자 ID, 전자 메일, 암호 및 모바일 번호의 입력이 있습니다. UI를 만들었습니다.응용 프로그램에 asyncTask 코드를 추가하는 방법은 무엇입니까?

코드 :

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를 이벤트를 보여주고 싶어요. 고맙습니다.

답변

3

질문을 올바르게 이해하고 있지만 AsyncTask을 실행하려면 RegisterAsyncTask의 인스턴스를 만들고 execute() 메서드를 호출해야합니다.

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

또는 인스턴스의 연락을 취하는 얻을 필요가없는 경우 :

new RegisterAsyncTask().execute(yourMap); 
0

당신은 단순히 당신의 로그인 활동 코드에 AsyncTask를 alongwith 당신의 해시 맵 객체를 넣어 간단하게 호출 할 수 있습니다 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", "[email protected]"); 
     params.put("userMobileNo", "9696323252"); 
     params.put("userPhoto", userPhoto); 


//call asynctask like this. 
RegisterAsyncTask task = new RegisterAsyncTask(); 
     task.execute(params); 
관련 문제