I have two activities which starts the same sub-activity for result.
But in only one of them onActivityResult works.
Here are parts of my code
This is my first Activity. As you can see it calls NewCommentActivity in startActivityForResult and this part works fine
public class OfferActivity extends ListActivity implements View.OnClickListener {
...
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.offer_menu_comment:
Intent commentIntent = new Intent(this, NewCommentActivity.class);
commentIntent.putExtra(Offer.OFFER, offer);
startActivityForResult(commentIntent, COMMENT_REQUEST_CODE);
return true;
...
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case COMMENT_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Integer commentCnt = offer.getCommentCnt() + 1;
offer.setCommentCnt(commentCnt);
commentButton.setText(getString(R.string.offer_comments, offer.getCommentCnt()));
}
break;
}
}
...
}
Here is my second activity which calls NewCommentActivity too, but here onActivityResult is not called
public class CommentsActivity extends ListActivity{
...
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
...
case COMMENT_ITEM_ID:
Intent commentIntent = new Intent(this, NewCommentActivity.class);
commentIntent.putExtra(Offer.OFFER, offer);
startActivityForResult(commentIntent, COMMENT_REQUEST_CODE);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case COMMENT_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Integer commentCnt = offer.getCommentCnt() + 1;
offer.setCommentCnt(commentCnt);
Comment comment = data.getParcelableExtra(Comment.COMMENT);
commentImageListAdapter.addItemAtFront(comment);
}
break;
}
}
...
}
And here is code for NewCommentActivity :
public class NewCommentActivity extends Activity implements View.OnClickListener {
private static final String TAG = "Gift/NewCommentActivity";
private Offer offer;
private EditText editText;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_comment);
offer = getIntent().getParcelableExtra(Offer.OFFER);
editText = (EditText) findViewById(R.id.new_comment_text);
Button button = (Button) findViewById(R.id.new_comment_button);
button.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (editText.getText().length() > 0) {
new AddCommentAsyncTask().execute(offer, editText.getText().toString());
}
}
private class AddCommentAsyncTask extends AsyncTask<Object, Void, Comment> {
private String errorString;
private ProgressDialog progressDialog;
#Override
protected Comment doInBackground(Object... objects) {
Offer offer = (Offer) objects[0];
String text = (String) objects[1];
Comment comment = null;
try {
comment = ServiceContainer.getService().addComment(offer, text);
} catch (OfferException e) {
Log.e(TAG, "exception in comment", e);
int id;
if ((id = e.getErrorStringId()) != -1) {
errorString = getString(id);
} else {
errorString = e.getLocalizedMessage();
}
cancel(false);
}
return comment;
}
#Override
protected void onPreExecute() {
progressDialog = Utils.newSpinnerDialog(NewCommentActivity.this, R.string.sending);
}
#Override
protected void onCancelled() {
progressDialog.dismiss();
AlertDialog.Builder builder = Utils.newAlertDialog(NewCommentActivity.this, errorString, true);
builder.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
new AddCommentAsyncTask().execute(offer, editText.getText().toString());
}
})
.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
setResult(RESULT_CANCELED);
finish();
}
})
.create()
.show();
}
#Override
protected void onPostExecute(Comment comment) {
progressDialog.dismiss();
Intent intent = new Intent();
intent.putExtra(Comment.COMMENT, comment);
setResult(RESULT_OK, intent);
finish();
}
}
And finally AndroidManifest for all activities:
<activity android:name=".activity.OfferActivity"
android:configChanges="orientation"/>
<activity android:name=".activity.CommentsActivity"
android:configChanges="orientation"
android:label="#string/comment_activity_title"/>
<activity android:name=".activity.NewCommentActivity"
android:windowSoftInputMode="adjustResize"
android:configChanges="orientation"
android:label="#string/new_comment_activity_title"/>
</application>
Please help me.
Thanks.
Related
I tried using a "speech to text" feature in my app.
it opens up the recording window/ dialog or whatever but the text doesn't show.
this is the code:
public void onTalk(View v){
promptSpeechInput();
}
public void promptSpeechInput()
{
Intent i=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
i.putExtra(RecognizerIntent.EXTRA_PROMPT,"say something");
try{
startActivityForResult(i, 50);
}
catch(ActivityNotFoundException e){
Toast.makeText(this,"sorry your device doesnt support speech language",Toast.LENGTH_LONG).show();
}
}
then there's the onResult part:
public void onActivityResult(int request_code, int result_code, Intent i){
super.onActivityResult(request_code,result_code,i);
if (request_code==RESULT_OK)
if(i!=null) {
EditText locationTS = (EditText) findViewById (R.id.locationET);
ArrayList<String> result = i.getStringArrayListExtra((RecognizerIntent.EXTRA_RESULTS));
locationTS.setText(result.get(0));
}
}
locationTS is an EditText, and it does not show any text after i talk.
This worked in my case:
I had a separate Helper class as:
public class SpeechRecognitionHelper {
private static final int VOICE_RECOGNITION_REQUEST_CODE=101;
public static void run(Activity activity){
if(isSpeechRecognitionActivityPresent(activity)){
startRecognition(activity);
}
else {
Toast.makeText(activity,"You must install Google Voice Search",Toast.LENGTH_LONG).show();
installGoogleVoiceSearch(activity);
}
}
private static boolean isSpeechRecognitionActivityPresent(Activity activity){
try {
PackageManager packageManager = activity.getPackageManager();
List activities = packageManager.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH),0);
if (activities.size()!=0){
return true;
}
}
catch (Exception e){
}
return false;
}
public static void startRecognition(Activity activity){
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,"Say Something");
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,1);
activity.startActivityForResult(intent,VOICE_RECOGNITION_REQUEST_CODE);
}
private static void installGoogleVoiceSearch(final Activity activity){
Dialog dialog = new AlertDialog.Builder(activity)
.setMessage("For recognition Install Google Voice Search")
.setTitle("Install voice search?")
.setPositiveButton("Install", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.voicesearch"));
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
activity.startActivity(intent);
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
}
}
Then in the MainActivity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private static final int VOICE_RECOGNITION_REQUEST_CODE=101;
private static final int CAMERA_REQUEST=201;
private Button buttonVoiceCommand;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonVoiceCommand = (Button)findViewById(R.id.buttonVoiceCommand);
buttonVoiceCommand.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int id = view.getId();
if (id == R.id.buttonVoiceCommand){
run(MainActivity.this);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode,data);
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if(matches.size()>0){
if(matches.get(0).indexOf("camera")>0){
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent,CAMERA_REQUEST);
}
else {
Toast.makeText(this,matches.get(0),Toast.LENGTH_LONG).show();
}
}
}
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
//Perform whatever you want to do (-.-)
Toast.makeText(this,"Camera Working",Toast.LENGTH_LONG).show();
}
}
}
I Toast the content of matches.get(0) You just have to set it in an edit text
For example: my app calls a native settings activity, by
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(myIntent, CODE);
Then when it is finished (by pressing the back button for example) I want to know. I tried this way, but the onActivityResult() wasn't called when the native activity was finalized... so my app wasn't informed...
How I have to do? Anyone knows?
Thanks...
EDIT:
Thanks every one.
The complete code is that:
public class MainActivity extends AppCompatActivity {
public static final int DIALOG_CODE = 0x1;
private TextView txtGps;
private TextView txtNet;
private LocationManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
first();
}
private void checkConfigs() {
boolean gps = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean net = manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
setWidgets(gps, net);
if (gps && net){
Toast.makeText(this, "Configurações Ok!", Toast.LENGTH_SHORT).show();
} else {
DialogConfig.exibDialog(getFragmentManager());
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((requestCode == DIALOG_CODE) && (resultCode == RESULT_OK)){
checkConfigs();
} else {
Toast.makeText(this, "As config não foram alteradas!", Toast.LENGTH_SHORT).show();
}
}
public void setWidgets(boolean gsp, boolean net){
if (gsp){
txtGps.setText(R.string.gps_hab);
} else {
txtGps.setText(R.string.gps_n_hab);
}
if (net){
txtNet.setText(R.string.wifi_hab);
} else {
txtNet.setText(R.string.wifi_n_hab);
}
}
private View.OnClickListener onClickCheck() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
checkConfigs();
}
};
}
#SuppressWarnings("ConstantConditions")
private void first() {
txtGps = (TextView) findViewById(R.id.txt_gps);
txtNet = (TextView) findViewById(R.id.txt_net);
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
findViewById(R.id.btn_check).setOnClickListener(onClickCheck());
}
public static class DialogConfig extends DialogFragment {
public static void exibDialog(FragmentManager fm){
new DialogConfig().show(fm, "dialog");
}
#Override
public android.app.Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle("As conf não estão corretas! Alt configs?")
.setPositiveButton("Ok", onOk())
.setNegativeButton("Cancel", onCancel())
.create();
}
private DialogInterface.OnClickListener onCancel() {
return new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dismiss();
}
};
}
private DialogInterface.OnClickListener onOk() {
return new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(myIntent, DIALOG_CODE);
}
};
}
}
}
[Resolved]
Thanks again to every one, I tried again, creating a interface of callback in dialog, so the activity could be informed and call the other native settings activity by itself , and got the response in onActivityResult(), but comparing only a code (not by RESULT_OK), This way worked. But there is a other way (like was suggested) that use the lifecycle, to me seems more easy.
I basically tried what you tried and it works for me.
startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), 1);
and for onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(PREFIX, "onActivityResult");
}
When I came back to the app, onActivityResult was called.
Not sure what you are doing different. can you show your onActivityResult code?
I'm using Activitygroup concept to handle multiple activities under single tab. What I am doing in first activity of tab, I fetch image from gallery and camera, and after that when user selects image that image should move to second activity but those both activities must remain under the same tab. Here is my code...
TabGroupActivity.java
public class TabGroupActivity extends ActivityGroup {
private ArrayList<String> mIdList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mIdList == null) mIdList = new ArrayList<String>();
}
#Override
public void finishFromChild(Activity child) {
LocalActivityManager manager = getLocalActivityManager();
int index = mIdList.size()-1;
if (index < 1) {
finish();
return;
}
manager.destroyActivity(mIdList.get(index), true);
mIdList.remove(index); index--;
String lastId = mIdList.get(index);
Intent lastIntent = manager.getActivity(lastId).getIntent();
Window newWindow = manager.startActivity(lastId, lastIntent);
setContentView(newWindow.getDecorView());
}
public void startChildActivity(String Id, Intent intent) {
Window window = getLocalActivityManager().startActivity(Id,intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT));
if (window != null) {
mIdList.add(Id);
setContentView(window.getDecorView());
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//preventing default implementation previous to android.os.Build.VERSION_CODES.ECLAIR
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
return true;
}
return super.onKeyUp(keyCode, event);
}
public void onBackPressed() {
int length = mIdList.size();
if ( length > 1) {
Activity current = getLocalActivityManager().getActivity(mIdList.get(length-1));
current.finish();
}
}
}
MainActivity.java
Intent intentPics = new Intent().setClass(this, GalleryPic_First.class);
TabSpec tabPics = tabHost
.newTabSpec("Photo")
.setIndicator("Photo", ressources.getDrawable(R.drawable.icon_apple_config))
.setContent(intentPics);
GalleryPic_First .java
public class GalleryPic_First extends TabGroupActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startChildActivity("EditActivity", new Intent(this,GalleryPic.class));
}
}
GalleryPic.java
public class GalleryPic extends Activity {
private static final int TAKE_PICTURE = 0;
private static final int REQUEST_ID = 1;
private static final int HALF = 2;
private Uri mUri;
private Bitmap mPhoto;
ImageView ivGallery, ivCamera;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery_pic);
ivGallery = (ImageView)findViewById(R.id.gallery);
ivCamera = (ImageView)findViewById(R.id.snap);
ivGallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
getParent().startActivityForResult(intent, REQUEST_ID);
}
});
ivCamera.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
File f = new File(Environment.getExternalStorageDirectory(), "photo.jpg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
mUri = Uri.fromFile(f);
getParent().startActivityForResult(i, TAKE_PICTURE);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK && data != null)
{
getContentResolver().notifyChange(mUri, null);
ContentResolver cr = getContentResolver();
try
{
mPhoto = android.provider.MediaStore.Images.Media.getBitmap(cr, mUri);
GalleryPic_Second.bmp = mPhoto;
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
break;
case REQUEST_ID :
InputStream stream = null;
if (resultCode == Activity.RESULT_OK && data != null) {
try
{
stream = getContentResolver().openInputStream(data.getData());
Bitmap original = BitmapFactory.decodeStream(stream);
GalleryPic_Second.bmp = Bitmap.createScaledBitmap(original, original.getWidth()/HALF, original.getHeight()/HALF, true);
Intent in = new Intent(GalleryPic.this, GalleryPic_Second.class);
TabGroupActivity parent = (TabGroupActivity)getParent();
parent.startChildActivity("ArrowsActivity", in);
}
catch (Exception e)
{
e.printStackTrace();
}
if (stream != null) {
try {
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
break;
}
}
#Override
public void onBackPressed() {
// this.getParent().onBackPressed();
TabViewLayout parentTab = (TabViewLayout) this.getParent();
parentTab.switchTabBar(1);
}
}
GalleryPic_Second.java
public class GalleryPic_Second extends Activity {
public static Bitmap bmp;
Button btnUpload;
ImageView iv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.transparent_dialog);
View viewToLoad = LayoutInflater.from(this.getParent()).inflate(R.layout.transparent_dialog, null);
this.setContentView(viewToLoad);
setResult(RESULT_OK);
iv = (ImageView)viewToLoad.findViewById(R.id.photo_holder);
btnUpload = (Button)viewToLoad.findViewById(R.id.upload);
iv.setImageBitmap(bmp);
btnUpload.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
#Override
public void onBackPressed() {
// this.getParent().onBackPressed();
finish();
}
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
}
}
But the image is not being displayed in second activity. How to do this?
call this way
GalleryPic.this.startActivityForResult(intent, REQUEST_ID);
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);
I have a Parent activity which is sending data to child activity but the child is not returning the result. I posted portion of code from both activity altogether below- Theres a few code that I didnt post for unnecessity.
public class TdeeActivity extends Activity {
public static final int CALLED_ACTIVITY = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tdee);
Button ok=(Button)findViewById(R.id.btnOk);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent bmr= new Intent(TdeeActivity.this,BMRActivity.class);
startActivityForResult(bmr,CALLED_ACTIVITY);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case CALLED_ACTIVITY:
if (resultCode == RESULT_OK) {
Toast.makeText(this, "THE RESULT-"+data.getExtras().getString("result"),
Toast.LENGTH_SHORT).show();
}
}
}
} // end class
public class BMRActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bmr);
Button btnOk=(Button)findViewById(R.id.btnOk);
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showResult();
}
});
public void showResult() {
Intent data= new Intent();
data.putExtra("result",result);
setResult(RESULT_OK, data);
finish();
}
}
}// end class
I tested you code in a dummy project and it was working fine at my end.. following is the code for both activity:
public class ParentActivity extends Activity {
private static final int CALLED_ACTIVITY = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent bmr = new Intent(ParentActivity.this, ChildActivity.class);
startActivityForResult(bmr, CALLED_ACTIVITY);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case CALLED_ACTIVITY:
if (resultCode == RESULT_OK) {
Toast.makeText(this, "THE RESULT-"+data.getExtras().getString("result"),
Toast.LENGTH_SHORT).show();
}
}
}
}
public class ChildActivity extends Activity {
final Activity activity = this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Returning result from child activity
Intent data = new Intent();
data.putExtra("result", "from child"
+ this.getCallingActivity().getClassName());
setResult(RESULT_OK, data);
finish();
}
}
So please post more code so that issue can be found..