How to fix "android.view.ViewRootImpl$CalledFromWrongThreadException" - android

I want to fix error as follows:
"android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views."
here are my code.
public class MainActivity extends Activity {
#SuppressLint("NewApi") #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
onShowMessage();
}
public void removeContent() {
LinearLayout list = (LinearLayout) findViewById(R.id.linearlayout_list);
list.removeAllViews();
}
public void onShowMessage() {
Thread myThread = new Thread(new Runnable() {
#Override
public void run() {
String id = "id1";
String message = "message1";
String response = HTTPUtils.HTTPPost(Global.MESSAGE_URL,
"id", id,
"message", message);
process(response);
}
});
myThread.start();
}
private void process(String response) {
if (response == null || response.equals("")) {
return;
} else {
try {
JSONObject json = null;
try {
json = FbUtil.parseJson(response);
} catch (FacebookError e) {
showErrorMessage();
}
if (json.has("exception")) {
showErrorMessage();
return;
} else {
Global.list = JsonParser.getInfo(json);
removeContent();
initView();
return;
}
} catch (JSONException e) {
}
return;
}
}
}
error occur on removeContent();
please help me.

You are updating Views in a different thread
removeContent();
initView();
Call this two methods in a UI thread like.
runOnUiThread(new Runnable() {
#Override
public void run() {
removeContent();
initView();
}
});

Related

Solved: Android socket is not getting connected to the server

