Im creating an intent to an activity by clicking on a button which should open google places, but it closes again really fast and says no location selected, and returns to the main activity, and then nothing happens if i click again.
My api should be fine, I have checked that it's the correct SHA1-fingerprint thats connected to the api key.
The result code is 2
It worked earlier in the activity before this one, but I needed it to open when i click on a button instead, and now when I try to open this new activity as an intent it wont work.
public class MapActivity extends AppCompatActivity {
int PLACE_PICKER_REQUEST = 1;
int status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events);
status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (status != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(status)) {
GooglePlayServicesUtil.getErrorDialog(status, this,
100).show();
}
}
if (status == ConnectionResult.SUCCESS) {
int PLACE_PICKER_REQUEST = 199;
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
Context context = this;
try {
startActivityForResult(builder.build(context), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println("Result code: " + resultCode);
System.out.println("Request code: " + requestCode);
if (requestCode == 100) {
status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
}
if (requestCode == 199) {
//process Intent......
if (data != null) {
Place place = PlacePicker.getPlace(data, this);
String toastMsg = String.format("Place: %s", place.getName());
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
} else {
String toastMsg = ("No location selected.");
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
}
}
}
}
This is from the intent which create the new intent to maps
public void onClick(View view) {
Intent i = new Intent(this, MapActivity.class);
startActivity(i);
}
I think its happening because of you are using old method of getPlace
try to swap the arguments, by changing it from:
Place place = PlacePicker.getPlace(data, this);
to
Place place = PlacePicker.getPlace(getContext(), data);
Update #2
Enable Google places API in the developer console and add these lines to AndroidManifest
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="ADD_YOUR_API_KEY_HERE" />
Update #3
after some search, it looks like there is others having same issue. Look at these links:
https://github.com/zhangtaii/react-native-google-place-picker/issues/21
https://stackoverflow.com/a/32751164/
https://github.com/googlesamples/android-play-places/issues/13
Related
My requirement is the end-user must be able to upload files into the application from internal or external storage and finally display the name of the file in the page.
Actual result: Now I've fetched the file name from the storage and displayed the name in my page.
Expected Result: The end user must be able to load image or video files from external or internal storage to the application and finally display their name in the page.
But don't have any idea about how to load read the file from storage and store it in a arrayList.
Code for fetching the file name
public class ServiceDetails extends AppCompatActivity {
private Button next, attachment_one;
private ImageButton attach_file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enter_details);
next = findViewById(R.id.submit);
attachment_one = findViewById(R.id.attachmentOne);
attach_file = findViewById(R.id.attachFile);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ServiceDetails.this, ServiceAddress.class);
startActivity(intent);
}
});
attach_file.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M &&
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 10001);
}
new MaterialFilePicker()
.withActivity(ServiceDetails.this)
.withRequestCode(1)
.withFilter(Pattern.compile(".*\\.(mkv|wmv|avi|mpeg|swf|mov|mp4|jpg|jpeg)$"))
.withHiddenFiles(true) // Show hidden files and folders
.start();
}
});
attachment_one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
attachment_one.setVisibility(View.INVISIBLE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
String file_path = data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH);
String file_array[] = file_path.split("/");
String file_name = file_array[file_array.length - 1];
// Do anything with file
if(attachment_one.getText().toString().isEmpty()) {
attachment_one.setVisibility(View.VISIBLE);
attachment_one.setText(file_name);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 10001: {
if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(ServiceDetails.this, "Permission granted", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(ServiceDetails.this, "Permission not granted", Toast.LENGTH_LONG).show();
finish();
}
}
}
}
}
I'm new to android and kindly help me providing solution for this answer. Million thanks in advance!
Image showing file attachment option
As you are willing to load the title of video/images, and other file related information from the External Storage. You have to use this code and also make sure don't forget to create a Arraylist with model(required to extract information and find to the listview).
//ContentResolver and contentProvider as well as cursor
String[] projection = new String[]{
MediaStore.Video.Media._ID,
MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.SIZE,
MediaStore.Video.Media.DATE_MODIFIED
};
String selection = null;
String[] selectionargs = null;
String orderBy = MediaStore.Video.Media.DISPLAY_NAME + " Desc";
Uri content_uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = getContentResolver().query(content_uri, projection, selection, selectionargs, orderBy);
if (cursor != null) {
cursor.moveToPosition(0);
}
while (true) {
long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
Uri VideoUri = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id);
Log.d("uri", "onCreate: video path " + VideoUri);
String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
float size = cursor.getFloat(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
// loading a thumbnail from the content resolver
// Load thumbnail of a specific media item.
Bitmap thumbnail = null;
try {
thumbnail = getApplicationContext().getContentResolver().loadThumbnail(VideoUri, new Size(200, 200), null);
Log.d("thumbnail", "onCreate: Lodaing a thumbnail");
} catch (IOException e) {
Log.d("thumbnail", "onCreate: Showing Error on thumbnail");
e.printStackTrace();
}
videolist.add(new Video(thumbnail, VideoUri, title, size));
if (!cursor.isLast()) {
cursor.moveToNext();
} else {
Log.d("lastItem", "onCreate: last uri is encountered");
break;
}
}
cursor.close();
I have created an app that you could share images with them. I have set a notification sound when the sharing process is done. However, if I hit Cancel/Back buttons, the sound still plays.
In my code below, I have set a share button, once you click on it, you can share a bitmap of the image through the basic sharing app of android.
How can I set the sound to ONLY play when the sharing is complete.
Thanks,
Safi
Here's my code:
shareBtn = findViewById(R.id.shareButton);
shareBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(animTranslate);
shareDigitalCard();
}
});
private void shareDigitalCard() {
if (ActivityCompat.checkSelfPermission(MyMenu.this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
try {
makeStorageRequest();
} catch (Exception e) {
e.printStackTrace();
}
}else {
Bitmap viewBmp = Bitmap.createBitmap(mPager.getWidth(),
mPager.getHeight(), Bitmap.Config.ARGB_8888);
viewBmp.setDensity(mPager.getResources().getDisplayMetrics().densityDpi);
Canvas canvas = new Canvas(viewBmp);
//mPager.layout(0, 0 , mPager.getLayoutParams().width, mPager.getLayoutParams().height);
mPager.draw(canvas);
path = String.valueOf(saveTempBitmap(viewBmp));
shareImage(path);
}
}
private void shareImage(String file) {
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent share = new Intent(Intent.ACTION_SEND);
// If you want to share a png image only, you can do:
// setType("image/png"); OR for jpeg: setType("image/jpeg");
share.setType("image/*");
File imageFileToShare = new File(file);
Uri uri = Uri.fromFile(imageFileToShare);
share.putExtra(Intent.EXTRA_STREAM, uri);
try {
startActivityForResult(Intent.createChooser(share, "Share Image!"),123);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 123){
if (isSoundEnable) {
MediaPlayer player = null;
if (player == null) {
player = MediaPlayer.create(this, R.raw.success);
final MediaPlayer finalPlayer = player;
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlayer(finalPlayer);
}
});
}
player.start();
}
} else {
Toast.makeText(this, "An Error Has Occured !", Toast.LENGTH_SHORT).show();
}
}
You cannot get this event. The sharing procedure depends on the other App and you haven't any control or result from it. What you know is just you have send an Intent to a specific App, but what it does it's all up to it.
I am using the Firebase AuthUI to sign in to my application, specifically with Facebook. I have verified within my console that my sign in was successful, as I see the user added.
However, my callback method is not triggering, I have toasts implemented and I do not know why the success method is not being called. I have logged the error code and do not know what issue it signifies. Am I capturing the error correctly? It is generating -1, which I do not see in the Firebase AuthUI docs:
public class LoginActivity extends AppCompatActivity {
private static final int RC_SIGN_IN = 123;
private static final String USERS = "Users";
private FirebaseAuth mAuth;
FirebaseDatabase mBaseRef;
DatabaseReference mUserRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mAuth = FirebaseAuth.getInstance();
mBaseRef = FirebaseDatabase.getInstance();
mUserRef = mBaseRef.getReference(USERS);
startActivityForResult(AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(Arrays.asList(
new AuthUI.IdpConfig.EmailBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build(),
new AuthUI.IdpConfig.FacebookBuilder().build()))
.build(), RC_SIGN_IN);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// RC_SIGN_IN is the request code you passed into startActivityForResult(...) when starting the sign in flow.
if (requestCode == RC_SIGN_IN) {
IdpResponse response = IdpResponse.fromResultIntent(data);
Log.v("RESPONSE", String.valueOf(response.getErrorCode()));
// Successfully signed in
if (resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), "SIGNED IN SUCCESSFULLY", Toast.LENGTH_LONG).show();
if (mAuth.getCurrentUser() != null) {
HashMap<String, Object> map = new HashMap<>();
map.put("TEST USER ", mAuth.getCurrentUser());
mUserRef.push().updateChildren(map);
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish();
} else {
//not signed in
Toast.makeText(getApplicationContext(), "SIGN IN FAILED", Toast.LENGTH_LONG).show();
return;
}
} else {
// Sign in failed
if (response == null) {
// User pressed back button
Toast.makeText(getApplicationContext(), "SIGN IN CANCELLED", Toast.LENGTH_LONG).show();
return;
}
if (response.getErrorCode() == ErrorCodes.NO_NETWORK) {
Toast.makeText(getApplicationContext(), "NO INTERNET CONNECTION", Toast.LENGTH_LONG).show();
return;
}
if (response.getErrorCode() == ErrorCodes.UNKNOWN_ERROR) {
Toast.makeText(getApplicationContext(), "UNKNOWN ERROR", Toast.LENGTH_LONG).show();
return;
}
}
}
}
}
EDIT: I have added the complete activity
EDIT: My log is running very quickly and then the error is automatically deleting before I can read it, it might actually be a StackOverflow.
The error code is only valid if an error actually occurred by checking the onActivityResult result code, otherwise it just returns -1 (Activity.RESULT_OK) as you've noticed. Here's an example from the sample:
private void handleSignInResponse(int resultCode, Intent data) {
IdpResponse response = IdpResponse.fromResultIntent(data);
// Successfully signed in
if (resultCode == RESULT_OK) {
startSignedInActivity(response);
finish();
} else {
// Sign in failed
if (response == null) {
// User pressed back button
showSnackbar(R.string.sign_in_cancelled);
return;
}
if (response.getError().getErrorCode() == ErrorCodes.NO_NETWORK) {
showSnackbar(R.string.no_internet_connection);
return;
}
showSnackbar(R.string.unknown_error);
Log.e(TAG, "Sign-in error: ", response.getError());
}
}
I have an application which uses a Google PlacePicker and Google StreetView. I have to test the application with the device in aeroplane mode.
I want the application to check when it reaches this activity if aeroplane mode is active, if it is not active I would like a Toast displayed
Below is the code for an Activity an activity in which there are 2 buttons, one of the buttons loads the PlacePicker and the other loads another activity which contains the StreetView.
I have seen this How can one detect airplane mode on Android? answer and that is where I got the code I have attempted in my answer but it will not work
Can someone please tell me how to get this working
public class PlacePickerActivity extends AppCompatActivity {
int PLACE_PICKER_REQUEST = 1;
TextView tvPlace;
private Button buttonStepsActivity;
private Button buttonStreet;
private boolean isAirplaneModeOn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_picker);
tvPlace = (TextView)findViewById(R.id.tvPlace);
//StreetView
buttonStreet = (Button) findViewById(R.id.buttonStreet);
if(isAirplaneModeOn) {
Toast.makeText(this,"Aeroplane mode active",Toast.LENGTH_LONG).show();
}
}
private static boolean isAirplaneModeOn(Context context) {
return Settings.System.getInt(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
public void goPlacePicker(View v) {
// Construct an intent for the place picker
try {
PlacePicker.IntentBuilder intentBuilder =
new PlacePicker.IntentBuilder();
Intent intent = intentBuilder.build(this);
// Start the intent by requesting a result,
// identified by a request code.
startActivityForResult(intentBuilder.build(this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
String toastMsg = String.format("You have chosen: %s", place.getName());
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
}
}
}
Use this way
find network enable
public static boolean isNetworkAvailable(Context mContext) {
ConnectivityManager connectivity = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
find aeroplane mode enable
private static boolean isAirplaneModeOn(Context context) {
return Settings.System.getInt(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
add this permission
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
Hi I'm new in Android Development.
I have doing a lot of research .
Everything go rights however there is no any output sound from the text I entered.
Did I miss out any important part ?
The following bellow is the coding :
public class SpeechTextActivity extends Activity implements OnInitListener {
private int MY_DATA_CHECK_CODE = 0;
private TextToSpeech tts;
private EditText inputText;
private Button speakButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speech);
inputText = (EditText) findViewById(R.id.edit_speechText);
speakButton = (Button) findViewById(R.id.btn_speechOut);
speakButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String text = inputText.getText().toString();
if (text!=null && text.length()>0) {
Toast.makeText(SpeechTextActivity.this, "Saying: " + text, Toast.LENGTH_LONG).show();
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
}
}
});
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
tts = new TextToSpeech(this, this);
}
else {
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Toast.makeText(SpeechTextActivity.this,
"Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
}
else if (status == TextToSpeech.ERROR) {
Toast.makeText(SpeechTextActivity.this,
"Error occurred while initializing Text-To-Speech engine", Toast.LENGTH_LONG).show();
}
}
}
Just now I test in my tablet it work! But in my phone not workable =(
Change the implements OnInitListener to TextToSpeech.OnInitListener.
Try to unplug the USB cable from your phone before testing. TTS is recognized to encountered some issues in debug mode.