Want to send data to another activity on getting data [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 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.

Related

MediaBrowser(Compat) subscribe/query items with pagination [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 4 years ago.
Improve this question
In my Service-side, it has huge data and I want to provide items with pagination way.
Is there any recommended flow to traverse with pagination between MediaBrowser/MediaBrowserService(Compat)?
I want to provide partial data in Result<List<MediaItem>> instead of all data (e.g. all YouTube songs), while browser-side using pagination to pull partial data once a time.
In your
MediaService extends MediaBrowserServiceCompat
#Override
public void onLoadChildren(#NonNull final String parentMediaId, #NonNull final Result<List<MediaItem>> result) {
result.detach();
for (int page = 0; i<pages.size(); i++){
result.sendResult(getList(page));
}
}
public List<MediaItem> getList(int page){
//here create List for page-number == page
}
OR
You can make request in your Fragment or Activity with page
MediaBrowserCompat mediaBrowser = ...;
mediaBrowser.subscribe("1"/*it's page*/, mSubscriptionCallback);
then in your Service make this:
#Override
public void onLoadChildren(#NonNull final String page, #NonNull final Result<List<MediaItem>> result) {
result.detach();
result.sendResult(getList(page));
}
I wanted to do a similar thing in my app - I wanted to return the existing songs on the device but in paginated way. Like you say, a partial result in the onLoadChildren() method. I ended up using Android's new Paging library to do just that. Using the library, I could make the client/UI side asks the service for only the pages the user is interested to see, and then serve only those in the onLoadChildren() method, calling the client's subscribe() method to retrieve it.
I go over it in details in a post I wrote, where I also give code samples to better demonstrate the concept.

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
}
});

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.

check if a method was called on UI-Thread with robolectric [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
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) {
///...
}

What is the relationship between AsyncTask and Activity? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have been given an assignment to develop an application that send server request and get response and then using JSON parsing, display the data content into a ListView.
I don't understand about AsyncTask and how to integrate all classes. Hope you will accommodate.
regards
What should you do?
The first, send a request to server
The second, get response
The thirds, Parse data from InputStream which you got from Response
The fourth, show on ListView
Oh, done.
Right now,
Look into the first step.
How to send a request to server?
You can use HttpURLConnection or HttpClient
So, What's problem when you send a request to server?
I think you know when you send a request to server, you will get some problem: Network bad, InputStream from Server too large, ...
And how to resolve?
With single statement, you can't take along time to do. So with task which will takes along time to do, you have to handle in other thread. That's reason why we should use Thread or AsyncTask.
What's AsyncTask?
You can read more by search on Google. I just tell you: How to use AsyncTask to solve your spec.
What does AsyncTask do?
When you create an instance of AsyncTask,
It's will follow:
-> Create -> PreExecute -> Execute (DoInBackground) - PostExecute
Ok.
Right now, I will answer your question:
Create an object which extends AsyncTask.
public class DownloadFile extends AsyncTask<String, Void, InputStream> {
#Override
public void onPreExecute() {
// You can implement this method if you want to prepare something before start execute (Send request to server)
// Example, you can show Dialog, or something,...
}
#Override
public InputStream doInBackground(String... strings) {
// This is the important method in AsyncTask. You have to implements this method.
// Demo: Using HttpClient
InputStream mInputStream = null;
try {
String uri = strings[0];
HttpClient mClient = new DefaultHttpClient();
HttpGet mGet = new HttpGet(uri);
HttpResponse mResponse = mClient.execute(mGet);
// There are 2 methods: getStatusCode & getContent.
// I dont' remember exactly what are they. You can find in HttpResponse document.
mInputStream = mReponse.getEntity().getContent();
} catch (Exception e) {
Log.e("TAG", "error: " + e.getMessage());
}
return mInputStream;
}
#Override
public void onPostExecute(InputStream result) {
//After doInBackground, this method will be invoked if you implemented.
// You can do anything with the result which you get from Result.
}
}
Ok. Now we have to use this class
In your MainActivity or where you want to invoke this class, create an instance of this class
DownloadFile mDownloader = new DownloadFile();
mDownloader.execute("your_url");
Using method mDownloader.get(); to get InputStream if you want to get. But you have to surround by try-catch
I know, if you want to use Dialog, you will search on Google how to show Dialog while download file from server.
And I suggest you that you should remember, you nead runOnUiThread if you want to Update UI.
Because an AsyncTask is Thread. So you can not Update UI if you are in another Thread which is not MainThread.
AsyncTask
AsyncTask enables proper and easy use of the UI thread. It is used when you want to perform long awaited task in background.
It publish result on the UI thread(display result to the UI) without having to manipulate any threads or handlers.It means that user doesn’t bother about Thread management, everything is managed by itself. And thats why it is known as Painless Threading, see below point.
It is also known as Painless Threading.
The result of AsyncTask operation is published on UI thread. It has basically 4 methods to override: onPreExecute, doInBackground, onProgressUpdate and onPostExecute
Never expect to be a programmer by referring short notes, study deep..
Look here for more detail.

Categories

Resources