Here I have a query related to connection between android socket and server. I'm following https://socket.io/blog/native-socket-io-and-android/ and found that it is working fine, so I replaced my local server URL with the URL in the tutorial. But here I'm always getting a connection failed or disconnection error. Here is my application class for further clarification.
public class ChatApplication extends Application {
private Socket mSocket;
{
try {
IO.Options options = new IO.Options();
options.forceNew = true;
options.reconnection = true;
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("uid", 1);
jsonObject.put("usid", 6847);
options.query = jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("JSON", jsonObject.toString());
Log.e("OPTIONS", options.toString());
mSocket = IO.socket(Constants.CHAT_SERVER_URL, options);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public Socket getSocket() {
return mSocket;
}
}
And the code of the fragment is below. It keeps calling onDisconnect() whenever I use my local server for it.
public class MainFragment extends Fragment {
private static final String TAG = "MainFragment";
private static final int REQUEST_LOGIN = 0;
private static final int TYPING_TIMER_LENGTH = 600;
private RecyclerView mMessagesView;
private EditText mInputMessageView;
private List<Message> mMessages = new ArrayList<Message>();
private RecyclerView.Adapter mAdapter;
private boolean mTyping = false;
private Handler mTypingHandler = new Handler();
private String mUsername;
private Socket mSocket;
private Boolean isConnected = true;
private Emitter.Listener onConnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if (!isConnected) {
if (null != mUsername)
mSocket.emit("add user", mUsername);
Toast.makeText(getActivity().getApplicationContext(),
R.string.connect, Toast.LENGTH_LONG).show();
isConnected = true;
}
}
});
}
};
private Emitter.Listener onDisconnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Log.i(TAG, "diconnected");
isConnected = false;
Toast.makeText(getActivity().getApplicationContext(),
R.string.disconnect, Toast.LENGTH_LONG).show();
}
});
}
};
private Emitter.Listener onConnectError = new Emitter.Listener() {
#Override
public void call(Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e(TAG, "Error connecting");
Toast.makeText(getActivity().getApplicationContext(),
R.string.error_connect, Toast.LENGTH_LONG).show();
}
});
}
};
private Emitter.Listener onNewMessage = new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String username;
String message;
try {
username = data.getString("username");
message = data.getString("message");
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
return;
}
removeTyping(username);
addMessage(username, message);
}
});
}
};
private Emitter.Listener onUserJoined = new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String username;
int numUsers;
try {
username = data.getString("username");
numUsers = data.getInt("numUsers");
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
return;
}
addLog(getResources().getString(R.string.message_user_joined, username));
addParticipantsLog(numUsers);
}
});
}
};
private Emitter.Listener onUserLeft = new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String username;
int numUsers;
try {
username = data.getString("username");
numUsers = data.getInt("numUsers");
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
return;
}
addLog(getResources().getString(R.string.message_user_left, username));
addParticipantsLog(numUsers);
removeTyping(username);
}
});
}
};
private Emitter.Listener onTyping = new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String username;
try {
username = data.getString("username");
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
return;
}
addTyping(username);
}
});
}
};
private Emitter.Listener onStopTyping = new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String username;
try {
username = data.getString("username");
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
return;
}
removeTyping(username);
}
});
}
};
private Runnable onTypingTimeout = new Runnable() {
#Override
public void run() {
if (!mTyping) return;
mTyping = false;
mSocket.emit("stop typing");
}
};
public MainFragment() {
super();
}
// This event fires 1st, before creation of fragment or any views
// The onAttach method is called when the Fragment instance is associated with an Activity.
// This does not mean the Activity is fully initialized.
#Override
public void onAttach(Context context) {
super.onAttach(context);
mAdapter = new MessageAdapter(context, mMessages);
if (context instanceof Activity) {
//this.listener = (MainActivity) context;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
ChatApplication app = (ChatApplication) getActivity().getApplication();
mSocket = app.getSocket();
mSocket.on(Socket.EVENT_CONNECT, onConnect);
mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.on("new message", onNewMessage);
mSocket.on("user joined", onUserJoined);
mSocket.on("user left", onUserLeft);
mSocket.on("typing", onTyping);
mSocket.on("stop typing", onStopTyping);
mSocket.connect();
startSignIn();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onDestroy() {
super.onDestroy();
mSocket.disconnect();
mSocket.off(Socket.EVENT_CONNECT, onConnect);
mSocket.off(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.off("new message", onNewMessage);
mSocket.off("user joined", onUserJoined);
mSocket.off("user left", onUserLeft);
mSocket.off("typing", onTyping);
mSocket.off("stop typing", onStopTyping);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMessagesView = (RecyclerView) view.findViewById(R.id.messages);
mMessagesView.setLayoutManager(new LinearLayoutManager(getActivity()));
mMessagesView.setAdapter(mAdapter);
mInputMessageView = (EditText) view.findViewById(R.id.message_input);
mInputMessageView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int id, KeyEvent event) {
if (id == R.id.send || id == EditorInfo.IME_NULL) {
attemptSend();
return true;
}
return false;
}
});
mInputMessageView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (null == mUsername) return;
if (!mSocket.connected()) return;
if (!mTyping) {
mTyping = true;
mSocket.emit("typing");
}
mTypingHandler.removeCallbacks(onTypingTimeout);
mTypingHandler.postDelayed(onTypingTimeout, TYPING_TIMER_LENGTH);
}
#Override
public void afterTextChanged(Editable s) {
}
});
ImageButton sendButton = (ImageButton) view.findViewById(R.id.send_button);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
attemptSend();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Activity.RESULT_OK != resultCode) {
getActivity().finish();
return;
}
mUsername = data.getStringExtra("username");
int numUsers = data.getIntExtra("numUsers", 1);
addLog(getResources().getString(R.string.message_welcome));
addParticipantsLog(numUsers);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.menu_main, menu);
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_leave) {
leave();
return true;
}
return super.onOptionsItemSelected(item);
}
private void addLog(String message) {
mMessages.add(new Message.Builder(Message.TYPE_LOG)
.message(message).build());
mAdapter.notifyItemInserted(mMessages.size() - 1);
scrollToBottom();
}
private void addParticipantsLog(int numUsers) {
addLog(getResources().getQuantityString(R.plurals.message_participants, numUsers, numUsers));
}
private void addMessage(String username, String message) {
mMessages.add(new Message.Builder(Message.TYPE_MESSAGE)
.username(username).message(message).build());
mAdapter.notifyItemInserted(mMessages.size() - 1);
scrollToBottom();
}
private void addTyping(String username) {
mMessages.add(new Message.Builder(Message.TYPE_ACTION)
.username(username).build());
mAdapter.notifyItemInserted(mMessages.size() - 1);
scrollToBottom();
}
private void removeTyping(String username) {
for (int i = mMessages.size() - 1; i >= 0; i--) {
Message message = mMessages.get(i);
if (message.getType() == Message.TYPE_ACTION && message.getUsername().equals(username)) {
mMessages.remove(i);
mAdapter.notifyItemRemoved(i);
}
}
}
private void attemptSend() {
if (null == mUsername) return;
if (!mSocket.connected()) return;
mTyping = false;
String message = mInputMessageView.getText().toString().trim();
if (TextUtils.isEmpty(message)) {
mInputMessageView.requestFocus();
return;
}
mInputMessageView.setText("");
addMessage(mUsername, message);
// perform the sending message attempt.
mSocket.emit("new message", message);
}
private void startSignIn() {
// mUsername = null;
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivityForResult(intent, REQUEST_LOGIN);
}
private void leave() {
mUsername = null;
mSocket.disconnect();
mSocket.connect();
startSignIn();
}
private void scrollToBottom() {
mMessagesView.scrollToPosition(mAdapter.getItemCount() - 1);
}
}
I'm using CHAT_SERVER_URL = "http://192.168.1.14:3000/" to make connection with server but it's not working for me. It works fine when we try to make a web connection through emulator or computer system. Can anyone please give me an idea if I'm doing anything wrong.
Thanks.
After debugging at the server end too, I got to know how to hit my server to make a connection and I got that we don't require IO.Options and Options.query in every case and now it is working fine completely. So for more clarification I'm posting an answer here:
//connect to server
public void startRunning() {
try {
if (baseUrl != null) {
socket = IO.socket("http://" + baseUrl + ":3000?uid=" + userId + "&usid=" + userSessionId);
}
} catch (URISyntaxException e) {
e.printStackTrace();
}
if (socket == null) return;
socket
.on(Socket.EVENT_CONNECT, CONNECTED)
.on(Socket.EVENT_DISCONNECT, DISCONNECTED)
.on("chat-message", CHAT_MESSAGE)
.on("chats-active", CHATS_ACTIVE)
.on("chat-logout", LOGOUT)
.on("messages-read", MESSAGE_READ)
.on("chat-login", CHAT_LOGIN);
socket.connect();
}

