I am looking to display loading screen until my main activity loads required data from back-end. Therefore I start LoadingActivity from my MainActivity oncreate method.
After all required data is retrieved from back-end I want to close LoadingActivity from MainActivity.
How could I do this? Is this a better way to avoid displaying empty screen to user until required data is loaded? Please help me.
You can easily this type of task with the help of Fragment. For example, when you want to start your LoadingFragment from your MainActivitiy you can start as,
LoadingFragment fragment = new LoadingFragment();
FragmentTransaction transaction = getSupportFragmentManager.beginTransaction();
transaction.replace(android.R.id.container, fragment);
transaction.commit();
Now, you want to make your fragment to be in fullscreen mode. You can easily do this by adding windowflags in onCreateView method of your fragment as,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getActivity().getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
In the MainActvity use a global variable:
ProgressDialog progressDialog;
#override
void onCreate(){
progressDialog = new ProgressDialog();
//Other initialisations and tasks
progrssDailog.show();
}
//After loading the MainActivity you can simply
progressDialog.dismiss();
Finally what you mean by LoadingActivity, is it a custom class by you? is it necessary to use that particular LoadingActivity.
Related
I want to check some condtiton before the main activity starts and based on test result i have to either start a new activity or continue the same activity. How to do this?
you can check it in your OnCreate() method. It is called when your activity start.
onCreate(...){
....
if(want this){
//continue;
}else{
// start new activity
}
}
The default Activity to start is set in the manifest, so a better approach to your problem would be to use fragments. Keep in mind that fragments are faster/lighter, so instead of using Application as a "decision" class to start activities (bad practice), use your main activity. In your onCreate() method, check for your condition and attach the needed fragment.
I am using java annotation to handle this case:
Create the Annoation class
Create CustomContext.java with a startActivity method in it
Create the Interceptor.java
Create a class which implement Interceptor like this (named DemoInterceptor.java here)
Declare a static variable of DemoInterceptor in your activity. and the demo Activity should like this then, start the activity via the custom startActivity in step #2
enjoy and let me know if you have any further question.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(startNewActivity) {
// TODO Fire off intent to start new activity
finish(); // Closes the current activity
return;
}
// TODO Code for current activity.
}
startNewActivity is a boolean indicating whether to launch a new activity or not. It should be assigned a value depending on your condition.
I am working with a navigation drawer on a MainActivity and then I am using this navigation drawer to replace different fragments int the container of the MainActivity. In Fragment I am using Google Map. In this fragment I am also using the Ion library to download some location information from the server and to show them on the map.
The navigation drawer items are Home ,friends location , about us
now when I click on friend location I want to draw pins on the map , so I am u
using the same map of the home screen as home screen is also showing map.
What I am doing on Friends location item click is as under
myMapFragment = new MyMapFragment();
fragmentTransaction1.replace(R.id.frame, myMapFragment, "MyMapFragment").commit();
fragmentManager.executePendingTransactions();
myMapFragment.GetAllFriendsLocation("share",MainActivity.this);
so the GetAllFriendsLocation is the method in that fragment which is showing map and this function is downloading location information from server and then draw pins on the map
this is how I am doing this
public void GetAllFriendsLocation(String type) {
MainActivity.setOverflowButtonColor(getActivity(),2);
if(cd.isConnectingToInternet()) {
progressDialog.show();
Ion.with(getActivity())
.load("http://myapi.com/data.php")...
but I am getting nulpointerException on the following line
Ion.with(getActivity())
.load("http://myapi.com/data.php").
it seems like that getActivity is empty as the fragment is not fully initiated.
So please give me advises that how can I call the fragment method when it is initialized and ready to show on the screen , after when it is initialized the method should run and download from server.
or second this i can think of is , How can I get context in mainactiivty before the fragment is initialized ???
please help me in this ..
Try Creating and using Fragment using instance instead of constructor.
Create an instance of fragment in the fragment class itself like this:
public static MyMapFragment newInstance(Bundle bundle) {
MyMapFragment fragment = new MyMapFragment ();
fragment.setArguments(bundle);
return fragment;
}
And then in your activity use it like this:
MyMapFragment fragment = MyMapFragment.getInstance(bundle);
where bundle contains any thing you might wish to send to fragment.
This should work.
You should use onCreate() and onViewCreated() methods.
You load a fragment inside onCreate() method. and call method in onViewCreated() method.
I think it's similar to here android get activity returns null
As my opinion, before doing something with getActivity you should check your Fragment isSafe or not safe like: (recommend)
private boolean isSafe()
{
if (this.isRemoving() || this.getActivity() == null || this.isDetached() || !this.isAdded()
|| this.getView() == null)
{
return false;
}
return true;
}
Or cache your activity like
private Activity mActivity;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.mActivity = activity;
}
I have a two class named Stock Details extends Fragment and another one is Stock info extends activity,
when I was trying to go back to my Stock details pages from Stock info pages it shows "Unfortunately,Application has stopped",but in my program I use
Intent intent = new Intent(this,StockDetails.class);
startActivity(intent);
finish();
for go back to fragment. but it does not work. help me to solve this problem
I am the beginner for android.
kindly help me to go back from an Activity to fragment
you do not need to start activity for StoreDetail as it is a subclass of Fragment not Activity.This is the reason that your app is crashed.
Now moving to your question if you want to go back to the fragment from the activty : Stock INFO you just need to call finish() it will finish the current activity(Stock Info) and the fragment which is in background will be resumed.I had same problem and solved by this way .This is the onCreate Method of Activity(in your case it is for StockInfo class).Have a look:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setmCallBack(new IResultCallback() {
#Override
public void result(Result lastResult) {
if (lastResult!=null) {
finish();// by this line I have killed the current activity
}
else
{
Toast.makeText(getActivity(), "NotScan: ", Toast.LENGTH_SHORT).show();
}
}
});
}
Ok look,
startActivity(intent);
this method name startActivity. So it will start another activity not fragment.
You can See & read the fragment:
http://developer.android.com/guide/components/fragments.html
Add fragment to go back to manually to the backstack.
FragmentTransaction transaction = getFragmentManager().beginTransaction();
YourFragmentName myFragment = new YourFragmentName();
transaction.replace(R.id.fragment_container, myFragment);
transaction.addToBackStack(null);
transaction.commit();
And There is several methods here. Just take a look:-
http://developer.android.com/reference/android/app/FragmentManager.html#popBackStack()
If you want to go back to the fragment , you can do this :
getFragmentManager().popBackStack();
I am checking internet connection in my main activity.If connection is lost,I want to show reconnecting message in fragment.Example:If I run following code in main activity my app is crashing.
ConversationFragment conv1 = new ConversationFragment();
conv1.showReconnecting();
And this is the showReconnecting method in fragment:
public void showReconnecting() {
final RelativeLayout rel=(RelativeLayout)rootView.findViewById(R.id.reconnecting);
rel.setVisibility(View.VISIBLE);
}
I know why my app is crashing because rootView is setting in onCreateView and when I call this method from activity rootView is returning null.
What can I do for resolve this problem ?
Try this (Assuming reconnecting view is in fragment and your fragment is visible on screen),
public void showReconnecting() {
if (conv1 != null && conv1.getView()!=null) {
final RelativeLayout rel=(RelativeLayout)conv1.getView().findViewById(R.id.reconnecting);
rel.setVisibility(View.VISIBLE);
}
}
If conv1 is not available then please make it class variable.
According to what you want to do, a simple ProgressDialog will do the job. You can lauch it from your ChatFragment, like this:
First, declare it on your Fragment:
private ProgressDialog connectiongProgressDialog;
Then, when you want to show it, use:
connectiongProgressDialog = ProgressDialog.show(getActivity(), "My title", "Reconnecting");
When you want to dismiss it, use:
if (connectiongProgressDialog != null){
connectiongProgressDialog .dismiss();
}
It will display a simple dialog with the message you want.
Well, just looking at this and your explanation, I would think you can't call methods relating to a view (such as a fragment) without creating said fragment. An option, if the fragment is only used for showing the reconnecting, would be just to put some code in the activity and use a Toast.makeText(....).show();
which notifies the user that you are attempting to reconnect. So instead of conv1.showReconnecting(); maybe rather put, Toast.makeText(context,"Reconnecting", Toast.LONG).show(); and then do the necessary background work in an AsyncTask.
I hope this helps.
Sorry if this been asked before but I couldn't find an answer to my specific case. Also sorry that I'm new and a little stupid.
Problem:
I'm showing a dialog from a fragment and passing along a context in my constructor method because I need a context in my dialog to register for broadcastrecievers etc.
DialogFragment fragmentDialog = MyDialog.myConstructor(getActivity());
fragmentDialog.show(getFragmentManager(), "dialog");
Then in MyDialog class I store the context in a instance variable.
The problem arises when rotating the device and I get a nullPointerException when I try to use the context again in the dialog.
Can this be solved in some easy way?
If the device is rotated the Activity will be destroyed and recreated. So the Context you passed to your Fragment points on the Activity which was destroyed.
You could use setRetainInstance(true) in your Fragment. This way your Fragment will survive the recreation of the Activity.
To solve the NPE you have to pass the Context to the Fragment, if the Activity is recreated. Then the Context belongs to the new Activity.
In fact, without this update every line of code which points on the Activity like getActivity() or getFragmentManager() will lead in a NPE.
You get the NullPointerException because activites are destroyed and recreated when rotating the screen.
The SO post below gives more info...
https://stackoverflow.com/a/1673374/
Please be careful with the order of events if you rotate a FragmentActivity, because this can also be a source of NullPointerExceptions.
This is not documentated:
When the FragmentActivity is created the first time,
public class MyActivity extends FragmentActivity implements
MyFragment.OnFragmentInteractionListener {
private int var1;
private int var2;
#Override
protected void onCreate(Bundle savedInstanceState) {
//before
var1 = 3;
super.onCreate(Bundle savedInstanceState)
//after
var2 = 5;
}
//Interface Methods
public int getVar1() { return var1; }
public int getVar2() { return var2; }
}
both of the [before] and [after] code will be run before the fragments are attached and created. So, if you get the vars in the onCreate() call of the Fragment you get both vars. But when you rotate your device, the Activity is recreated from the savedInstanceState in the super call. Now, the fragments are reattached and created anew in this call! That means, this time the Methods of the Listener Interface are called before your [after] code. So, if you pass the Context of the activity to the fragment and get Information through the Interface like it is shown in: https://developer.android.com/training/basics/fragments/communicating.html
you get a NullPointerException for var2 because the interface methods are called from the fragments onCreate() onAttach() ... functions before the [after] code in the Activity's onCreate() is executed! So, take care that you set your Information the InterfaceFunctions are accessing before the super call.
Depending on what you're doing in your initialization you could consider creating a new class that extends Application and moving your initialization code into an overwridden onCreate method within that class.
public class MyApplicationClass extends Application {
#Override
public void onCreate() {
super.onCreate();
// TODO Put your application initialization code here.
}
}
And you are not stupid, even experts need help from time to time.