Search code examples
androidjsonhttppostrunnable

How can I post HTTP request without onClick method?


I am working about an Android Service, have a service, a receiver and an activity. My activity posts datas to web service with json. I would like to post datas automatically there. Activity is using onClick method for this. I did not find something about this. Can I use runnable method for this?

Here is Activity's onclick method:

@Override
    public void onClick(View view) {

        switch(view.getId()){
            case R.id.btnPost:
                if(!validate())
                    Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
                // call AsynTask to perform network operation on separate thread
                new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");
                break;
        }

    }

I came from here Android | Send “POST” JSON Data to Server

I made something and this is working.

 @Override
public void onResume() {
    super.onResume();

    //if(content!=null)

        if (!validate())
            Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
        // call AsynTask to perform network operation on separate thread
        new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");
       // put your code here...


}

Solution

  • You can consider onClick as an event. When the click happens (this is the event), you're posting the request. The same way you can use others system handled events (by overriding them), eg. post the request every time the app is resumed (onResume()) and so on... I hope it's a bit cleaner.