0

I am trying to call AsyncTask inside handler every 1 second but I keep getting RuntimeException.Anybody knows how this could be fixed? Below is my code:

package com.example.whatsapp;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.os.Build;

public class MainActivity extends ActionBarActivity {

    Intent contacts;
    EditText t;
    int counter=0;
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        public void run() {
            new AsyncReceiveMessage().execute();
            //afficher();
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        contacts = new Intent(this, ContactsList.class);
        runnable.run();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void afficher()
    {
        counter+=1;
        System.out.println("Hello " +counter);
        handler.postDelayed(runnable, 1000);
    }

    public void registerUser(View view)
    {
        t = (EditText) findViewById(R.id.editText1);
        Button b = (Button) findViewById(R.id.button1);
        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if(t.getText().length()==11)
                {
                    Toast.makeText(getApplicationContext(), "Done", Toast.LENGTH_LONG).show();
                    contacts.putExtra("deviceNumber", t.getText().toString());
                    startActivity(contacts);
                    new AsyncRegister().execute();
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "Check you number again", Toast.LENGTH_LONG).show();
                }
            }
        });

    }

    private class AsyncRegister extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            t = (EditText) findViewById(R.id.editText1);
            ServerAPI.registerUser(t.getText().toString());
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }

    private class AsyncReceiveMessage extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            ServerAPI.receiveMessage(t.getText().toString());
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }

}
omarsafwany
  • 3,695
  • 8
  • 44
  • 75
  • Please do not dump your whole project here. Post only relevant code, and provide the stack trace. Furthermore, show the line where the Exception is thrown. – nhaarman May 06 '14 at 19:33

1 Answers1

0

You're accessing to the Main thread in doInBackground method of AsyncTask when:

@Override
protected String doInBackground(String... params) {
    ServerAPI.receiveMessage(t.getText().toString());
    return "Executed";
}

Do you get the error if you comment the first line of code within doInBackground? Avoid that and try to get those values before in onPreExecute, in doInBackgroundas paramsString parameter, or passing to the AsyncTask constructor.

GoRoS
  • 5,183
  • 2
  • 43
  • 66
  • when I comment the line, it works normaly. That line is reponsible for creating post request and fetching some data from the server. – omarsafwany May 06 '14 at 19:53
  • Well, and what happens if you just hardcode the text of the EditTextBox in that method? e.g. `ServerAPI.receiveMessage("WriteHereWhatTextBoxHas");` Does it work? – GoRoS May 06 '14 at 19:57
  • the function doesn't get called.so weird – omarsafwany May 06 '14 at 20:01
  • 1
    That might be another different problem and we don't know what ServerAPI does inside. The question you asked, can be easily solved avoiding to access to the Main thread there. Get the text of the EditTextBox before and pass it though `doInBackground(String... params)`, then use it with `ServerAPI.receiveMessage(params[0]);` – GoRoS May 06 '14 at 20:07