How to display data from a Loader using Toast - java

I've a simple Activity (class MainActivity extends Activity implements LoaderManager.LoaderCallbacks<Cursor>)
Also I've a simple layout with a text box and a button.
Just to keep it simple, lets say I've a Loader that loads data from a HashMap<String> (which is already populated) and I've intialized/configured LoaderManager and CursorLoader appropriately.
Now I'd like to display the content of HashMap using a Toast upon clicking on the button, (which is bound to onClickRetrieveData(){} in Activity)
Any hint on how to do that?
UPDATE: I understand how to display data on Toast (once I have the data), but my question is more of the line of retrieving data from the Loader inside onClicRetrieveData().

It's hard to tell whether you're asking how to kickstart the Loader to get it loading or what to do when it is done. If we assume that you mean you want to start loading the data when the button is clicked and calls onClickRetrieveData(), then you'll do something like this:
#Override
void onClickRetrieveData(View v) {
getLoaderManager().initLoader(MY_LOADER_ID, null, this);
}
Then, your implementation of the LoaderCallbacks.onCreateLoader() will need to actually create an instance of your Loader. The framework will then kick it off and run it appropriately. When it is done, onLoadFinished() will be called and you'll have your results. From there you can do as you please: update an Adapter, pop up a Toast, etc.
Here's a primer on Loaders you may find helpful: http://po.st/xHoVMf

Related

Passing data though multiple activities (while one gets destroyed)

I'm building my first Android app in Android Studio (with Java) and I need some help understanding how to pass data through multiple activities.
The setup of affected classes/activities is this:
MainActivity: Opens a dialog called AddDialog (by creating a new Instance of it).
AddDialog (extends AppCompatDialogFragment): A dialog that has some buttons. One of them launches a class called BarcodeScanActivity (using intent).
BarcodeScanActivity: Simple activity that scan QR codes.
I want to pass the list of QR codes scanned by BarcodeScanActivity (I store them in a String Array) to MainActivity in order to use them, although BarcodeScanActivity is launched from the dialog that gets destroyed once buttons are clicked. Because of that I'm unable to set some startActivityForResult on the dialog and chain the result (onActivityResult) back to the MainActivity.
Also since MainActivity launches the AddDialog by creating an instance, I can't set a startActivityForResult there too.
I have tried adding Intent.FLAG_ACTIVITY_FORWARD_RESULT while launching BarcodeScanActivity from AddDialog, hoping that the result from BarcodeScanActivity will be forwarded back to MainActivity where I have created an onActivityResult method since AddDialog gets destroyed, but I don't know if that is even supposed to work as AddDialog is "launched" by a new instance of it, and not by using an intent.
I have thought about using broadcasts as a last resort, although I read that they are insecure, unreliable and not supposed to be used for passing that kind of data.
Any help is highly appreciated! Thanks

Relation between android:onClick and View.OnClickListener s

Dabbling with Android Studio, and working through a few tutorials , but I don't understand a concept. Oh, and new to java too...haha.
Lets say I have a screen, an activity, MainActivity.xml with a button.
MainActivity.xml has an onClick attribute goForIt defined for the button.
In the MainActivity class I have a method goForIt.
This is where the button being clicked will be responded to.
Inside that goForIt method,
I build an Intent to start another activity,
and fire it off by the statement startActivity(intent)
Questions:
Why do I need a listener? (If I do)? The MainActivity.xml is an explicit directive to a specific method. Or is that a "listener"?
What's the role of the manifest in this? The activity is there... but for what purpose? Again, being able to find the class and method is pretty explicit without any need to consult a lookup like the manifest....?
I'm confused by the Activity XML having an explicit attribute to a specific method in the class, and then at the same time, the Listener saying that if the onClick happens, then do something... they are both trying to do the same thing are they not?
You can use listener or you can specify a method in xml to listen to the click on a view. In both you can the view as the parameter.
2.Manifest file helps you for many purpose:
to specify which activity is to be launched first
to get permissions for accessing internet, getting cal logs, using maps etc,
Specifying the theme or label for each activity and so and so ..
3.Both does the same thing. One is an alternative for other.
This question is waaay to wide and should be (probably will be) closed.
But, here goes:
onClick attribute in xml file is a shortcut for creating a listener (the listener in such case gets created behind your back). You either use that, or a listener done by hand.
Manifest has no role in this (pressing the button). But it is necessary to configure the activity so that it starts when the launcher icon is pressed (among many other things).
Android API looks as if it was never properly designed... it just grew and evolved. So yes, there are multiple, confusing ways to do a single thing.
Using
<Button
android:id="#+id/button"
android:onClick="goForIt"/>
and then
public void goForIt(View v) {
startActivity(...)
}
is exactly the same thing that using:
Button b = findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(...)
}
});
The first option is just a workaround, a short path to have the same effect.
Internally, it is just doing things the second way - take the button, add a click listener to it, and run it as soon as the user clicks on the button.
When your layout is inflated (after you call setContentView(R.layout.my_layout)) the attribute android:onClick gets internally converted into something like this:
Button b = findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goForIt(v);
}
});
The only difference is that it does it for you.
The manifest has no role in this context.
Why do I need a listener? (If I do)? The MainActivity.xml is an explicit directive to a specific method. Or is that a "listener"?
Think you have 10 buttons where click is required, so Listener can handle all those types of button click.
What's the role of the manifest in this? The activity is there... but for what purpose? Again, being able to find the class and method is pretty explicit without any need to consult a lookup like the manifest....?
From manifest Android ( application manager ) understands things about your app like, which page is 1st or launcher page.
I'm confused by the Activity XML having an explicit attribute to a specific method in the class, and then at the same time, the Listener saying that if the onClick happens, then do something... they are both trying to do the same thing are they not?
yes they are doing same thing, try to use listener for them.

