android dialog call dismiss but is not dismiss - android

I have a problem with my Android app coding as follows:
I use dismiss() to hide a dialog, but dialog just does not disappear as expected. Dialog remains in activity interface while dismiss() is actually called.
It feels like get stucked or something else. Hardware back button does not work either. App just gets stuck in there.
Can anyone help me out
Thanks in advance.
Example pic
And there are some related code. I use MVP architect.
#Override
public void editAllNum(Context context, int num, List<ShopCar.GoodListBean> goodList) {
Subscription s = Observable.just(num)
.filter(integer -> goodList.size() != 0) //the goodList of size is never equal to 0.
.subscribeOn(Schedulers.io())
.compose(TransformerUtil.showLoadingDialog(mView)) //call show dialog.
.flatMap(new Func1<Integer, Observable<List<ShopCar.GoodListBean>>>() {
#Override
public Observable<List<ShopCar.GoodListBean>> call(Integer num) {
List<ShopCar.GoodListBean> list = new ArrayList<ShopCar.GoodListBean>();
for ( ShopCar.GoodListBean item : goodList ) {
if ( item.getRemainNum() != 0 ) {
if ( item.getRemainNum() > num ) {
if ( item.getLimit() != 0 ) {
item = editNum(item, num); //editNum is not important
} else {
item.setNum(num);
}
} else {
if ( item.getLimit() != 0 ) {
item = editNum(item, num);
} else {
item.setNum(item.getRemainNum());
}
}
}
list.add(item);
}
return Observable.just(list);
}
})
.flatMap(new Func1<List<ShopCar.GoodListBean>, Observable<List<ShopCar.GoodListBean>>>() {
#Override
public Observable<List<ShopCar.GoodListBean>> call(List<ShopCar.GoodListBean> temp) {
return mPaymentImpl.updateGoodsNumAndQuery(context, temp); //operate databases update some data.
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<ShopCar.GoodListBean>>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
mView.dismissLoadingDialog();
}
#Override
public void onNext(List<ShopCar.GoodListBean> list) {
mView.dismissLoadingDialog();// call dismiss dialog.
mView.setShopCarFromDB(list);
}
});
addSubscription(s);
}
#Override
public void showLoadingDialog() {
if ( mLoadingDialog == null ) {
mLoadingDialog = new LoadingDialog(getContext());
LogUtils.e(" show loading dialog = " + mLoadingDialog);
}
mLoadingDialog.show();
}
#Override
public void dismissLoadingDialog() {
if ( mLoadingDialog != null ) {
LogUtils.e(" dismiss loading dialog ");
mLoadingDialog.dismiss();
}
}
some code of Dialog.
public class LoadingDialog extends Dialog {
public LoadingDialog(Context context) {
super(context, android.R.style.Theme_Translucent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.widget_loading_dialog);
setCanceledOnTouchOutside(true);
setCancelable(true);
}
}
//XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#drawable/loading_dialog_bg"
>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
/>
</RelativeLayout>
</RelativeLayout>
Finally, sorry my English.

Check if the value of mLoadingDialog is null first. Maybe somehow the value is null. ie. the dialog u see on the screen might not be that mLoadingDialog. By change the function below, what did you see in logcat?
#Override
public void dismissLoadingDialog() {
if ( mLoadingDialog != null ) {
LogUtils.e(" dismiss loading dialog ");
mLoadingDialog.dismiss();
}else{
LogUtils.e("mLoadingDialog is null skip dismiss loading dialog ");
}
}

Related

I want to use a progress bar with RxJava like you can with AsyncTask

