I'm new to android studio, I came across this multiple contact picker and I want to get phone numbers in 1st activity and in the 2nd activity send messages to those selected numbers.
In my first activity I have -
new MultiContactPicker.Builder(MainActivity.this) //Activity/fragment context
.theme(R.style.MyCustomPickerTheme) //Optional - default: MultiContactPicker.Azure
.hideScrollbar(false) //Optional - default: false
.showTrack(true) //Optional - default: true
.searchIconColor(Color.WHITE) //Option - default: White
.setChoiceMode(MultiContactPicker.CHOICE_MODE_MULTIPLE) //Optional - default: CHOICE_MODE_MULTIPLE
.handleColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary)) //Optional - default: Azure Blue
.bubbleColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary)) //Optional - default: Azure Blue
.bubbleTextColor(Color.WHITE) //Optional - default: White
.setTitleText("Select Contacts") //Optional - default: Select Contacts
.setSelectedContacts("10", "5" / myList) //Optional - will pre-select contacts of your choice. String... or List<ContactResult>
.setLoadingType(MultiContactPicker.LOAD_ASYNC) //Optional - default LOAD_ASYNC (wait till all loaded vs stream results)
.limitToColumn(LimitColumn.NONE) //Optional - default NONE (Include phone + email, limiting to one can improve loading time)
.setActivityAnimations(android.R.anim.fade_in, android.R.anim.fade_out,
android.R.anim.fade_in,
android.R.anim.fade_out) //Optional - default: No animation overrides
.showPickerForResult(CONTACT_PICKER_REQUEST);
The numbers get stored in results which is also in 1st activity -
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CONTACT_PICKER_REQUEST){
if(resultCode == RESULT_OK) {
List<ContactResult> results = MultiContactPicker.obtainResult(data);
Log.d("MyTag", results.get(0).getDisplayName());
} else if(resultCode == RESULT_CANCELED){
System.out.println("User closed the picker without selecting items.");
}
}
}
I called the results in 2nd activity -
List<ContactResult> results = new ArrayList<>();
But when I print the output, it doesn't give any. How can I get it right. Thanks in advance.
You can set up intents when you are starting a new activity. Intents are a way to pass values from your current activity to the next and I'd suggest you learn the basics uses for them. Here's official documentation you can check out: https://developer.android.com/guide/components/intents-filters
When you start the other activity you can code the Intent like this:
//Code to start an activity
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("id", "YOUR_VALUE1");
intent.putExtra("title", "YOUR_VALUE2");
startActivity(intent);
On the SecondActivity.class you will get can then assign your value to a variable:
//Code on your second activity
public class FollowersActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent intent = getIntent();
String id = intent.getStringExtra("id");
String title = intent.getStringExtra("title");
//id will equal "YOUR_VALUE1"
//title will equal "YOUR_VALUE2"
First activity sent your data:-
// if you want to send on selected position data than pass position in place of zero (0).
Inent intent = new Intent(this, SecondActivity.class)
intent.putExtra("name", results.get(0).getName());
intent.putExtra("number", results.get(0).getNumber());
startActivity(intent)
// if you want to send the all the list in second activity using intent than
Intent intent = new Intent(this,SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("data", results);
intent.putExtras(bundle);
startActivity(intent);
Second activity get your data:-
// retrive selected position data
Intent intent = new Intent();
String name = intent.getStringExtra("name").toString();
String number = intent.getStringExtra("number").toString();
tv_name2.setText(name);
tv_number.setText(number);
// retrive result list from intent
Bundle bundle = getIntent().getExtras();
sharedBookingObject = bundle.getParcelable("data");
hope this answer will helpful for you...
Related
I have two Activity. I want pass LatLng pass to another Activity.
This code in first Activity:
public void testclick (View v){
Intent intent = new Intent(TestActivity.this, MainMenu.class);
intent.putExtra("lat", "58.37");
intent.putExtra("lan", "37.95");
startActivity(intent);
}
What I must write in another Activity to get LaTLng?
Intent intent = new Intent(getApplicationContext(), MainMenu.class);
intent.putExtra("lat", "`58.37`");
intent.putExtra("lan", "37.95")
startActivity(intent)
And MainMenu Activity onCreate() method receive
if(getIntent().getExtras() != null) {
String lat = getIntent().getExtras().getString("lat");
String lan = getIntent().getExtras().getString("lan");
}
How can I send information from one activity to two activities? I would like to add another intent but I get an error about a null object... My guess is that I also would need to use another spinner for this class but just wondering if there is a short cut?
add_review.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Review.this, Add_Review.class);
String chosenOption = spinner.getSelectedItem().toString();
intent.putExtra("Add a Review for", chosenOption);
startActivity(intent);
finish();
Intent send_information = new Intent(Review.this, PopularMedicalClinic.class);
String chosenOption2 = spinner.getSelectedItem().toString();
intent.putExtra("Name", chosenOption2);
startActivity(send_information);
finish();
}
This is a wrong approach in your code. You are trying to open two activity at a time. After starting first intent you call finish() method. finish() method kill current activity.
Can you explain why you want to open two activity at a time. Then I can suggest you.
Just use another extra putExtra method.
and remove finish() method. it will destroy your activity.
String chosenOption = spinner.getSelectedItem().toString();
String chosenOption2 = spinner.getSelectedItem().toString();
Intent intent = new Intent(Review.this, Add_Review.class);
intent.putExtra("Add_a_Review_for", chosenOption);
intent.putExtra("Name", chosenOption2);
startActivity(intent);
I want to open a new activity when search filter is clicked in recycler view of android studio.
An open source code may be found here that is given below. It has json file from where we can fetch the search filter item.
https://www.androidhive.info/2017/11/android-recyclerview-with-search-filter-functionality/
Please tell me the code that how we can get to new activity such as hello.xml when hello is being clicked in search filter item.
In my opinion the code should be here in mainactivity.java..
#Override
public void onContactSelected(Contact contact) {
String type = contact.getClass().getName();
if (type.startsWith("Tom")) {
Intent i = new Intent(MainActivity.this, MainActivity.class);
startActivity(i);
} else if (type.startsWith("")) {
Intent intent = new Intent(MainActivity.this, Hello.class);
startActivity(intent);
}
Please help to put my code instead of toast.
public void onContactSelected(Contact contact) {
// TextView name = (TextView) Contact;
if ( contact.getName().toString().equalsIgnoreCase("Tom Hardy"))
{
startActivity(new Intent(MainActivity.this, Hello.class));
finish();
}
else{
Toast.makeText(MainActivity.this, " no activity "+contact.getName(), Toast.LENGTH_SHORT).show();
}
}
I am working with orientation sensors,everything works except for notification. Notification is coming from sensor parameter values set in my code
My goal is controlling the notifications,as soon as the application loads before the defined sensor parameters are checked. There is a notification in the notification bar and when cleared comes right back.
The other goal is getting the notification to fire only when the sensor parameters are meet. The sensor parameters are correct I can see them in a log file and in a text view.
The final goal is to limit the notifications to the notification bar, as you can imagine moving the senor about can fire a lot of notifications.
Thanks for any help,
Still on the learning path.
Below is the relevant code area:
private SensorEventListener mySensorEventListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
String.valueOf(event.values[0]) ;
String.valueOf(event.values[1]);
String.valueOf(event.values[2]);
if (event.values[1]<-100)mVibrator.vibrate(new long[] { 0, 200, 0 }, 0);
else if
(event.values[1]>-75)mVibrator.vibrate(new long[] { 0, 200, 0 }, 0);
else mVibrator.cancel();
//We get a reference to the NotificationManager
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String MyText = "Reminder";
Notification mNotification = new Notification(R.drawable.ic_launcherone, MyText, System.currentTimeMillis() );
//The three parameters are: 1. an icon, 2. a title, 3. time when the notification appears
String MyNotificationTitle = "blah blah";
String MyNotificationText = "blah blah";
Intent MyIntent = new Intent(Intent.ACTION_VIEW);
PendingIntent StartIntent = PendingIntent.getActivity(getApplicationContext(),0,MyIntent, PendingIntent.FLAG_CANCEL_CURRENT);
//A PendingIntent will be fired when the notification is clicked. The FLAG_CANCEL_CURRENT flag cancels the pendingintent
mNotification.setLatestEventInfo(getApplicationContext(), MyNotificationTitle, MyNotificationText, StartIntent);
int NOTIFICATION_ID = 1;
notificationManager.notify(NOTIFICATION_ID , mNotification);
//We are passing the notification to the NotificationManager with a unique id.
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
};
I have an app that started with the Google's geofencing sample code. It works great for a few days, and I get all the transition intents as I anticipate. However, after a bit of time, something like 3 days, the app stops getting these intents, and I don't know why.
When I create my fences, I'm setting the expiration duration to Geofence.NEVER_EXPIRE
Here is my IntentService where I get the transition intents before they stop working:
public class ReceiveTransitionsIntentService extends IntentService {
#Override
protected void onHandleIntent(Intent intent) {
Intent broadcastIntent = new Intent();
broadcastIntent.addCategory(GeofenceUtils.CATEGORY_LOCATION_SERVICES);
// First check for errors
if (LocationClient.hasError(intent)) {
...handle errors
} else {
// Get the type of transition (entry or exit)
int transition = LocationClient.getGeofenceTransition(intent);
// Test that a valid transition was reported
if ((transition == Geofence.GEOFENCE_TRANSITION_ENTER)
|| (transition == Geofence.GEOFENCE_TRANSITION_EXIT)) {
// Post a notification
NEVER GETS HERE
} else {
...log error
}
}
}
}
Here is pertinent part of the manifest:
<service
android:name="com.aol.android.geofence.ReceiveTransitionsIntentService"
android:exported="false" >
</service>
In my GeofenceRequester class, it is almost identical to the sample code. Here are the pertinent parts:
// Get a PendingIntent that Location Services issues when a geofence transition occurs
mGeofencePendingIntent = createRequestPendingIntent();
// Send a request to add the current geofences
mLocationClient.addGeofences(mCurrentGeofences, mGeofencePendingIntent, this);
private PendingIntent createRequestPendingIntent() {
// Create an Intent pointing to the IntentService
Intent intent = new Intent(context, ReceiveTransitionsIntentService.class);
return PendingIntent.getService(
context,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
}
Can anyone see why this would stop working?
So after playing around with this a bit, it looks like the ReceiveTransitionsIntentService as defined in the sample code will stop getting the notifications when the app is not around. I think this is a big problem with the example code... Seems like that will trip folks like me up.
So I used a broadcast receiver instead, and so far it seems to be working from my tests.
Add this to the manifest:
<receiver android:name="com.aol.android.geofence.GeofenceReceiver"
android:exported="false">
<intent-filter >
<action android:name="com.aol.android.geofence.ACTION_RECEIVE_GEOFENCE"/>
</intent-filter>
</receiver>
Then in the GeofenceRequester class you need to change the createRequestPendingIntent method so that it goes to your BroadcastReceiver instead of the ReceiveTransitionsIntentService
private PendingIntent createRequestPendingIntent() {
// If the PendingIntent already exists
if (null != mGeofencePendingIntent) {
// Return the existing intent
return mGeofencePendingIntent;
// If no PendingIntent exists
} else {
// Create an Intent pointing to the IntentService
Intent intent = new Intent("com.aol.android.geofence.ACTION_RECEIVE_GEOFENCE");
// Intent intent = new Intent(context, ReceiveTransitionsIntentService.class);
/*
* Return a PendingIntent to start the IntentService.
* Always create a PendingIntent sent to Location Services
* with FLAG_UPDATE_CURRENT, so that sending the PendingIntent
* again updates the original. Otherwise, Location Services
* can't match the PendingIntent to requests made with it.
*/
return PendingIntent.getBroadcast(
context,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
}
Then I added the GeofenceReceiver class that looks something like this:
public class GeofenceReceiver extends BroadcastReceiver {
Context context;
Intent broadcastIntent = new Intent();
#Override
public void onReceive(Context context, Intent intent) {
this.context = context;
broadcastIntent.addCategory(GeofenceUtils.CATEGORY_LOCATION_SERVICES);
if (LocationClient.hasError(intent)) {
handleError(intent);
} else {
handleEnterExit(intent);
}
}
private void handleError(Intent intent){
// Get the error code
int errorCode = LocationClient.getErrorCode(intent);
// Get the error message
String errorMessage = LocationServiceErrorMessages.getErrorString(
context, errorCode);
// Log the error
Log.e(GeofenceUtils.APPTAG,
context.getString(R.string.geofence_transition_error_detail,
errorMessage));
// Set the action and error message for the broadcast intent
broadcastIntent
.setAction(GeofenceUtils.ACTION_GEOFENCE_ERROR)
.putExtra(GeofenceUtils.EXTRA_GEOFENCE_STATUS, errorMessage);
// Broadcast the error *locally* to other components in this app
LocalBroadcastManager.getInstance(context).sendBroadcast(
broadcastIntent);
}
private void handleEnterExit(Intent intent) {
// Get the type of transition (entry or exit)
int transition = LocationClient.getGeofenceTransition(intent);
// Test that a valid transition was reported
if ((transition == Geofence.GEOFENCE_TRANSITION_ENTER)
|| (transition == Geofence.GEOFENCE_TRANSITION_EXIT)) {
// Post a notification
List<Geofence> geofences = LocationClient
.getTriggeringGeofences(intent);
String[] geofenceIds = new String[geofences.size()];
String ids = TextUtils.join(GeofenceUtils.GEOFENCE_ID_DELIMITER,
geofenceIds);
String transitionType = GeofenceUtils
.getTransitionString(transition);
for (int index = 0; index < geofences.size(); index++) {
Geofence geofence = geofences.get(index);
...do something with the geofence entry or exit. I'm saving them to a local sqlite db
}
// Create an Intent to broadcast to the app
broadcastIntent
.setAction(GeofenceUtils.ACTION_GEOFENCE_TRANSITION)
.addCategory(GeofenceUtils.CATEGORY_LOCATION_SERVICES)
.putExtra(GeofenceUtils.EXTRA_GEOFENCE_ID, geofenceIds)
.putExtra(GeofenceUtils.EXTRA_GEOFENCE_TRANSITION_TYPE,
transitionType);
LocalBroadcastManager.getInstance(MyApplication.getContext())
.sendBroadcast(broadcastIntent);
// Log the transition type and a message
Log.d(GeofenceUtils.APPTAG, transitionType + ": " + ids);
Log.d(GeofenceUtils.APPTAG,
context.getString(R.string.geofence_transition_notification_text));
// In debug mode, log the result
Log.d(GeofenceUtils.APPTAG, "transition");
// An invalid transition was reported
} else {
// Always log as an error
Log.e(GeofenceUtils.APPTAG,
context.getString(R.string.geofence_transition_invalid_type,
transition));
}
}
/**
* Posts a notification in the notification bar when a transition is
* detected. If the user clicks the notification, control goes to the main
* Activity.
*
* #param transitionType
* The type of transition that occurred.
*
*/
private void sendNotification(String transitionType, String locationName) {
// Create an explicit content Intent that starts the main Activity
Intent notificationIntent = new Intent(context, MainActivity.class);
// Construct a task stack
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the main Activity to the task stack as the parent
stackBuilder.addParentStack(MainActivity.class);
// Push the content Intent onto the stack
stackBuilder.addNextIntent(notificationIntent);
// Get a PendingIntent containing the entire back stack
PendingIntent notificationPendingIntent = stackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// Get a notification builder that's compatible with platform versions
// >= 4
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context);
// Set the notification contents
builder.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(transitionType + ": " + locationName)
.setContentText(
context.getString(R.string.geofence_transition_notification_text))
.setContentIntent(notificationPendingIntent);
// Get an instance of the Notification manager
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
// Issue the notification
mNotificationManager.notify(0, builder.build());
}
}
Hopefully that helps someone else.
Following can be the reasons why the App is not getting Pending Intents according to the official google documentation -
1.The device is rebooted.
2.The app is uninstalled and re-installed.
3.The app's data is cleared.
4.Google Play services data is cleared.
5.The app has received a GEOFENCE_NOT_AVAILABLE alert.(When Android Location Provider gets switched off)
You have to re-register the geofence after these events.
In my case Location provider gets switched off and also device gets rebooted that's why I was not getting the pending intents.
In my case I had to clear Google Play Services app cache from the app settings, then everything started to work fine again.