Dialog does not show via AsyncTask

I have a custom progress dialog that seems to work everywhere except here in my code:
My login activity (relevant snippets):
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
context = this;
pd = AUtils.getProgressDialog(context, false);
UserExistsAuthenticateAndRoute = getIntent().getBooleanExtra("UserExistsAuthenticateAndRoute", false);
RouteToActivity = getIntent().getStringExtra("RouteToActivity");
//make sure there is no token in APrefs in memory during login
APrefs pref = new APrefs();
if (pref != null) {
pref.putNMToken(null);
pref.putNMRefreshToken(null);
}
ClickableSpan span = new ClickableSpan() {
#Override
public void onClick(View widget) {
}
};
setActionBar();
initUi();
mToolbarTitle.setText("Log In");
} catch (Exception exc) {
exc.printStackTrace();
}
}
#Override
protected Void doInBackground(Void... voids) {
GDDataManager.get().login(GDUser, new DataCallBack() {
#Override
public void update(DataUpdate update) {
if (update.code == 0) {
final GDUser _gdUser = pref.getMember();
//call get status
if (_gdUser != null) {
Log.i(TAG, "getUserStatus()");
GDDataManager.get().getUserStatus(_gdUser, new DataCallBack() {
#Override
public void update(DataUpdate update) {
if (update.code == 0) {
setGdUserStatus((GDUserStatus) update.data);
loginController(getGdUserStatus(), _gdUser);
} else {
Log.e(TAG, "getUserStatus(), error response msg " + update.message);
if (update.message.contains("error")) {
App.toast(getString(R.string.general_server_error_message));
}
}
}
});
}
} else {
Log.e(TAG, "update message:" + update.message);
if (update.message.contains("error")) {
App.toast(getString(R.string.general_server_error_message));
} else if (update.message.contains("could not verify password")) {
App.toast(getString(R.string.could_not_verify_password));
} else if (update.message.contains("no user found")) {
App.toast(getString(R.string.no_user_found));
} else {
App.toast(update.message);
}
if (btnLogIn != null) {
//disable is valid in order to prevent double click
btnLogIn.setEnabled(false);
btnLogIn.setTextColor(ContextCompat.getColor(context, R.color.colorGrey));
}
edtEmail.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(context, R.drawable.cross_icon), null);
edtEmail.setBackground(ContextCompat.getDrawable(context, R.drawable.textfield_red));
edtPassword.setBackground(ContextCompat.getDrawable(context, R.drawable.textfield_red));
}
}//end update getUserStatus
}
);
return null;
}
};
try {
tryLoginTask.execute();
} catch (Exception exc) {
Log.d(TAG, exc.getMessage());
exc.printStackTrace();
//cancel task on exception , DISMISS DIALOG to avoid locking screen
tryLoginTask.cancel(true);
}
}//end tryLogin()
The static code from utility class, were the dialog is returned (relevant snippet):
public static Dialog getProgressDialog(Context c, boolean isCancelable) {
Dialog pd = new Dialog(c,c.getApplicationInfo().theme);
pd.setCanceledOnTouchOutside(isCancelable);
pd.requestWindowFeature (Window.FEATURE_NO_TITLE);
pd.setContentView (R.layout.progress_dialog);
pd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(150,0,0,0)));
return pd;
}
Im not seeing any errors, exceptions, and the dialog is showiong in other places using the same approach. Sometimes I see it for fraction of a second however the task hasn't completed.
Any suggestions.
Thanks
AlertDialogs are foreground things. You should show your Dialogs in your UI thread. So if you want to show your Dialog in an AsyncTask you should approach with runOnUiThread:
runOnUiThread(new Runnable() {
#Override
public void run() {
// Show your dialog here
}
});
Documentations:
https://developer.android.com/reference/android/os/AsyncTask.html
https://developer.android.com/guide/components/processes-and-threads.html