I want to replace my AsyncTask with RxJava in android. My current AsyncTask goes like this:
public class ProgressBarAsyncTask extends AsyncTask<Void,Void,Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
ringProgressDialog = ProgressDialog.show(context,"MyProgressBarTitle","Working please wait",true, false);
}
#Override
protected Void doInBackground(Void... void) {
//do work
myTask();
return null;
}
#Override
protected void onPostExecute(Void void) {
super.onPostExecute();
ringProgressDialog.dismiss();
}
}
Here's my RxJava replacement:
public static Observable<Void> getObservable(final Context context,final String... params) {
return Observable.defer(new Func0<Observable<Void>>() {
#Override
public Observable<Void> call() {
return Observable.just(myTask());
}
});
}
public static Subscriber<Void> getSubscriber() {
Subscriber<Void> subscriber = new Subscriber<Void>() {
#Override
public void onCompleted() {
ringProgressDialog.dismiss();
}
#Override
public void onError(Throwable e) {
Log.d(TAG,e.toString());
}
#Override
public void onNext(Void aVoid) {
manipulateData();
}
};
return subscriber;
}
My Activity:
public class MainActivity extends Activity {
private ProgressDialog ringProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GetNumberObservable.Observable()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()))
.subscribe(getSubscriber());
}
}
How do I mimic the onPreExecute() method in the AsyncTask where I kick off the progressDialog?
Here is how I would do it:
public final class ProgressOrResult<T> {
final int progress;
final T result;
public ProgressOrResult(int progress, T result) {
this.progress = progress;
this.result = result;
}
}
ProgressDialog ringProgressDialog = ProgressDialog.show(
context, "MyProgressBarTitle", "Working please wait", true, false);
Observable.fromEmitter((Emitter<ProgressOrResult> emitter) -> {
// generate "progress"
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
emitter.onNext(new ProgressOrResult(i, null));
Thread.sleep(1);
}
// generate "result"
emitter.onNext(new ProgressOrResult(100, sum));
emitter.onComplete();
}, BackpressureMode.BUFFER)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(result -> {
if (pr.result == null) {
ringProgressDialog.setProgress(pr.progress);
} else {
ringProgressDialog.dismiss();
// process the result here
}
}, error -> {
// handle error here
})
In RxJava you have the do operators, that creates Observable
lifecycle events listeners, in your case you want to do something
(update the UI) before the task started, which mean you want the
doOnSubscribe event. (side note it is true with 'cold' Observables
that started thier work when subscrbied to - like your case) Just
beware to call .observeOn(AndroidSchedulers.mainThread())) before
the doOnSubscribe in order to get notified on the mainThread, as
you're updating the UI.
Instead of using both defer and just
return Observable.defer(new Func0<Observable<Void>>() {
#Override
public Observable<Void> call() {
return Observable.just(myTask());
}
});
you can use fromCallable:
Observable.fromCallable(new Callable<Object>() {
#Override
public Object call() throws Exception {
return myTask();
}
})
I am showing progressBar indoOnSubscribe() , hiding in doOnError() and in subscribe().
Please refer to this link for more details.
Shameless Promotion
I've created RxLoading library for that, it can do this and much more,
you can just do something like this:
networkCall().compose(RxLoading.<>create(loadingLayout)).subscribe(...);
it consists out of 2 classes, a custom view (loadingLayout) and RxLoading which is a transformer that glue it all together, you can choose to work with both or either of them.
if you want RxLoading with a simple progress bar you just need to implement an interface and you are done.
you can check more on the GitHub page.

Android: Avoid opening the dialog several times, but allow hide and shows the same dialog

