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);
}
}
}`
Related
I'm making an app where I ask a question and the answering machine answers me depending on the question, but the problem is that the cell phone listens but it does not respond, that is, it does not talk.
She is speak in open app with welcome, but after no talk
My code
public class MainActivity extends AppCompatActivity {
private TextToSpeech myTTS;
private SpeechRecognizer mySpeechReconizer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button mic = (Button) findViewById(R.id.mic);
mic.setOnClickListener((view) ->
{
Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
i.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
mySpeechReconizer.startListening(i);
});
initializeTextToSpeech();
initializeSpeechReconizer();
}
private void initializeSpeechReconizer() {
if (SpeechRecognizer.isRecognitionAvailable(this)) {
mySpeechReconizer = SpeechRecognizer.createSpeechRecognizer(this);
mySpeechReconizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int error) {
}
#Override
public void onResults(Bundle bundle) {
List<String> res = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
processResult(res.get(0));
}
#Override
public void onPartialResults(Bundle partialResults) {
}
#Override
public void onEvent(int eventType, Bundle params) {
}
});
}
}
private void processResult(String s) {
s = s.toLowerCase();
//Qual é o teu nome?
if (s.indexOf("What") != -1){
if (s.indexOf("your name") != -1){
speak("two");
}
if (s.indexOf("time") != -1){
Date now = new Date();
String time = DateUtils.formatDateTime(this,now.getTime(),
DateUtils.FORMAT_SHOW_TIME);
speak(time);
}
}
else if (s.indexOf("open") != -1){
if (s.indexOf("browser") != -1){
}
speak("Sou a Lian, fui fundada pelo Leandro e moro em Baião.");
}
}
private void initializeTextToSpeech() {
myTTS = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (myTTS.getEngines().size()==0){
Toast.makeText(MainActivity.this, "Teste", Toast.LENGTH_LONG).show();
finish();
} else {
Locale l1 = new Locale("pt","PT");
myTTS.setLanguage(l1);
speak("Olá Leandro, estou pronta,podes falar!");
}
}
});
}
private void speak(String s) {
if (Build.VERSION.SDK_INT >=21){
myTTS.speak(s,TextToSpeech.QUEUE_FLUSH,null,null);
} else{
myTTS.speak(s,TextToSpeech.QUEUE_FLUSH,null);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPause() {
super.onPause();
myTTS.shutdown();
}
}
I have this problem with the tutorial from sinch. The first time I logged in the broadcast receiver gets registered but the second time to visit the activity the progress dialog doesnt disappear I think its because theres already same broadcast receiver registered on the device. heres my code
public class ListUserActivity extends AppCompatActivity {
private Object currentUserId;
private ArrayList names;
private ListView usersListView;
private ArrayAdapter<String> namesArrayAdapter;
Toolbar toolbar;
ProgressDialog progressDialog;
BroadcastReceiver receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_user);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
showSpinner();
}
public void openConversation(ArrayList<String> names, int pos) {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("username", names.get(pos));
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> list, ParseException e) {
if (e == null) {
//start the messaging activity
} else {
Toast.makeText(getApplicationContext(),
"Error finding that user",
Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.menu_list_user, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if(id == android.R.id.home){
// emulate the back hardware press of the device
super.onBackPressed();
}
return super.onOptionsItemSelected(item);
}
public void showSpinner(){
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Loading");
progressDialog.setMessage("Please wait...");
progressDialog.show();
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Boolean success = intent.getBooleanExtra("success", false);
progressDialog.dismiss();
//show a toast message if the Sinch
//service failed to start
if (!success) {
Toast.makeText(getApplicationContext(), "Messaging service failed to start", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Messaging service success to start", Toast.LENGTH_LONG).show();
}
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("com.serverus.oom.ListUserActivity"));
}
public void setConversationsList(){
currentUserId = ParseUser.getCurrentUser().getObjectId();
names = new ArrayList<String>();
ParseQuery<ParseUser> query = ParseUser.getQuery();
//don't include yourself
query.whereNotEqualTo("objectId", currentUserId);
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> userList, com.parse.ParseException e) {
if (e == null) {
for (int i = 0; i < userList.size(); i++) {
names.add(userList.get(i).getUsername().toString());
}
usersListView = (ListView) findViewById(R.id.usersListView);
namesArrayAdapter = new ArrayAdapter<String>(getApplicationContext(),
R.layout.user_list_item, names);
usersListView.setAdapter(namesArrayAdapter);
usersListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
openConversation(names, i);
}
});
} else {
Toast.makeText(getApplicationContext(),
"Error loading user list",
Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public void onResume() {
setConversationsList();
super.onResume();
}
}
thanks in advance guys. Im just a newbie in android dev so please explain things to me if I dont get something in my code.
your trouble is because you register your BroadcastReciever every time activity starts, in OnCreate() method. There's a link on showSpinner() method, where you initialize receiver = new BroadcastReceiver. Save a boolean to SharedPreferences, and then in showSpinner() method check it. If it is true, do not call receiver = ...
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.
I am using the class SpeechRecognizer by calling the method startListening when a button is pressed, but I get an error. First the callback methods onReadyForSpeech, onBeginningOfSpeech, onEndofSpeech are called (immediately) and at the end onError with the errorcode 2 "ERROR_NETWORK" is called. When I call the intent directly by using startActivityForResult, it works. But I want to get rid of the time consuming popup dialog.
I have the RECORD_AUDIO permission set.
I am not sure, but perhaps the intent want to load something from the internet. For that, I tried to add the INTERNET-Permission, but it did not work either.
Here the code:
public class MainActivity extends ActionBarActivity implements RecognitionListener
{
private SpeechRecognizer speechRecognizer;
public void onReadyForSpeech(Bundle params)
{
AddLog("onReadyForSpeech called.");
}
public void onBeginningOfSpeech()
{
AddLog("onBeginningOfSpeech called.");
}
public void onRmsChanged(float rmsdB)
{
AddLog("onRmsChanged called.");
}
public void onBufferReceived(byte[] buffer)
{
AddLog("onBufferReceived called.");
}
public void onEndOfSpeech()
{
AddLog("onEndOfSpeech called.");
}
public void onError(int error)
{
AddLog(String.format("onError called with id: %d.", error));
}
public void onResults(Bundle results)
{
String str = new String();
ArrayList<String> data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for(int i = 0; i < data.size(); i++)
{
str += data.get(i);
}
final String strAnswer = str;
AddLog(String.format("Answer is %s", strAnswer));
}
public void onPartialResults(Bundle psrtialResults)
{
AddLog("onPartialResults called.");
}
public void onEvent(int eventType, Bundle params)
{
AddLog("onEvent called.");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
speechRecognizer.setRecognitionListener(this);
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment
{
public PlaceholderFragment()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
public void AddLog(final String text)
{
TextView txtLogView = (TextView) findViewById(R.id.textViewLog);
if (txtLogView != null)
{
txtLogView.append(text + "\n");
}
}
// Only for test
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == 1 && resultCode == RESULT_OK)
{
ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
AddLog(matches.get(0));
}
super.onActivityResult(requestCode, resultCode, data);
}
public void Start(View view)
{
AddLog("Start pressed.");
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
// Only for test
//startActivityForResult(intent, 1);
speechRecognizer.startListening(intent);
AddLog("startListening called.");
}
}
I solved it by myself. The problem was, that the language pack for US had an update. I had to load it by hand (in the language settings of my mobile). After that the error ERROR_NETWORK disappeared.
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);