check the current activity in if condition

I am working on an android application so I need to check if the user is at some activity say "xyz" then proceed or change background colour etc. How can I check the current activity in if condition like
if (xyz activity){
set Background Color
// Do something
}
How can I do this in runtime so that whenever user goes to any screen this condition becomes true and then the below code works?
Try this:
if(getActivity() instanceof TheWantedActivity){
//...
}
If i follow your question than put your background code in your OnResume(); if the activity is in foreground its onResume always called.
In each activity or "screen" a user can see or interact with, a class is designated to that view. So if you want to set the background to activity xyz, you do not need to check if the user is there. You need to just load the background you specify within the onCreate(Bundle bundle) method with "setContentView(R.layout.your_activity_layout)". This layout should be stored in your res/layout folder after you create an activity. So for example, if your activity is named StartActivity.java, the layout file saved in res/layout will most likely be named activity_start.xml.
If the answer Saurabh provided isn't promising enough you can take
ActivityLifecycleCallbacks in your Application class, It will only work API 14 and above

Start android program with settings

When my program start I would like to do some settings before is really starting. Forexample choose the user, check the updates and so on. After these settings I would like to start the main program with the appropriate.
Which is the best way to do this?
You can run an AyncTask, or multiple if you need one for each check, in your onCreate() and show a ProgressDialog while the data is being fetched then cancel it in onPostExecute() and move on to the rest of the MainActivity depending on the data that is downloaded. If you need help getting started with AsyncTask you can see this SO answer on the basic structure.
If you use a ProgressDialog then the app will still start but the users will see something and know that data is loading so they won't feel like it is freezing or taking too long to load (or at least they will know why it isn't loaded right away).
AsyncTask Docs
Edit after comment
For what you said you want in your comment you can do this easily with an Activity that has a Dialog Theme. This will give you the functionality you need (a couple Buttons and store the values) but it will look like a little popup. You can't use an actual Dialog as they need an Activity, the same with any menus, AFAIK. Just create your Activity and make it the launcher and main using the Intent-filters then also add the following line to that Activity's tag in the manifest
android:theme="#android:style/Theme.Dialog"
This approach should give you what you need
There are numerous ways to do that.
First - your app is doing some heavy stuff and this may be freezing user interface. In that version do:
1. Create and activity on what you will override onCreate method and set some content with a spinner - so something will be alive and user will see that something is being done.
2. after you will compute all the things that your app need and may I suggest write it to some global variables override onStart method in what change layout to what suit you and give a user a great UI!
Second - you app is not heavy lifting here just throw everything into override of onStart method.
Handy material here for educating:

How to show DialogFragment from within the onLoadFinished method of LoaderCallbacks

I receive an exception when trying to show a DialogFragment from within the onLoadFinished method of a Fragment that implements the LoaderCallbacks interface. Basically I am using the LoaderCallbacks to get some data from a rest service and then on the onLoadFinished I am trying to show a custom DialogFragment that contains a ListVeiw to allow the user to make a selection. Everything works great except when I try to launch the dialog from within the onLoadFinished. How can I accomplish this..and is this the correct approach to the problem.
Here is an example of what I am trying to do:
public class EventFragment extends Fragment implements LoaderCallbacks<someresponse> {
#Override
public void onLoadFinished(Loader<someresponse> arg0, someresponse data) {
//an exception is generated when trying to launch a dialog fragment from
//within the onLoadFinished
FragmentManager manager = getFragmentManager();
ListViewDialogFragment dialog = ListViewDialogFragment.newInstance(data);
dialog.show(manager, "event_list_dialog");
}
}
Thanks!
So after some research, I have determined that my approach was incorrect. You should never try to launch a new fragment from within the onLoadFinished method of an LoaderCallbacks async task. The framework tries to keep you from doing this because the state of the currently running fragment or activity, that implements the LoaderCallbacks is indeterminate and therefore not guaranteed to be there when the async task finishes.
Additionally trying to separate a processing dialog state and data display state into two separate fragments is a bit counter to the MVC design pattern that the android framework supports. That said, my new approach consisted of dynamically changing the view for the fragment implenting LoaderCallbacks to hide or show a specific linear layout, one for the process indicator and one for the display of the data. This approach left me modifying an existing fragment instead of launching a new one which worked out great.
Here is a link to the discussion that finally gave me clarity.
https://groups.google.com/forum/#!topic/android-developers/dXZZjhRjkMk/discussion
The approach you define is quite good, except one case - what will happen if your activity had already gone from the screen, when loading operation got finished? How it will show dialog in this case?
So generally, I would appreciate if you'll tell which exactly exception did you get.
However, as a general approach, it can be useful to check is the activity holding the fragment is still on top or even was it finished or not.
Even better - you should consider cancelling all background operations when activity/fragment is destroying, in this case you'll have no problems with showing dialogs.
Good luck!

Categories

Resources