I have an Activity with ViewPager PagerSlidingTabStrip for each page of my ViewPager has a fragment, and in each fragment realize an http request (using Volley) to load the data from the page, but when the request ends in error, type timeout or lost connection, I need to display a dialog with the option to redo the call to the server, the problem to prevent multiple dialogs are open for each error is resolved with the snippet:
See this solution here: http://www.jorgecoca.com/android-quick-tip-avoid-opening-multiple-dialogs-when-tapping-an-element/
#Override
public void show(FragmentManager manager, String tag) {
if (manager.findFragmentByTag(tag) == null) {
super.show(manager, tag);
}
}
When the user clicks the dialog button to try again, and the dialog closed and taken to check if there is internet connection, if I'm not, the dialog should be opened again, but the dialog is not displayed again, I believe that the tag does not was released to FragmentManager.
Code in Activity:
final Button mButton = ( Button ) this.findViewById( R.id.btn_opendialog );
final DialogFragmentHelper mDialog = new DialogFragmentHelper();
mDialog.setCallbackListener( new OnCallback() {
#Override
public void onCancel() {
}
#Override
public void onConfirm() {
// verify if network available
mDialog.show( MainActivity.this.getSupportFragmentManager(), DialogFragmentHelper.DIALOG_TAG );
}
} );
mButton.setOnClickListener( new OnClickListener() {
#Override
public void onClick( final View v ) {
mDialog.show( MainActivity.this.getSupportFragmentManager(), DialogFragmentHelper.DIALOG_TAG );
}
} );
Would someone have a suggestion of a workaround?
In order to maintain the structure that is ready in my project, and also keep something closer to my goal, which is to use no flags, nor pass control of a third dialogfragment to manage, arrived at a solution that'll take an hour as a result.
DialogFragmentHelper mDialog = new DialogFragmentHelper();
mDialog.setCallbackListener( new OnCallback() {
#Override
public void onCancel() {}
#Override
public void onConfirm() {
mDialog.dismissAllowingStateLoss();
if(networkAvailable == false){
new Handler().post( new Runnable() {
#Override
public void run() {
mDialog.show( MainActivity.this.getSupportFragmentManager(), DialogFragmentHelper.DIALOG_TAG );
}
} );
}else {
//do something here
}
}
} );
this way I guarantee that while several requests are sent to open the dialogfragment, only the first is executed, and closing the dialogfragment, I can quickly open it again if needed, as can happen in the scenario I'm working.
You could approach it with a singleton controller. E.g.:
package com.example.stackoverflowsandbox;
public class MyDialogController {
private static MyDialogController instance;
public static MyDialogController getInstance() {
if ( MyDialogController.instance == null ) {
MyDialogController.instance = new MyDialogController();
}
return MyDialogController.instance;
}
private boolean dialogOpenned;
private MyDialogController() {}
public void closeDialog() {
if ( this.dialogOpenned ) {
this.dialogOpenned = false;
// you close code...
}
}
public void openDialog() {
if ( !this.dialogOpenned ) {
this.dialogOpenned = true;
// your open code...
}
}
}

Custom progressbar dialog with dialogFragment

