check if a method was called on UI-Thread with robolectric [closed] - android

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Anyone here knows how to write a test ( or ideally has an example for this ) to check if a method was called on the UI-Thread?

Answer refered from the following links :
How to check if current thread is not main thread
How to know if this thread is a UI Thread
1) Looper.myLooper() == Looper.getMainLooper()
2) Android app has only one UI thread, so you could somewhere in the Activity callback like onCreate() check and store its ID and later just compare that thread's ID to the stored one.
mMainThreadId = Thread.currentThread().getId();
3) if you want to do something on the UI thread and have any reference to Activity by using
mActivity.runOnUiThread( new Runnable() {
#Override
public void run() {
...
}
});
Hope it helps

UI thread always have id = 1, so you can try to check:
if(Thread.currentThread().getId() == 1) {
///...
}

Related

Future String in flutter [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
So I have a function that returns a value that is of future. When this function executes I want to extract the string from the future. How should I do this?
Future<String> coverImage(id, space) {
String link = 'https://cdn.contentful.com/spaces/$space/assets/$id?access_token=1d4932ce2b24458e85ded26532bb81184e0d79c1a16c5713ec3ad391c2e8f5b3';
return http.get(link).then((response) => decodeToImage(decodeJson(response.body)));
}
this function return Future<String>, i want to extract to string when i am using with image widget
Future someMethod() async {
String s = await someFuncThatReturnsFuture();
}
or
someMethod() {
someFuncTahtReturnsFuture().then((s) {
print(s);
});
}
There is no way to go from async (Future) to sync execution.
async/await is only syntactic sugar to make the code look more like sync code, but as you see in my first example, someMethod will return a Future and if you want to use the string s on the call site, you have to use async/await or then() there.

Android Event Bus Alternative [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Context: In a previous Android application I have developed, I used an event bus (otto by Square) to handle async task results (for example: the result of a server request is posted on the bus and somewhere in the application I intercept that response). Although it did the job, in some article I've read it was mentioned that using such a bus is rather a bad idea as it's considered an antipattern.
Why is that so? What are some alternatives to using an event bus when dealing with results of async operations? I know that, most of the time, there is no standard way to handle things, but is there "a more canonical" method?
Use RxJava and Retrofit for asynchronous network calls. RxJava provide out of the box support for Retrofit.
Return Observable from retrofit interface.
#GET("/posts/{id}")
public Observable<Post> getData(#Path("id") int postId);
Use it in your activity class -
retrofitBuilderClass.getApi()
.getData()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer < List < Data >> () {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(List < Data > data) {
// Display data
}
});

Want to send data to another activity on getting data [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have an activity in which i am getting some value in string and i want to send that data to another activity. The data that i want to send changes frequently after calling some method. So i want to send updated data into another activity. My data will be updated anytime no matter whether i am on that activity or not. My code
if (event.equals("gameRequstinvitaion")) {
try {
socket.emit("gameRequstinvitaion", jsonObject);
gamerequest = jsonObject.toString();
Log.e("TAG", "gamereq" + gamerequest);
}
}
My gamerequest will be updated anytime so i want to send updated data to another activity. Is it possible?PleASE HELP ME OUT
Use Handler to send data to another activity
public static Handler handler;
handler=new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg1) {
//-- retreiving data
String data=msg.obj.toString();
return false;
}
});
Now pass data from activity 1
Message msg=new Message();
msg.obj="Test Message";//Pass any type of value
Activity2.handler.sendMessage(msg);
Cheers
I think what you are looking for is sending and receiving broadcast messages between activities.
Refer:
How to send and receive broadcast message
Or This tutorial.
http://hmkcode.com/android-sending-receiving-custom-broadcasts/
use of interface...
when the upload is successfull , it will fire the interface method
in that defination of method in activity will navigate to activity to carry data with put extra.

Why Use 'new' When Using AsyncTask [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
When using AsyncTask in android, I have to use like this,
new MyAsyncTask().execute()
I have to make new instance If I want to use AsyncTask.
But I wonder why I have to do.
I just want to use it like,
private MyAsyncTask task;
...
private void foo()
{
...
task.excute();
}
BUT I can't.
And I want to know why it doesn't work.
If you give me answer, I'm very appreciated.
Java is not RAII. You always need to create an instance of a class, because you cannot execute methods on a class directly unless the method is static. But then still the syntax would be different.
What you can do is more like this:
private MyAsyncTask task;
…
private void foo() {
task = new MyAsyncTask();
…
task.execute();
}
execute() is a method of AsyncTask. If you want to invoke then you need to create an instance of Asynctask.
If you want to execute a method of a class you need to instantiate and then call the appropriate methods.
task.excute(); will give you NUllPointerException.
task = new MyAsyncTask();
task.execute();
You may also want to check
http://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html
Look at the public methods as suggested by prosper k it is not a static method
http://developer.android.com/reference/android/os/AsyncTask.html
This is a matter of Java not Android. In java, something like:
MyAsynkTask task;
doesn't create an object. In this step you have only declared a variable. To use any method of your object (e.g. task.execute()) you have to instantiate an object (i.e. actually create one); like:
task = new MyAsyncTask();
Check this link for basics of "new" keyword. Basically it is use for Instantiating a Class.The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.
Hope this helps you.

Android & Azure Mobile Service Query: how to halt code execution until query finishes [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I need to know how to halt code execution until my mobile service query finishes. I am getting a null pointer exception because the code is attempting to access the query data before the query finishes.
---Code---
mEmployeeTable.execute(new TableQueryCallback<Employee>() {
//get employees
...
});
//In this activity i attempt to use the info loaded from the query above
//however since the query has not completed i get null pointer exception
startActivity(intent);
You need to start the activity only when you receive the callback, something similar to the code below:
mEmployeeTable.execute(new TableQueryCallback<Employee>() {
#Override
public void onCompleted(List<Employee> employees, int count, Exception exception, ServiceFilterResponse response) {
if (exception != null) {
// error happened during query, deal with it appropriately
} else {
// store the loaded employees somewhere
startActivity(intent);
}
}
});

Categories

Resources