java.lang.classcastexception fragment cannot be cast to android.app.activity - android

I get error at runtime:
java.lang.classcastexception com.android.homework.AllAppsFragment cannot be cast to android.app.activity. Whats is wrong with this code?
04-26 08:42:02.065: E/AndroidRuntime(1755):
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.android.homework/com.andorid.homework.AllAppsFragment}:
java.lang.ClassCastException: com.andorid.homework.AllAppsFragment
cannot be cast to android.app.Activity
public class AllAppsFragment extends ListFragment {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
private HashMap<ApplicationInfo, Float> appRating = null;
private SharedPreferences sh = null;
private SharedPreferences.Editor preferencesEditor = null;
public static final String MY_PREFERENCES = "myPreferences";
private OnItemSelectedListener listener;
public interface OnItemSelectedListener {
public void onRssItemSelected(String link);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof OnItemSelectedListener) {
listener = (OnItemSelectedListener) activity;
} else {
throw new ClassCastException(activity.toString()
+ " must implemenet MyListFragment.OnItemSelectedListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
packageManager = getActivity().getBaseContext().getPackageManager();
new LoadApplications().execute();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_main, null);
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
inflater.inflate(R.menu.menu, menu);
super.onCreateOptionsMenu(menu, inflater);
// return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
boolean result = true;
switch (item.getItemId()) {
case R.id.menu_about: {
displayAboutDialog();
break;
}
default: {
result = super.onOptionsItemSelected(item);
break;
}
}
return result;
}
private void displayAboutDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity().getBaseContext());
builder.setTitle(getString(R.string.about_title));
builder.setItems(new CharSequence[] { getString(R.string.sort_lex),
getString(R.string.sortuj_lex_desc),
getString(R.string.sort_ranked),
getString(R.string.sort_ranked_desc) },
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
sh = getActivity().getBaseContext()
.getSharedPreferences(MY_PREFERENCES,
Context.MODE_PRIVATE);
preferencesEditor = sh.edit();
switch (which) {
case 0:
listadaptor.sortLex();
preferencesEditor.putInt("sort_type", 1);
preferencesEditor.commit();
dialog.cancel();
break;
case 1:
listadaptor.sortLexDesc();
preferencesEditor.putInt("sort_type", 2);
preferencesEditor.commit();
dialog.cancel();
break;
case 2:
listadaptor.sortRating();
preferencesEditor.putInt("sort_type", 3);
preferencesEditor.commit();
dialog.cancel();
break;
case 3:
listadaptor.sortRaingDesc();
preferencesEditor.putInt("sort_type", 4);
preferencesEditor.commit();
dialog.cancel();
break;
}
}
});
builder.create().show();
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ApplicationInfo app = applist.get(position);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(getActivity().getBaseContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getActivity().getBaseContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
private List<ApplicationInfo> checkForLaunchIntent(
List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (null != packageManager
.getLaunchIntentForPackage(info.packageName)) {
applist.add(info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager
.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(
getActivity().getBaseContext(), R.layout.snippet_list_row,
applist);
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
sh = getActivity().getBaseContext().getSharedPreferences(
MY_PREFERENCES, Context.MODE_PRIVATE);
int sortOrder = sh.getInt("sort_type", 0);
switch (sortOrder) {
case 1:
listadaptor.sortLex();
break;
case 2:
listadaptor.sortLexDesc();
break;
case 3:
listadaptor.sortRating();
break;
case 4:
listadaptor.sortRaingDesc();
break;
default:
}
setListAdapter(listadaptor);
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(getActivity().getBaseContext(),
null, "Ładujemy!!");
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
HostActivity
public class HostActivity extends Activity implements OnItemSelectedListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_fragment);
}
#Override
public void onRssItemSelected(String link) {
// TODO Auto-generated method stub
}
}
main_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<fragment
android:id="#+id/country_fragment"
android:name="com.android.homework.AllAppsFragment"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>

The exception is thrown on starting the app. It attempts to start the main activity but, for some reason, is attempting to start the fragment. It casts it to an Activity but Fragment does not extend Activity. What you have done is added the fragment as an activity in the AndroidManifest.xml. Change this to HostActivity.

Related

Password Manager autofilling in installed applications

I am developing a password manager app. I need auto filling in login section of installed apps whereby I have got a list of all installed apps in my activity. On click in the list I want that particular item to auto fill its login section. I tried it using content provider, but all in vain.
Below is the code containing list of installed apps.
public class MainActivity extends ListActivity {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
packageManager = getPackageManager();
new LoadApplications().execute();
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ApplicationInfo app = applist.get(position);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
// displayAboutDialog();
if (null != intent) {
startActivity(intent);
//intent.FILL_IN_DATA;
}
} catch (ActivityNotFoundException e) {
Toast.makeText(MainActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();}
}
private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {
applist.add(info);
// displayAboutDialog();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(MainActivity.this,
R.layout.list_row, applist);
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
setListAdapter(listadaptor);
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(MainActivity.this, null,
"Loading application info...");
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}`

Listview not updating (notify datasetchanged)

I'm trying to update my listview after I change the 'dataset' but it doesn't, unless I manually refresh the view or refresh the activity.
This doesn't work:
runOnUiThread(new Runnable() {
public void run() {
entriesListAdapter.notifyDataSetChanged();
}
});
While this does:
handler.postDelayed(new Runnable() {
#Override
public void run() {
onCreate(null);
entriesListAdapter.notifyDataSetChanged();
}
}, 1000);
But this is absolutely not the right way to do it. Am I using notifydatasetchanged wrong?
My whole activity:
package app.wordpress;
import app.wordpress.service.FetcherService;
import someontherimports
public class EntriesListActivity extends ListActivity {
private static final int CONTEXTMENU_REFRESH_ID = 4;
private static final int CONTEXTMENU_MARKASREAD_ID = 6;
private static final int ACTIVITY_APPLICATIONPREFERENCES_ID = 1;
private static final Uri CANGELOG_URI = Uri.parse("http://wordpress.com");
private static final int CONTEXTMENU_MARKASUNREAD_ID = 7;
private static final int CONTEXTMENU_DELETE_ID = 8;
private static final int CONTEXTMENU_COPYURL = 9;
private static final int DIALOG_ABOUT = 7;
public static final String EXTRA_SHOWREAD = "show_read";
public static final String EXTRA_SHOWFEEDINFO = "show_feedinfo";
public static final String EXTRA_AUTORELOAD = "autoreload";
private static final String[] FEED_PROJECTION = {FeedData.FeedColumns.NAME,
FeedData.FeedColumns.URL,
FeedData.FeedColumns.ICON
};
private Uri uri;
private EntriesListAdapter entriesListAdapter;
private byte[] iconBytes;
#Override
protected void onCreate(Bundle savedInstanceState) {
if (MainTabActivity.isLightTheme(this)) {
setTheme(R.style.Theme_Light);
}
super.onCreate(savedInstanceState);
String title = null;
iconBytes = null;
Intent intent = getIntent();
long feedId = intent.getLongExtra(FeedData.FeedColumns._ID, 0);
if (feedId > 0) {
Cursor cursor = getContentResolver().query(FeedData.FeedColumns.CONTENT_URI(feedId), FEED_PROJECTION, null, null, null);
if (cursor.moveToFirst()) {
title = cursor.isNull(0) ? cursor.getString(1) : cursor.getString(0);
iconBytes = cursor.getBlob(2);
}
cursor.close();
}
if (!MainTabActivity.POSTGINGERBREAD && iconBytes != null && iconBytes.length > 0) { // we cannot insert the icon here because it would be overwritten, but we have to reserve the icon here
if (!requestWindowFeature(Window.FEATURE_LEFT_ICON)) {
iconBytes = null;
}
}
setContentView(R.layout.entries);
uri = intent.getData();
entriesListAdapter = new EntriesListAdapter(this, uri, intent.getBooleanExtra(EXTRA_SHOWFEEDINFO, false), intent.getBooleanExtra(EXTRA_AUTORELOAD, false));
setListAdapter(entriesListAdapter);
if (title != null) {
setTitle(title);
}
if (iconBytes != null && iconBytes.length > 0) {
int bitmapSizeInDip = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24f, getResources().getDisplayMetrics());
Bitmap bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.length);
if (bitmap != null) {
if (bitmap.getHeight() != bitmapSizeInDip) {
bitmap = Bitmap.createScaledBitmap(bitmap, bitmapSizeInDip, bitmapSizeInDip, false);
}
if (MainTabActivity.POSTGINGERBREAD) {
CompatibilityHelper.setActionBarDrawable(this, new BitmapDrawable(bitmap));
} else {
setFeatureDrawable(Window.FEATURE_LEFT_ICON, new BitmapDrawable(bitmap));
}
}
}
if (RSSOverview.notificationManager != null) {
RSSOverview.notificationManager.cancel(0);
}
getListView().setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
menu.setHeaderTitle(((TextView) ((AdapterView.AdapterContextMenuInfo) menuInfo).targetView.findViewById(android.R.id.text1)).getText());
menu.add(0, CONTEXTMENU_REFRESH_ID, Menu.NONE, R.string.contextmenu_refresh);
menu.add(0, CONTEXTMENU_MARKASREAD_ID, Menu.NONE, R.string.contextmenu_markasread).setIcon(android.R.drawable.ic_menu_manage);
menu.add(0, CONTEXTMENU_MARKASUNREAD_ID, Menu.NONE, R.string.contextmenu_markasunread).setIcon(android.R.drawable.ic_menu_manage);
menu.add(0, CONTEXTMENU_DELETE_ID, Menu.NONE, R.string.contextmenu_delete).setIcon(android.R.drawable.ic_menu_delete);
menu.add(0, CONTEXTMENU_COPYURL, Menu.NONE, R.string.contextmenu_copyurl).setIcon(android.R.drawable.ic_menu_share);
}
});
}
#Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
TextView textView = (TextView) view.findViewById(android.R.id.text1);
textView.setTypeface(Typeface.DEFAULT);
textView.setEnabled(false);
view.findViewById(android.R.id.text2).setEnabled(false);
entriesListAdapter.neutralizeReadState();
startActivity(new Intent(Intent.ACTION_VIEW, ContentUris.withAppendedId(uri, id)).putExtra(EXTRA_SHOWREAD, entriesListAdapter.isShowRead()).putExtra(FeedData.FeedColumns.ICON, iconBytes));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.entrylist, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.setGroupVisible(R.id.menu_group_0, entriesListAdapter.getCount() > 0);
return true;
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_markasread: {
new Thread() { // the update process takes some time
public void run() {
getContentResolver().update(uri, RSSOverview.getReadContentValues(), null, null);
}
}.start();
entriesListAdapter.markAsRead();
break;
}
case R.id.menu_markasunread: {
new Thread() { // the update process takes some time
public void run() {
getContentResolver().update(uri, RSSOverview.getUnreadContentValues(), null, null);
}
}.start();
entriesListAdapter.markAsUnread();
break;
}
case R.id.menu_hideread: {
if (item.isChecked()) {
item.setChecked(false).setTitle(R.string.contextmenu_hideread).setIcon(android.R.drawable.ic_menu_close_clear_cancel);
entriesListAdapter.showRead(true);
} else {
item.setChecked(true).setTitle(R.string.contextmenu_showread).setIcon(android.R.drawable.ic_menu_view);
entriesListAdapter.showRead(false);
}
break;
}
case R.id.menu_deleteread: {
new Thread() { // the delete process takes some time
public void run() {
String selection = Strings.READDATE_GREATERZERO+Strings.DB_AND+" ("+Strings.DB_EXCUDEFAVORITE+")";
getContentResolver().delete(uri, selection, null);
FeedData.deletePicturesOfFeed(EntriesListActivity.this, uri, selection);
runOnUiThread(new Runnable() {
public void run() {
entriesListAdapter.getCursor().requery();
}
});
}
}.start();
break;
}
case R.id.menu_deleteallentries: {
Builder builder = new AlertDialog.Builder(this);
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setTitle(R.string.contextmenu_deleteallentries);
builder.setMessage(R.string.question_areyousure);
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new Thread() {
public void run() {
getContentResolver().delete(uri, Strings.DB_EXCUDEFAVORITE, null);
runOnUiThread(new Runnable() {
public void run() {
entriesListAdapter.getCursor().requery();
}
});
}
}.start();
}
});
builder.setNegativeButton(android.R.string.no, null);
builder.show();
break;
}
case CONTEXTMENU_MARKASREAD_ID: {
long id = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id;
getContentResolver().update(ContentUris.withAppendedId(uri, id), RSSOverview.getReadContentValues(), null, null);
entriesListAdapter.markAsRead(id);
break;
}
case CONTEXTMENU_MARKASUNREAD_ID: {
long id = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id;
getContentResolver().update(ContentUris.withAppendedId(uri, id), RSSOverview.getUnreadContentValues(), null, null);
entriesListAdapter.markAsUnread(id);
break;
}
case CONTEXTMENU_DELETE_ID: {
long id = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id;
getContentResolver().delete(ContentUris.withAppendedId(uri, id), null, null);
FeedData.deletePicturesOfEntry(Long.toString(id));
entriesListAdapter.getCursor().requery(); // he have no other choice
break;
}
case CONTEXTMENU_COPYURL: {
((ClipboardManager) getSystemService(CLIPBOARD_SERVICE)).setText(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).targetView.getTag().toString());
break;
}
case R.id.menu_settings: {
startActivityForResult(new Intent(this, ApplicationPreferencesActivity.class), ACTIVITY_APPLICATIONPREFERENCES_ID);
break;
}
case R.id.menu_about: {
showDialog(DIALOG_ABOUT);
break;
}
case R.id.menu_refresh: {
new Thread() {
public void run() {
sendBroadcast(new Intent(Strings.ACTION_REFRESHFEEDS).putExtra(Strings.SETTINGS_OVERRIDEWIFIONLY, PreferenceManager.getDefaultSharedPreferences(EntriesListActivity.this).getBoolean(Strings.SETTINGS_OVERRIDEWIFIONLY, false)));
}
}.start();
runOnUiThread(new Runnable() {
public void run() {
entriesListAdapter.notifyDataSetChanged();
}
});
break;
}
}
return true;
}
#Override
protected void onResume()
{
super.onResume();
setProgressBarIndeterminateVisibility(isCurrentlyRefreshing());
registerReceiver(refreshReceiver, new IntentFilter("app.wordpress.REFRESH"));
}
#Override
protected void onPause()
{
unregisterReceiver(refreshReceiver);
super.onPause();
}
private BroadcastReceiver refreshReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
setProgressBarIndeterminateVisibility(true);
}
};
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog;
switch (id) {
case DIALOG_ABOUT: {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(android.R.drawable.ic_dialog_info);
builder.setTitle(R.string.menu_about);
MainTabActivity.INSTANCE.setupLicenseText(builder);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setNeutralButton(R.string.changelog, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Intent.ACTION_VIEW, CANGELOG_URI));
}
});
return builder.create();
}
default: dialog = null;
}
return dialog;
}
private boolean isCurrentlyRefreshing()
{
ActivityManager manager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service: manager.getRunningServices(Integer.MAX_VALUE)) {
if (FetcherService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
Are you referring to this block of code in your Activity?
case R.id.menu_refresh: {
new Thread() {
public void run() {
sendBroadcast(new Intent(Strings.ACTION_REFRESHFEEDS).putExtra(Strings.SETTINGS_OVERRIDEWIFIONLY, PreferenceManager.getDefaultSharedPreferences(EntriesListActivity.this).getBoolean(Strings.SETTINGS_OVERRIDEWIFIONLY, false)));
}
}.start();
runOnUiThread(new Runnable() {
public void run() {
entriesListAdapter.notifyDataSetChanged();
}
});
break;
If so, the problem is likely that the call to runOnUiThread() is not actually inside of the Thread you created, it's called on the main thread.
The way this code is structured, upon selecting refresh, the background thread is created to fire a broadcast Intent (not necessary, BTW, because that is also an asynchronous process...it returns immediately) and then notifyDataSetChanged() is immediately run after that (because runOnUiThread() when called from the main thread just executes the Runnable right away).
So you are sending a broadcast and updating the adapter at basically the same time...not much time for anything to have actually changed in that period. If you were expecting sendBroadcast() to block and return after some receiver had processed it, this is not the case.
In you contentProvider, you should call contentResolver.notifyChange to notify the adapter that there have been a change to the data provided by the contentResolver, this will update the listView for you.

If Progressdialog is not showing (android)

I have a ProgressDialog, and I want to do something when the dialog dissappears (but I do not want put my action after the progressdialog.dismiss).
Is it possible to:
----> if No ---> Do something
Check if dialog is showing
----> if Yes
/|\ |
| \|/
--------------------- Wait
Don't think to difficult, I just want to perform an action, but only if there is no dialog, and if there is one, to perform the action when the dialog is done.
Thank you!
EDIT: My activity:
import verymuchimportshere..
public class ScroidWallpaperGallery extends Activity {
private WallpaperGalleryAdapter wallpaperGalleryAdapter;
private final WallpaperManager wallpaperManager;
private final ICommunicationDAO communicationDAO;
private final IFavouriteDAO favouriteDAO;
private final List<Integer> preloadedList;
private Wallpaper selectedWallpaper;
private static final int PICK_CONTACT = 0;
private static final int DIALOG_ABOUT = 0;
public ScroidWallpaperGallery() {
super();
if (!DependencyInjector.isInitialized()) {
DependencyInjector.init(this);
}
this.wallpaperManager = DependencyInjector.getInstance(WallpaperManager.class);
this.communicationDAO = DependencyInjector.getInstance(ICommunicationDAO.class);
this.favouriteDAO = DependencyInjector.getInstance(IFavouriteDAO.class);
this.preloadedList = new ArrayList<Integer>();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
this.initGallery();
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage(this.getString(R.string.loadingText));
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
else {
SharedPreferences settings = getSharedPreferences("firstrun", MODE_PRIVATE);
if (settings.getBoolean("isFirstRun", true)) {
new AlertDialog.Builder(this).setTitle("How to").setMessage("Long press item to add/remove from favorites.").setNeutralButton("Ok", null).show();
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("isFirstRun", false);
editor.commit();
}
}
if (this.wallpaperGalleryAdapter != null) {
this.updateGalleryAdapter();
return;
}
AdView adView = (AdView)this.findViewById(R.id.adView);
adView.loadAd(new AdRequest());
new FillGalleryTask(progressDialog, this).start();
}
private void updateGalleryAdapter() {
this.updateGalleryAdapter(this.wallpaperManager.getWallpapers());
}
private synchronized void updateGalleryAdapter(Wallpaper[] wallpapers) {
this.wallpaperGalleryAdapter = new WallpaperGalleryAdapter(this, wallpapers, this.wallpaperManager);
Gallery gallery = (Gallery)this.findViewById(R.id.gallery);
gallery.setAdapter(this.wallpaperGalleryAdapter);
}
private void initGallery() {
Gallery gallery = (Gallery)this.findViewById(R.id.gallery);
gallery.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Wallpaper wallpaper = (Wallpaper)parent.getItemAtPosition(position);
showPreviewActivity(wallpaper);
}
});
gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, final int position, long id) {
selectedWallpaper = (Wallpaper)wallpaperGalleryAdapter.getItem(position);
new Thread(new Runnable() {
#Override
public void run() {
preloadThumbs(wallpaperGalleryAdapter.getWallpapers(), (position + 1), 3);
}
}).start();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
selectedWallpaper = null;
}
});
this.registerForContextMenu(gallery);
}
private void showPreviewActivity(Wallpaper wallpaper) {
WallpaperPreviewActivity.showPreviewActivity(this, wallpaper);
}
private void preloadThumbs(Wallpaper[] wallpapers, int index, int maxCount) {
for (int i = index; (i < (index + maxCount)) && (i < wallpapers.length); i++) {
if (this.preloadedList.contains(i)) {
continue;
}
try {
this.wallpaperManager.getThumbImage(wallpapers[i]);
this.preloadedList.add(i);
}
catch (ClientProtocolException ex) {
// nothing to do - image will be loaded on select
}
catch (IOException ex) {
// nothing to do - image will be loaded on select
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if (this.selectedWallpaper == null
|| !(v instanceof Gallery)) {
return;
}
MenuInflater menuInflater = new MenuInflater(this);
menuInflater.inflate(R.menu.gallery_context_menu, menu);
if (this.favouriteDAO.isFavourite(this.selectedWallpaper.getId())) {
menu.findItem(R.id.galleryRemoveFavouriteMenuItem).setVisible(true);
}
else {
menu.findItem(R.id.galleryAddFavouriteMenuItem).setVisible(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if (this.selectedWallpaper == null) {
return false;
}
switch (item.getItemId()) {
case R.id.galleryAddFavouriteMenuItem:
this.favouriteDAO.add(this.selectedWallpaper.getId());
return true;
case R.id.galleryRemoveFavouriteMenuItem:
this.favouriteDAO.remove(this.selectedWallpaper.getId());
return true;
}
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.aboutMenuItem:
this.showDialog(DIALOG_ABOUT);
return true;
case R.id.settingsMenuItem:
this.startActivity(new Intent(this, SettingsActivity.class));
return true;
case R.id.recommendMenuItem:
this.recommendWallpaper();
return true;
case R.id.favouritesMenuItem:
FavouriteListActivity.showFavouriteListActivity(this);
return true;
case R.id.closeMenuItem:
this.finish();
return true;
}
return false;
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ABOUT:
return new AboutDialog(this);
default:
return null;
}
}
private void recommendWallpaper() {
if (this.selectedWallpaper == null) {
return;
}
Intent intent = new Intent(Intent.ACTION_PICK, People.CONTENT_URI);
this.startActivityForResult(intent, PICK_CONTACT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_CONTACT:
this.onPickContactActivityResult(resultCode, data);
break;
}
}
private void onPickContactActivityResult(int resultCode, Intent data) {
if (resultCode == 0) {
return;
}
Communication[] communications = this.communicationDAO.getCommunications(data.getData());
if (communications.length < 1) {
AlertDialogFactory.showInfoMessage(this, R.string.infoText, R.string.noCommunicationFoundInfoText);
return;
}
CommunicationChooseDialog dialog = new CommunicationChooseDialog(this, communications, new CommunicationChosenListener() {
#Override
public void onCommunicationChosen(Communication communication) {
handleOnCommunicationChosen(communication);
}
});
dialog.show();
}
private void handleOnCommunicationChosen(Communication communication) {
Wallpaper wallpaper = this.selectedWallpaper;
if (communication.getType().equals(Communication.Type.Email)) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { communication.getValue() });
intent.putExtra(Intent.EXTRA_SUBJECT, getBaseContext().getString(R.string.applicationName));
intent.putExtra(Intent.EXTRA_TEXT, String.format(getBaseContext().getString(R.string.recommendEmailPattern),
wallpaper.getWallpaperUrl()));
intent.setType("message/rfc822");
this.startActivity(intent);
}
else if (communication.getType().equals(Communication.Type.Mobile)) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra("address", communication.getValue());
intent.putExtra("sms_body", String.format(getBaseContext().getString(R.string.recommendSmsPattern),
wallpaper.getWallpaperUrl()));
intent.setType("vnd.android-dir/mms-sms");
this.startActivity(intent);
}
}
private class FillGalleryTask extends LongTimeRunningOperation<Wallpaper[]> {
private final Context context;
public FillGalleryTask(Dialog progressDialog, Context context) {
super(progressDialog);
this.context = context;
}
#Override
public void afterOperationSuccessfullyCompleted(Wallpaper[] result) {
updateGalleryAdapter(result);
}
#Override
public void handleUncaughtException(Throwable ex) {
if (ex instanceof WallpaperListReceivingException) {
AlertDialogFactory.showErrorMessage(this.context,
R.string.errorText,
ex.getMessage(),
new ShutDownAlertDialogOnClickListener());
}
else if (ex instanceof IOException) {
AlertDialogFactory.showErrorMessage(this.context,
R.string.errorText,
R.string.downloadException,
new ShutDownAlertDialogOnClickListener());
}
else {
throw new RuntimeException(ex);
}
}
#Override
public Wallpaper[] onRun() throws Exception {
// retrieving available wallpapers from server
wallpaperManager.loadAvailableWallpapers(getBaseContext());
Wallpaper[] wallpapers = wallpaperManager.getWallpapers();
// preloading first 3 thumbs
preloadThumbs(wallpapers, 0, 3);
return wallpapers;
}
}
private class ShutDownAlertDialogOnClickListener implements DialogInterface.OnClickListener {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
}
}
Try this,
private void doSomethingWhenProgressNotShown() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
//is running
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doSomethingWhenProgressNotShown();
}
}, 500);
}
//isnt running- do something here
}
I think you can use this code:
if (mProgressDialog != null && mProgressDialog.isShowing()) {
//is running
}
//isnt running
Or you can set listeners:
mProgressDialog.setOnCancelListener(listener);
mProgressDialog.setOnDismissListener(listener);

Android: Execute http requests via Service

I have a trouble with getting Activity(Nullpointerexception) after that I have rotate screen and received callback from AsyncTask to update my views of the fragment. If I wont change orientation then everything is OK(but not all the time, sometimes this bug appears)
My main activity:
public class MainActivity extends SherlockFragmentActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pager_layout);
fm = getSupportFragmentManager();
fm.addOnBackStackChangedListener(this);
session = new SessionManager(getApplicationContext());
if (session.isAuthorizated()) {
disableTabs();
FragmentTransaction ft = fm.beginTransaction();
if (session.termsAndConditions()) {
ft.replace(android.R.id.content, new TermsAndConditionsFragment(), "terms-and-conditions").commit();
}
}
} else {
enableTabs();
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(actionBar.newTab().setText("Log in"), LoginFragment.class, null);
mTabsAdapter.addTab(actionBar.newTab().setText("Calculator"), CalculatorFragment.class, null);
}
}
That`s my fragment:
public class TermsAndConditionsFragment extends SherlockFragment implements OnClickListener, OnTouchListener, OnEditorActionListener, ValueSelectedListener, AsyncUpdateViewsListener {
private static final String TAG = "TermsAndConditionsFragment";
private TermsAndConditionsManager termsAndConditionsM;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prepareData();
}
public void prepareData() {
if (getSherlockActivity() == null)
Log.d(TAG, "Activity is null");
termsAndConditionsM = new TermsAndConditionsManager(getSherlockActivity().getApplicationContext());
termsAndConditions = termsAndConditionsM.getTermsAndConditions();
...
// some stuff
...
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = init(inflater, container);
return rootView;
}
private View init(LayoutInflater inflater, ViewGroup container) {
rootView = inflater.inflate(R.layout.fragment_terms_and_conditions, container, false);
//bla bla bla
return rootView;
}
public void updateTermsAndConditionsView() {
//update views here
}
#Override
public void onClick(View v) {
ft = fm.beginTransaction();
switch (v.getId()) {
case R.id.etHowMuch:
d = NumberPaymentsPickerFragment.newInstance(getSherlockActivity(), Integer.valueOf(howMuch.replace("£", "")), 0);
d.setValueSelectedListener(this);
d.show(getFragmentManager(), Const.HOW_MUCH);
break;
}
}
#Override
public void onValueSelected() {
Bundle args = new Bundle();
...
ExecuteServerTaskBackground task = new ExecuteServerTaskBackground(getSherlockActivity());
task.setAsyncUpdateViewsListener(this);
task.action = ServerAPI.GET_TERMS_AND_CONDITIONS;
task.args = args;
task.execute();
}
#Override
public void onUpdateViews() {
prepareData();
updateTermsAndConditionsView();
}
}
My AsyncTask with callback:
public class ExecuteServerTaskBackground extends AsyncTask<Void, Void, Void> {
private static final String TAG = "ExecuteServerTaskBackground";
Activity mActivity;
Context mContext;
private AsyncUpdateViewsListener callback;
public ExecuteServerTaskBackground(Activity activity) {
this.mActivity = activity;
this.mContext = activity.getApplicationContext();
}
public void setAsyncUpdateViewsListener(AsyncUpdateViewsListener listener) {
callback = listener;
}
#Override
protected Void doInBackground(Void... params) {
ServerAPI server = new ServerAPI(mContext);
if (!args.isEmpty())
msg = server.serverRequest(action, args);
else
msg = server.serverRequest(action, null);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
callback.onUpdateViews();
}
}
Why does it behave so? How can I get activity correctly if I change orientation.
EDIT:
As I understand correctly nullpointer appears after orientation changed and asynctask executed due to wrong reference between asyctask and Activity. Recreated activity doesnt have this reference thats why when I receive callback I use wrong activity reference which isn`t exist anymore. But how can I save current activity reference?
EDIT:
I have decided to try realize my task throughout Service and that`s what I have done.
Activity:
public class MainFragment extends Fragment implements ServiceExecutorListener, OnClickListener {
private static final String TAG = MainFragment.class.getName();
Button btnSend, btnCheck;
TextView serviceStatus;
Intent intent;
Boolean bound = false;
ServiceConnection sConn;
RESTService service;
ProgressDialog pd = new ProgressDialog();
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
intent = new Intent(getActivity(), RESTService.class);
getActivity().startService(intent);
sConn = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder binder) {
Log.d(TAG, "MainFragment onServiceConnected");
service = ((RESTService.MyBinder) binder).getService();
service.registerListener(MainFragment.this);
if (service.taskIsDone())
serviceStatus.setText(service.getResult());
bound = true;
}
public void onServiceDisconnected(ComponentName name) {
Log.d(TAG, "MainFragment onServiceDisconnected");
bound = false;
}
};
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main_fragment, container, false);
serviceStatus = (TextView) rootView.findViewById(R.id.tvServiceStatusValue);
btnSend = (Button) rootView.findViewById(R.id.btnSend);
btnCheck = (Button) rootView.findViewById(R.id.btnCheck);
btnSend.setOnClickListener(this);
btnCheck.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSend:
pd.show(getFragmentManager(), "ProgressDialog");
service.run(7);
service.run(2);
service.run(4);
break;
case R.id.btnCheck:
if (service != null)
serviceStatus.setText(String.valueOf(service.taskIsDone()) + service.getTasksCount());
break;
}
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "Bind service");
getActivity().bindService(intent, sConn, 0);
}
#Override
public void onPause() {
super.onDestroy();
Log.d(TAG, "onDestroy: Unbind service");
if (!bound)
return;
getActivity().unbindService(sConn);
service.unregisterListener(this);
bound = false;
}
#Override
public void onComplete(String result) {
Log.d(TAG, "Task Completed");
pd.dismiss();
serviceStatus.setText(result);
}
}
Dialog:
public class ProgressDialog extends DialogFragment implements OnClickListener {
final String TAG = ProgressDialog.class.getName();
public Dialog onCreateDialog(Bundle savedInstanceState) {
setRetainInstance(true);
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity())
.setTitle("Title!")
.setPositiveButton(R.string.yes, this)
.setNegativeButton(R.string.no, this)
.setNeutralButton(R.string.maybe, this)
.setCancelable(false)
.setMessage(R.string.message_text)
.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
return true;
}
});
return adb.create();
}
public void onClick(DialogInterface dialog, int which) {
int i = 0;
switch (which) {
case Dialog.BUTTON_POSITIVE:
i = R.string.yes;
break;
case Dialog.BUTTON_NEGATIVE:
i = R.string.no;
break;
case Dialog.BUTTON_NEUTRAL:
i = R.string.maybe;
break;
}
if (i > 0)
Log.d(TAG, "Dialog 2: " + getResources().getString(i));
}
public void onDismiss(DialogInterface dialog) {
Log.d(TAG, "Dialog 2: onDismiss");
// Fix to avoid simple dialog dismiss in orientation change
if ((getDialog() != null) && getRetainInstance())
getDialog().setDismissMessage(null);
super.onDestroyView();
}
public void onCancel(DialogInterface dialog) {
super.onCancel(dialog);
Log.d(TAG, "Dialog 2: onCancel");
}
}
Service:
public class RESTService extends Service {
final String TAG = RESTService.class.getName();
MyBinder binder = new MyBinder();
ArrayList<ServiceExecutorListener> listeners = new ArrayList<ServiceExecutorListener>();
Handler h = new Handler();
RequestManager mRequest;
ExecutorService es;
Object obj;
int time;
StringBuilder builder;
String result = null;
public void onCreate() {
super.onCreate();
Log.d(TAG, "RESTService onCreate");
es = Executors.newFixedThreadPool(1);
obj = new Object();
builder = new StringBuilder();
}
public void run(int time) {
RunRequest rr = new RunRequest(time);
es.execute(rr);
}
class RunRequest implements Runnable {
int time;
public RunRequest(int time) {
this.time = time;
Log.d(TAG, "RunRequest create");
}
public void run() {
Log.d(TAG, "RunRequest start, time = " + time);
try {
TimeUnit.SECONDS.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Log.d(TAG, "RunRequest obj = " + obj.getClass());
} catch (NullPointerException e) {
Log.d(TAG, "RunRequest error, null pointer");
}
builder.append("result " + time + ", ");
result = builder.toString();
sendCallback();
}
}
private void sendCallback() {
h.post(new Runnable() {
#Override
public void run() {
for (ServiceExecutorListener listener : listeners)
listener.onComplete();
}
});
}
public boolean taskIsDone() {
if (result != null)
return true;
return false;
}
public String getResult() {
return result;
}
public void registerListener(ServiceExecutorListener listener) {
listeners.add(listener);
}
public void unregisterListener(ServiceExecutorListener listener) {
listeners.remove(listener);
}
public IBinder onBind(Intent intent) {
Log.d(TAG, "RESTService onBind");
return binder;
}
public boolean onUnbind(Intent intent) {
Log.d(TAG, "RESTService onUnbind");
return true;
}
public class MyBinder extends Binder {
public RESTService getService() {
return RESTService.this;
}
}
}
As you mention in your edit, the current Activity is destroyed and recreated on orientation change.
But how can I save current activity reference?
You shouldn't. The previous Activity is no longer valid. This will not only cause NPEs but also memory leaks because the AsyncTask might hold the reference to old Activity, maybe forever.
Solution is to use Loaders.