Get information of object in mainactivity from class

I would like to use the information of 'result' in the XMLRPCMethod. When the thread is finished the correct data is in the result object.
This is a code snipped from my OpenerpRPC.java class.
class XMLRPCMethod extends Thread {
private String method;
private Object[] params;
private Handler handler;
public Object result;
private OpenerpRpc callBack;
public XMLRPCMethod(String method, OpenerpRpc callBack) {
this.method = method;
this.callBack = callBack;
handler = new Handler();
}
public void call() {
call(null);
}
public void call(Object[] params) {;
this.params = params;
start();
}
#Override
public void run() {
try {
result = client.callEx(method, params);
handler.post(new Runnable() {
public void run() {
try {
callBack.resultcall(result);
} catch (XMLRPCException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} catch (final XMLRPCFault e) {
handler.post(new Runnable() {
public void run() {
Log.d("Test", "error", e);
}
});
} catch (final XMLRPCException e) {
handler.post(new Runnable() {
public void run() {
Throwable couse = e.getCause();
if (couse instanceof HttpHostConnectException) {
Log.d(TAG, "error"+uri.getHost());
} else {
Log.d("Test", "error", e);
}
Log.d("Test", "error", e);
}
});
}
}
}
My result call in the OpenerpRpc class looks like:
public void resultcall(Object result) throws XMLRPCException{
allres=result;
if (rtype.equals("login")){
//Isn't impossible cast the result var with (String) because cause crash..why?
userid=""+result;
}
if (rtype.equals("read")){
//Isn't impossible cast the result var with (String) because cause crash..why?
// userid=""+result;
}
// name of callback function to use in parent class (MainActivity) for receive data
this.parent.oerpcRec(rtype,allres);
}
This is how i can receive the data in mainactivity
#SuppressWarnings("unchecked")
public void oerpcRec(String rtype,Object res) throws XMLRPCException{
if (rtype=="login"){
connector.setModel("res.users");
Object[] Ids = {Integer.parseInt(connector.userid)};
// set here the fields you wont loads
Object[] values={"name"};
connector.Read(Ids,values);
}
if(rtype=="read"){
Object[] ret=(Object[])res;
Map<String, Object> map1 = (Map<String, Object>) ret[0];
if(ret.length > 1){
}
}
}
But how can i get this information in my mainactivity? I only get the information of the login id value. When I put a breakpoint in the thread it only goes to the function resultcall when I try to login.
...
public void onClick(View v) {
try {
//here set user and pass for login
connector.Login(USER,PASS);
Object[] ids = {31,30,28,26};
Object[] params ={"partner_id","tax_line","section_id","invoice_line"};
connector.Read(ids,params);
//get information of openERP for specific id's
} catch (XMLRPCException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Use an interface
public interface MyListener {
public void callback(Object result);
}
Your MainActivity must implement the interface
public class MyActivity extends Activity implements MyListener {
...
...
...
#override
public void callback(Object result) {
// getting the result value.
}
}
So when your thread finish, execute the callback() method:
MyListener ml;
ml.callback(result);
and the callback() method of you MainActivity will receive the object.

AsyncTask, doInBackground doesn't seem to work

I have that AsyncTask code
public class DiceTask extends AsyncTask<Socket, Void, int[]> {
private int[] arrayFromServer = new int[8];
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected int[] doInBackground(Socket...params) {
Socket soc = params[0];
try {
ObjectInputStream ois = new ObjectInputStream(soc.getInputStream());
int[] tempArray = (int[]) (ois.readObject());
return tempArray;
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
#Override
protected void onProgressUpdate(Void...arg1) {
}
#Override
protected void onPostExecute(int[] result) {
arrayFromServer = result;
}
public int[] getTempDice() {
return arrayFromServer;
}
}
where is called this way into my main thread.
rollDiceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rollDiceButton.setEnabled(false);
rollDice();
task.execute(socket);
tempArray = task.getTempDice();
printDice(tempArray,pDice);
clickableDice(pDice);
}
});
where I am getting a null tempArray. If I change my onPreExecute to this
#Override
protected void onPreExecute() {
super.onPreExecute();
for(int i = 0; i < arrayFromServer.length; i++) {
arrayFromServer[i] = 1;
}
}
I am getting my dice as it should, all are one. The code I am running into the rollDice() is this
public void rollDice() {
try {
DataOutputStream sout = new DataOutputStream(socket.getOutputStream());
String line = "dice";
PrintStream out = new PrintStream(sout);
out.println(line);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
and I can see the results in the server.
You don't need to implement onPostExecute in your AsyncTask class definition. You also don't need the getTempDice function. You just need to override onPostExecute in an anonymous class and run your UI code in it.
rollDiceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rollDiceButton.setEnabled(false);
rollDice();
task = new DiceTask() {
#Override
public void onPostExecute(int[] result) {
tempArray = result;
printDice(tempArray,pDice);
clickableDice(pDice);
}
}.execute(socket);
}
});
Children of AsyncTask run in parallel with main Thread, you are trying access the attribute arrayFromServer right after to start the Thread. It's recommended you use a callback to retried the value wanted, making sure you get the value after Thread is done.
Making the follow changes can solve your problem. Let me know if you understand.
public class DiceTask extends AsyncTask<Socket, Void, int[]> {
public interface Callback {
void onDone(int[] arrayFromServer);
}
private Callback mCallback;
public DiceTask(Callback c) {
mCallback = c;
}
#Override
protected int[] doInBackground(Socket...params) {
Socket soc = params[0];
try {
ObjectInputStream ois = new ObjectInputStream(soc.getInputStream());
int[] tempArray = (int[]) (ois.readObject());
return tempArray;
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(int[] result) {
mCallback.onDone(result);
}
}
rollDiceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rollDiceButton.setEnabled(false);
rollDice();
new DiceTask(new Callback() {
public void onDone(int[] tempArray) {
printDice(tempArray,pDice);
clickableDice(pDice);
}
}).execute(socket);
}
});

AsyncTask onPostExecute() not called in Unit Test Case

I've seen a bunch of posts related to this, but none seem to have the same issue I'm getting. GetBusinessRulesTask extends AsyncTask. When I execute this in a unit test case the onPostExecute() never gets called. However, if I use the real client code then onPostExecute() is called everytime. Not sure what I'm doing wrong here.
Test Case:
package com.x.android.test.api;
import java.util.concurrent.CountDownLatch;
import android.test.ActivityInstrumentationTestCase2;
import android.test.UiThreadTest;
import android.widget.Button;
import com.x.android.api.domain.businessrule.BusinessRules;
import com.x.android.api.exception.NetworkConnectionException;
import com.x.android.api.tasks.GetBusinessRulesTask;
import com.x.android.test.activity.SimpleActivity;
public class GetBusinessRulesTaskTest
extends
ActivityInstrumentationTestCase2<SimpleActivity> {
SimpleActivity mActivity;
Button mButton;
public GetBusinessRulesTaskTest() {
super("com.x.android.test.activity", SimpleActivity.class);
}
#Override
protected void setUp() throws Exception {
super.setUp();
mActivity = this.getActivity();
mButton = (Button) mActivity
.findViewById(com.x.android.test.activity.R.id.b1);
}
public void testPreconditions() {
assertNotNull(mButton);
}
#UiThreadTest
public void testCallBack() throws Throwable {
final CountDownLatch signal = new CountDownLatch(1);
final GetBusinessRulesTask task = (GetBusinessRulesTask) new GetBusinessRulesTask(
new GetBusinessRulesTask.Receiver<BusinessRules>() {
#Override
public void onReceiveResult(BusinessRules rules, Exception e) {
assertNotNull(rules);
assertNull(e);
signal.countDown();// notify the count down latch
}
});
task.start(mActivity.getApplicationContext());
try {
signal.await();// wait for callback
} catch (InterruptedException e1) {
fail();
e1.printStackTrace();
}
}
}
OnPostExecute:
#Override
protected void onPostExecute(AsyncTaskResponse<O> response) {
Log.d(TAG, "onPostExecuted");
if (mReceiver != null) {
mReceiver.onReceiveResult(response.getResponse(), response.getException());
}
}
DoInBackground:
#Override
protected AsyncTaskResponse<O> doInBackground(I... params) {
Log.d(TAG, "doInBackgroundr");
try {
Uri uri = createUri(params);
mBaseRequest = new GetLegacyRequest(uri);
String json = mBaseRequest.executeRequest();
O response = deserializeJson(json);
Log.d(TAG, "Returning AsyncTaskResponse");
return new AsyncTaskResponse<O>(response, null);
} catch (Exception e) {
Log.e(TAG, "Error", e);
/*
AsyncTaskResponse<O> maintenance = ReadBusinessControlledPropertiesTask.blockingCall(mServiceLocatorUrl);
if(maintenance.getException() == null) {
MaintenanceException mExcep = new MaintenanceException( maintenance.getResponse());
if (mExcep.isUnderMaintenance())
return new AsyncTaskResponse(null,mExcep);
}*/
return new AsyncTaskResponse<O>(null, e);
}
}
Start method()
public AsyncTask<Void, Void, AsyncTaskResponse<BusinessRules>> start(
Context context) throws NetworkConnectionException {
super.start(context);
Log.d(TAG, "start");
return execute();
}
FOUND THE ISSUE. Don't make your AsyncTask final and put it inside the runnable.
The fix:
public void testCallBack() throws Throwable {
final CountDownLatch signal = new CountDownLatch(1);
// Execute the async task on the UI thread! THIS IS KEY!
runTestOnUiThread(new Runnable() {
#Override
public void run() {
try {
GetBusinessRulesTask task = (GetBusinessRulesTask)new GetBusinessRulesTask(new GetBusinessRulesTask.Receiver<BusinessRules>() {
#Override
public void onReceiveResult(
BusinessRules rules, Exception e) {
assertNotNull(rules);
assertNull(e);
signal.countDown();// notify the count downlatch
}
});
task.start(mActivity.getApplicationContext());
} catch (Exception e) {
Log.e(TAG, "ERROR", e);
fail();
}
}
});
try {
signal.await();// wait for callback
} catch (InterruptedException e1) {
fail();
e1.printStackTrace();
}
}
FOUND THE ISSUE. Don't make your AsyncTask final and put it inside the runnable.
The fix:
public void testCallBack() throws Throwable {
final CountDownLatch signal = new CountDownLatch(1);
// Execute the async task on the UI thread! THIS IS KEY!
runTestOnUiThread(new Runnable() {
#Override
public void run() {
try {
GetBusinessRulesTask task = (GetBusinessRulesTask)new GetBusinessRulesTask(new GetBusinessRulesTask.Receiver<BusinessRules>() {
#Override
public void onReceiveResult(
BusinessRules rules, Exception e) {
assertNotNull(rules);
assertNull(e);
signal.countDown();// notify the count downlatch
}
});
task.start(mActivity.getApplicationContext());
} catch (Exception e) {
Log.e(TAG, "ERROR", e);
fail();
}
}
});
try {
signal.await();// wait for callback
} catch (InterruptedException e1) {
fail();
e1.printStackTrace();
}
}

Categories

Resources