I'm new to android programming. I want to create a custom progress dialog with some textview and button and showing the progress with two progressBar and updating them while sending the files from Asynctask, Also I want it works with minimum API 10. google doc recommend me to use DialogFragment and i do not have any idea how to update the progress bars and textviews that are in that custom layout of my fragmentDialog, when I try to reference a textview or progress bar it throw null exeption
Here is my code
public static class FireMissilesDialogFragment extends DialogFragment {
public FireMissilesDialogFragment(){
}
public static FireMissilesDialogFragment newInstance(String title) {
FireMissilesDialogFragment frag = new FireMissilesDialogFragment();
Bundle args = new Bundle();
args.putString("title", title);
frag.setArguments(args);
return frag;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = this.getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
View view = inflater.inflate(R.layout.custom_progress, null);
ProgressBar pbCurrent = (ProgressBar) view.findViewById(R.id.current);
builder.setView(view);
builder.setMessage("Fire Missiles")
.setPositiveButton("Fire", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
I got a nullExeption here in my main activity when try to reference a view
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button frag = (Button) findViewById(R.id.frag);
frag.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FireMissilesDialogFragment fragment = FireMissilesDialogFragment.newInstance("hi") ;
fragment.getActivity().findViewById(R.id.current);// nullExeption here
// downloadAsync as = new downloadAsync();
// as.execute();
}
});
I didn't see much question and example about that, did I go all the way wrong and should pick another way to achieve my point??!!
Edit :
I'm trying to create something like this
thanks in advance
I can not do a full explanation but I can leave an example and then hopefully you can figure out a way to incorporate the things you need.
The DialogFragment with an AsyncTask and a Progress bar:
public class LoadHydrantsToMapTaskFragment extends DialogFragment {
public static final String TAG = LoadHydrantsToMapTaskFragment.class
.getSimpleName();
public interface LoadHydrantsToMapTaskCallback {
void onPreExecute(int maxProgress);
void onProgressUpdate(int progress);
void onCancelled();
void onPostExecute();
}
private LoadHydrantsToMapTask mTask;
// private ProgressBar mProgressBar;
private List<HydrantHolder> mHydrants;
private GoogleMap map;
public static LoadHydrantsToMapTaskFragment newInstance(
List<HydrantHolder> hydrants, GoogleMap map) {
LoadHydrantsToMapTaskFragment taskFragment = new LoadHydrantsToMapTaskFragment();
taskFragment.mHydrants = hydrants;
taskFragment.map = map;
return taskFragment;
}
#Override public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_progress_task, container);
mProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);
mProgressBar.setProgress(0);
mProgressBar.setMax(mHydrants.size());
getDialog().setTitle(getActivity().getString(R.string.adding_hydrants));
// This dialog can't be canceled by pressing the back key.
getDialog().setCancelable(false);
getDialog().setCanceledOnTouchOutside(false);
return view;
}
/**
* This method will only be called once when the retained Fragment is first
* created.
*/
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(SherlockDialogFragment.STYLE_NORMAL, R.style.TuriosDialog);
// Retain this fragment across configuration changes.
setRetainInstance(true);
mTask = new LoadHydrantsToMapTask(mHydrants);
mTask.setCallback(new LoadHydrantsToMapTaskCallback() {
#Override public void onPreExecute(int maxProgress) {
}
#Override public void onProgressUpdate(int progress) {
mProgressBar.setProgress(progress);
}
#Override public void onPostExecute() {
if (isResumed())
dismiss();
mTask = null;
}
#Override public void onCancelled() {
if (isResumed())
dismiss();
mTask = null;
}
});
mTask.execute();
}
#Override public void onResume() {
super.onResume();
// This is a little hacky, but we will see if the task has finished
// while we weren't
// in this activity, and then we can dismiss ourselves.
if (mTask == null)
dismiss();
}
#Override public void onDetach() {
super.onDetach();
}
// This is to work around what is apparently a bug. If you don't have it
// here the dialog will be dismissed on rotation, so tell it not to dismiss.
#Override public void onDestroyView() {
if (getDialog() != null && getRetainInstance())
getDialog().setDismissMessage(null);
super.onDestroyView();
}
// Also when we are dismissed we need to cancel the task.
#Override public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
// If true, the thread is interrupted immediately, which may do bad
// things.
// If false, it guarantees a result is never returned (onPostExecute()
// isn't called)
// but you have to repeatedly call isCancelled() in your
// doInBackground()
// function to check if it should exit. For some tasks that might not be
// feasible.
if (mTask != null)
mTask.cancel(false);
}
private class LoadHydrantsToMapTask extends
AsyncTask<Void, Integer, List<MarkerOptions>> {
// Before running code in separate thread
List<HydrantHolder> mHydrants;
LoadHydrantsToMapTaskCallback mLoadHydrantsToMapTaskCallback;
public LoadHydrantsToMapTask(List<HydrantHolder> hydrants) {
this.mHydrants = hydrants;
}
public void setCallback(
LoadHydrantsToMapTaskCallback loadHydrantsToMapTaskCallback) {
this.mLoadHydrantsToMapTaskCallback = loadHydrantsToMapTaskCallback;
}
#Override protected void onPreExecute() {
if (mLoadHydrantsToMapTaskCallback != null) {
mLoadHydrantsToMapTaskCallback.onPreExecute(mHydrants.size());
}
}
// The code to be executed in a background thread.
#Override protected List<MarkerOptions> doInBackground(Void... arg) {
List<MarkerOptions> markers = new ArrayList<MarkerOptions>();
for (HydrantHolder hydrant : mHydrants) {
final String hydrant_type = hydrant.getHydrantType();
final String hydrant_icon_path = hydrant.getIconPath();
double latitude = hydrant.getLatitude();
double longitude = hydrant.getLongitude();
final LatLng position = new LatLng(latitude, longitude);
final String address = hydrant.getAddress();
final String addressNumber = hydrant.getAddressNumber();
final String addressremark = hydrant.getAddressRemark();
final String remark = hydrant.getRemark();
// Log.d(TAG, hydrant.toString());
BitmapDescriptor icon = BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED);
if (!hydrant_icon_path.isEmpty()) {
File iconfile = new File(hydrant_icon_path);
if (iconfile.exists()) {
BitmapDescriptor loaded_icon = BitmapDescriptorFactory
.fromPath(hydrant_icon_path);
if (loaded_icon != null) {
icon = loaded_icon;
} else {
Log.e(TAG, "loaded_icon was null");
}
} else {
Log.e(TAG, "iconfile did not exist: "
+ hydrant_icon_path);
}
} else {
Log.e(TAG, "iconpath was empty on hydrant type: "
+ hydrant_type);
}
StringBuffer snippet = new StringBuffer();
if (!address.isEmpty())
snippet.append("\n" + address + " " + addressNumber);
if (addressremark.isEmpty())
snippet.append("\n" + addressremark);
if (!remark.isEmpty())
snippet.append("\n" + remark);
markers.add(new MarkerOptions().position(position)
.title(hydrant_type).snippet(snippet.toString())
.icon(icon));
publishProgress(markers.size());
}
return markers;
}
// Update the progress
#Override protected void onProgressUpdate(Integer... values) {
if (mLoadHydrantsToMapTaskCallback != null) {
mLoadHydrantsToMapTaskCallback.onProgressUpdate(values[0]);
}
}
#Override protected void onCancelled() {
if (mLoadHydrantsToMapTaskCallback != null) {
mLoadHydrantsToMapTaskCallback.onCancelled();
}
}
// after executing the code in the thread
#Override protected void onPostExecute(List<MarkerOptions> markers) {
for (MarkerOptions marker : markers) {
if (marker != null && map != null)
map.addMarker(marker);
}
if (mLoadHydrantsToMapTaskCallback != null) {
mLoadHydrantsToMapTaskCallback.onPostExecute();
}
}
}
}
My dialog_progress_task layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:maxHeight="10dip"
android:minHeight="10dip"
android:progress="0"
android:progressDrawable="#drawable/progress_orange" />
</LinearLayout>
And finally the code I use to add it:
#Override public void loadHydrantsToMap(List<HydrantHolder> hydrants,
GoogleMap map) {
LoadHydrantsToMapTaskFragment loadHydrantsFragment;
if (fm != null) {
FragmentTransaction ft = fm.beginTransaction();
loadHydrantsFragment = (LoadHydrantsToMapTaskFragment) fm
.findFragmentByTag(LoadHydrantsToMapTaskFragment.TAG);
if (loadHydrantsFragment != null) {
Log.i("Attatching LoadHydrantsToMapTaskFragment");
ft.attach(loadHydrantsFragment);
} else {
loadHydrantsFragment = LoadHydrantsToMapTaskFragment
.newInstance(hydrants, map);
Log.i("Adding new LoadHydrantsToMapTaskFragment");
ft.add(loadHydrantsFragment, LoadHydrantsToMapTaskFragment.TAG);
}
ft.commit();
}
}