How to Show ListView Items in Tabs

In Contacts Tab, trying to fetch list of all Facebook Friends
In Month Tab, trying to fetch list of Facebook Friends those Birthdays in Current Month
In Week Tab, trying to fetch list of Facebook Friends those Birthdays in Current Week
I have written code for all and i am not getting any error while build and run my program, but i am not getting list of friends in any of the Tab.
Please let me know, where i am doing silly mistake...where i am missing..
TabSample.Java :-
public class TabSample extends TabActivity {
String response;
private static JSONArray jsonArray;
public static TabHost mTabHost;
private MyFacebook fb = MyFacebook.getInstance();
public static MyLocalDB db = null;
private BcReceiver bcr = null;
private BcReceiverAlarm bcra = null;
private PendingIntent mAlarmSender;
private boolean isAlarmSet;
private ProgressDialog busyDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAlarmSender = PendingIntent.getService(TabSample.this, 0, new Intent(
TabSample.this, BdRemService.class), 0);
setContentView(R.layout.main);
if (db == null) {
db = new MyLocalDB(this);
db.open();
}
if (!fb.isReady()) {
Log.v(TAG, "TabSample- initiating facebook");
fb.init(this);// after finishing, this will call loadContents itself
} else {
loadContents();
}
busyDialog = new ProgressDialog(this);
busyDialog.setIndeterminate(true);
busyDialog.setMessage("Refreshing");
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
response = getIntent().getStringExtra("FRIENDS");
try {
jsonArray = new JSONArray(response);
} catch (JSONException e) {
FacebookUtility.displayMessageBox(this,
this.getString(R.string.json_failed));
}
setTabs();
}
private void setTabs() {
addTab("Contacts", com.chr.tatu.sample.friendslist.ContactTab.class);
addTab("Month", com.chr.tatu.sample.friendslist.MonthTab.class);
addTab("Week", com.chr.tatu.sample.friendslist.WeekTab.class);
}
private void setupTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
}
private void setupTab(final View view, final String tag, Intent intent,
int id) {
View tabview = createTabView(mTabHost.getContext(), tag, id);
TabSpec setContent = mTabHost.newTabSpec(tag).setIndicator(tabview)
.setContent(intent);
mTabHost.addTab(setContent);
}
private void addTab(String labelId, Class<?> c) {
TabHost tabHost = getTabHost();
Intent intent = new Intent(this, c);
intent.putExtra("FRIENDS", response);
TabHost.TabSpec spec = tabHost.newTabSpec("tab" + labelId);
View tabIndicator = LayoutInflater.from(this).inflate(
R.layout.tab_indicator, getTabWidget(), false);
TextView title = (TextView) tabIndicator.findViewById(R.id.title);
title.setText(labelId);
spec.setIndicator(tabIndicator);
spec.setContent(intent);
tabHost.addTab(spec);
}
private static View createTabView(final Context context, final String text,
final int id)
{
View view = LayoutInflater.from(context).inflate(
R.layout.tab_indicator, null);
return view;
}
#Override
protected void onResume() {
if (bcr == null) {
bcr = new BcReceiver();
registerReceiver(bcr, new IntentFilter(MyUtils.BIRTHDAY_ALERT));
}
if (bcra == null) {
bcra = new BcReceiverAlarm();
registerReceiver(bcra, new IntentFilter(MyUtils.ALARM_RESET));
}
super.onResume();
}
public void loadContents() {
if (fb.getFriendsCount() > 0) {
return;
}
fb.setMyFriends(db.getAllFriends());
if (fb.getFriendsCount() > 0) {
notifyTabSample(Note.FRIENDLIST_CHANGED);
} else {
fb.reLoadAllFriends();
}
// 4. initiate alarm
if (!isAlarmSet) {
setAlarm(true);
}
}
private void setAlarm(boolean isON) {
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
if (isON) {
am.setRepeating(AlarmManager.RTC_WAKEUP, MyUtils
.getAlarmStartTimeAsLong(MyUtils.getAlarmHour(), MyUtils
.getAlarmMinute()), 24 * 60 * 60 * 1000,
mAlarmSender);
isAlarmSet = true;
Log.v(TAG, "TabSample- alarm set");
} else {
am.cancel(mAlarmSender);
isAlarmSet = true;
Log.v(TAG, "TabSample- alarm cancelled");
}
}
public void notifyTabSample(Note what) {
switch (what) {
case FRIENDLIST_RELOADED:
db.syncFriends(fb.getMyFriends());
sendBroadcast(new Intent(MyUtils.FRIENDLIST_CHANGED));
break;
case FRIENDLIST_CHANGED:
sendBroadcast(new Intent(MyUtils.FRIENDLIST_CHANGED));
// setup timer
break;
default:
break;
}
}
ContactTab.Java :-
public class ContactTab extends ListActivity {
private MyFacebook fb = MyFacebook.getInstance();
private BcReceiver bcr = null;
private MyAdapter adapter;
private List<MyFriend> list;
private ProgressDialog busyDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
busyDialog = new ProgressDialog(this);
busyDialog.setIndeterminate(true);
busyDialog.setMessage("Refreshing");
}
private void refreshList() {
new Thread() {
public void run() {
list = fb.getAllFriends();
Log.v(TAG, "contactstab- refresh called. " + list.size());
adapter = new MyAdapter(ContactTab.this, list);
handler.sendEmptyMessage(0);
}
}.start();
}
#Override
protected void onResume() {
if (bcr == null) {
bcr = new BcReceiver();
registerReceiver(bcr, new IntentFilter(MyUtils.FRIENDLIST_CHANGED));
}
refreshList();
super.onResume();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
MyFriend friend = (MyFriend) this.getListAdapter().getItem(position);
Intent intent = new Intent(ContactTab.this, PersonalGreeting.class);
intent.putExtra("fbID", friend.getFbID());
intent.putExtra("name", friend.getName());
intent.putExtra("pic", friend.getPic());
startActivity(intent);
}
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication()).inflate(R.layout.menu, menu);
return (super.onPrepareOptionsMenu(menu));
}
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case R.id.globalGreeting:
intent = new Intent(ContactTab.this, com.chr.tatu.sample.friendslist.GlobalGreeting.class);
startActivity(intent);
break;
case R.id.Settings:
intent = new Intent(ContactTab.this, com.chr.tatu.sample.friendslist.Settings.class);
startActivity(intent);
}
return (super.onOptionsItemSelected(item));
}
public class BcReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
runOnUiThread(new Runnable() {
public void run() {
refreshList();
}
});
}
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
setListAdapter(adapter);
//busyDialog.dismiss();
}
};
}
MonthTab.Java :-
public class MonthTab extends ListActivity {
private MyFacebook fb = MyFacebook.getInstance();
private BcReceiver bcr = null;
private MyAdapter adapter;
private List<MyFriend> list;
private ProgressDialog busyDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
busyDialog = new ProgressDialog(this);
busyDialog.setIndeterminate(true);
busyDialog.setMessage("Please wait ...");
busyDialog.show();
refreshList();
}
private void refreshList() {
// list = fb.getFilteredFriends(Filter.MONTH);
list = fb.getFilteredFriends(Filter.MONTH);
adapter = new MyAdapter(MonthTab.this, list);
setListAdapter(adapter);
busyDialog.dismiss();
}
#Override
protected void onResume() {
if (bcr == null) {
bcr = new BcReceiver();
registerReceiver(bcr, new IntentFilter(MyUtils.FRIENDLIST_CHANGED));
}
super.onResume();
}
#Override
#SuppressWarnings("unchecked")
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
MyFriend friend = (MyFriend) this.getListAdapter().getItem(position);
Intent intent = new Intent(MonthTab.this, PersonalGreeting.class);
intent.putExtra("fbID", friend.getFbID());
intent.putExtra("name", friend.getName());
startActivity(intent);
}
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication()).inflate(R.layout.menu, menu);
return (super.onPrepareOptionsMenu(menu));
}
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case R.id.globalGreeting:
intent = new Intent(MonthTab.this, GlobalGreeting.class);
startActivity(intent);
break;
case R.id.Settings:
intent = new Intent(MonthTab.this, Settings.class);
startActivity(intent);
}
return (super.onOptionsItemSelected(item));
}
public class BcReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
runOnUiThread(new Runnable() {
public void run() {
refreshList();
}
});
}
}
}

Categories

Resources