Search code examples
javaandroidnetworkonmainthread

android.os.NetworkOnMainThreadException - For Button Click


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.


Solution

  • 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.