android.os.NetworkOnMainThreadException - For Button Click

1k views Asked by At

I have this error of android.os.NetworkOnMainThreadException. I have read some threads that to avoid this we should do AsyncTask. However, I dont know how to do it for ButtonClick event. Below are my code...

MainActivity.java:

public class MainActivity extends ActionBarActivity {

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

        Button test = (Button) findViewById(R.id.testbutton);

        test.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    DynamoDBClient dbClient = new DynamoDBClient();

                    dbClient.DynamoDB();
                    dbClient.createTable();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

Could you guys give me a suggestion how to use AsyncTask for ButtonClick event? I have tried but failed. Thank you.

2

There are 2 answers

0
Nagaraju V On BEST ANSWER

You are doing network operations on main thread just take a thread and write onClick() code in the run method of that Thread and start that Thread in onClick() as follows

Thread t=new Thread(){
    public void run(){
        try
        {
            DynamoDBClient dbClient = new DynamoDBClient();

            dbClient.DynamoDB();
            dbClient.createTable();


        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

and in OnClick()

test.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick (View view)
        {
           t.start();
        }
      }

Hope this will helps you.

1
Kanaiya Katarmal On

This is the correct way:

public class DoYoreWork extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {

        try {
            DynamoDBClient dbClient = new DynamoDBClient();
            dbClient.DynamoDB();
            dbClient.createTable();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    protected void onPostExecute(String page) {
        // onPostExecute
    }
}

MainActivity.java

public class MainActivity extends ActionBarActivity {

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

        Button test = (Button) findViewById(R.id.testbutton);
        test.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DoYoreWork obj = new DoYoreWork();
                obj.execute();
            }
        });
    }
}