Que multiple dialogFragments to display one after the other

If I have an ArrayList<DialogFragment> containing DialogFragments of unknown size, how can I programmatically cue up each one so that once the first one is dismissed, the next one is shown, and so on?
for (int i = 0; i < tutorialViews.size(); i++) {
final int current = i;
DialogFragment someDialogFragment = dialogFragmentList.get(i);
if (i == 0) {
someDialogFragment .show(activity.get().getSupportFragmentManager(), "some_dialog_fragment");
}
if (i + 1 != dialogFragmentList.size() - 1) {
someDialogFragment.getDialog().setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
dialogFragmentList.get(current + 1).show(activity.get().getSupportFragmentManager(), "more_dialog_fragments");
}
});
}
}
Unforunately this doesn't work since the dialog object within a dialogFragment isn't instantiated yet, giving a nullPointerException for the getDialog() call
Create your own interface to callback when the fragmentdialog is closed.
OnDialogFragHide mListener;
public interface OnDialogFragHide {
public void onFragmentDismissed();
}
public void setOnFragDismissedListener(OnDialogFragHide listener) {
mListener = listener;
}
Register the interface in the for loop
if (i == 0) {
tutorial.show(activity.get().getSupportFragmentManager(), "smoking_hawt");
}
if (i != tutorialViews.size() - 1) {
tutorial.setOnFragDismissedListener(new OnDialogFragHide() {
#Override
public void onFragmentDismissed() {
tutorialViews.get(current + 1).show(activity.get().getSupportFragmentManager(), "some_tag");
}
});
}
Call upon the listener whenever the fragment is closed (i.e. in the FragmentDialog's onDismiss() and onCancel() methods, NOT the DIALOG's onDismiss / onCancel listeners.
#Override
public void onDismiss(DialogInterface dialog) {
if (mListener != null && !dismissed) {
dismissed = true;
mListener.onFragmentDismissed();
} else {
Log.e(TAG, "DialogFragmentDismissed not set");
}
super.onDismiss(dialog);
}
#Override
public void onCancel(DialogInterface dialog) {
if (mListener != null && dismissed) {
dismissed = true;
mListener.onFragmentDismissed();
} else {
Log.e(TAG, "DialogFragmentDismissed not set");
}
super.onCancel(dialog);
}
the dismissed boolean is for good measure to make the listener isn't called twice.

Android: PullToRefresh ListView not showing

I have used Chris Banes implementation of pull to refresh list view for my app. The problem is if I set visibility for list view as gone or invisible and make it visible in java code, the list doesn't shows up. On the other hand, if I set its visibility as visible or don't set its visibility, every thing works fine. My requirement is such that I have two list views in the same activity. I have to set the visibility as one will appear first once it get data from server. The other will appear on search function. I had set the visibility for search result's listview as gone in the xml code, and making it visible only once it gets search results. Despite using setVisibility() for this listview, it never shows up screen. I had checked server response as well. It is showing search result on logcat.
I am posting my code below:
Code Snippet from Activity
//The result from this async task will populate the first list view
if(NetworkConnection.isOnline(MainCategory.this))
{
new MainMenuAsyncTask(dataUrl, MainCategory.this, listMainMenu, false).execute();
}
else
{
Log.v(TAG, "no network available");
SeattleNightLifeUtility.OpenWiFiDialog(MainCategory.this, getResources().getString(R.string.no_internet_msg));
}
loadListView();
//This will populate the list view that I have created for search results
_txtAutoSearch.setOnEditorActionListener(new TextView.OnEditorActionListener()
{
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
String term = _txtAutoSearch.getText().toString().trim();
if(! term.equals(""))
{
SeattleNightLifeUtility.hideSoftKeyboard(MainCategory.this, _txtAutoSearch);
if(NetworkConnection.isOnline(MainCategory.this))
{
search(term, false);
}
else
{
SeattleNightLifeUtility.OpenWiFiDialog(MainCategory.this, getResources().getString(R.string.no_internet_msg));
}
}
return true;
}//onEditorAction
});
listMainMenu.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener()
{
#Override
public void onRefresh()
{
if(NetworkConnection.isOnline(MainCategory.this))
{
new MainMenuAsyncTask(dataUrl, MainCategory.this, listMainMenu, true).execute();
}
else
{
SeattleNightLifeUtility.OpenWiFiDialog(MainCategory.this, getResources().getString(R.string.no_internet_msg));
}
}
});
listViewSearch.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener()
{
public void onRefresh()
{
if(NetworkConnection.isOnline(MainCategory.this))
{
search(_txtAutoSearch.getText().toString().trim(), true);
}
else
{
SeattleNightLifeUtility.OpenWiFiDialog(MainCategory.this, getResources().getString(R.string.no_internet_msg));
}
}
});
Search result Async Task
public class GetSearchAsyncTask extends AsyncTask<Void, Void, String>
{
Context ctx;
ProgressDialog pd;
PullToRefreshListView listViewSearch;
public static final String TAG = "GetSearchAsyncTask";
public static ArrayList<SearchDAO> searchArrayList;
private String term, callingclass;
private TextView txtNoData;
boolean flag;
public GetSearchAsyncTask(String term, Context ctx,
PullToRefreshListView listViewSearch, TextView txtNoData,
String callingclass, boolean flag)
{
this.term = term;
this.ctx = ctx;
this.listViewSearch = listViewSearch;
this.txtNoData = txtNoData;
this.callingclass = callingclass;
this.flag = flag;
}//Constructor
#Override
protected void onPreExecute()
{
if(flag == false)
{
pd = new ProgressDialog(ctx);
pd.setMessage(ctx.getResources().getString(R.string.please_wait));
pd.show();
}
}//onPreExecute
protected String doInBackground(Void... params)
{
String parsed = ServerConnection.getSearchedData(term);
try
{
if(flag == true)
{
Log.v(TAG, "doInBackground isListRefreshed is true");
Thread.sleep(2000);
}
}
catch(Exception e){}
return parsed;
}//doInBackground
#Override
protected void onPostExecute(String result)
{
searchArrayList = ParsedSearchData.getSearchedData(result);
listViewSearch.setVisibility(View.VISIBLE);
if(searchArrayList != null && searchArrayList.size() > 0)
{
Log.v(TAG, "searcharraylist not null");
for(int i = 0; i < searchArrayList.size(); i++)
{
Log.v(TAG, "Name: "+searchArrayList.get(i).getMerchant());
}
SearchAdapter mSearchAdapter = new SearchAdapter(ctx, searchArrayList);
mSearchAdapter.notifyDataSetChanged();
listViewSearch.setAdapter(mSearchAdapter);
if(callingclass.equals("EventActivity"))
{
Log.v(TAG, "callingclass EventActivity");
if(txtNoData.getVisibility() == View.VISIBLE)
{
Log.v(TAG, "txtNoData VISIBLE");
txtNoData.setVisibility(View.GONE);
}
if(((EventsActivity)ctx).txtNoEvent.getVisibility() == View.VISIBLE)
{
Log.v(TAG, "txtNoEvent VISIBLE");
((EventsActivity)ctx).txtNoEvent.setVisibility(View.GONE);
}
}
else
{
Log.v(TAG, "callingclass not EventActivity");
if(txtNoData.getVisibility() == View.VISIBLE)
{
Log.v(TAG, "else loop txtNoData VISIBLE");
txtNoData.setVisibility(View.GONE);
}
if(listViewSearch.getVisibility() == View.VISIBLE)
{
Log.v(TAG, "listViewSearch VISIBLE");
}
else
{
Log.v(TAG, "listViewSearch INVISIBLE");
}
}
}
else
{
Log.v(TAG, "searcharraylist null");
if(callingclass.equals("EventActivity"))
{
Log.v(TAG, "callingclass EventActivity");
txtNoData.setVisibility(View.VISIBLE);
listViewSearch.setVisibility(View.GONE);
if(((EventsActivity)ctx).txtNoEvent.getVisibility() == View.VISIBLE)
{
Log.v(TAG, "searcharraylist null else txtNoEvent VISIBLE");
((EventsActivity)ctx).txtNoEvent.setVisibility(View.GONE);
}
}
else
{
Log.v(TAG, "callingclass not EventActivitysearcharraylist null else txtNoEvent VISIBLE");
txtNoData.setVisibility(View.VISIBLE);
listViewSearch.setVisibility(View.GONE);
}
}
if(flag == false)
{
if(pd != null)
{
Log.v(TAG, "onPostExecute pd not null");
if(pd.isShowing())
{
Log.v(TAG, "onPostExecute pd is showing");
pd.dismiss();
}
}
}
else
{
listViewSearch.onRefreshComplete();
}
}//onPostExecute
}
Search Method
protected void search(String term, boolean result)
{
listMainMenu.setVisibility(View.GONE);
//listViewSearch.setVisibility(View.VISIBLE);
new GetSearchAsyncTask(term, MainCategory.this, listViewSearch , txtNoData, "MainCategory", result).execute();
}//search
Earlier I was setting visibility of in the XML as gone and in java code, I was making it VISIBLE. At that time, the list didn't showed up. When I removed the visibility attribute from XML layout file, and only set it in java code with setVisibility(), it worked perfect. I couldn't figured out the reason behind this. May be, I need to take a look at the implementation of library so that I find where did I went wrong. But, for the time being, this is what worked for me.

Categories

Resources