Espresso and Android contact picker - select

I try to add a contact with an Android contact picker by Espresso, but this does not work.
This is the command to invoke the contact picker:
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, RC_PICK_CONTACT);
The contact picker is shown, when I run Espresso test. OK, now I try to select a specific contact entry by display name (e.g. "Jake"). Unfortunately I don't know how to accomplish this. I've tried the following:
onData(withItemContent("Jake")).inRoot(withDecorView(not(is(getActivity().getWindow().getDecorView())))).perform(click());
I also tried this variation:
onView(withText("Jake")).inRoot(withDecorView(not(is(getActivity().getWindow().getDecorView())))).perform(click());
No success with both approaches. As already mentioned the contact picker is shown, but nothing is selected.
Any idea?

What you're experiencing is normal behavior, since the contact picker belongs to an external activity, whose user interface cannot be manipulated. Trying to assert anything will result in the tests stalling for some time and ending up with a
android.support.test.espresso.NoActivityResumedException: No activities in stage RESUMED. Did you forget to launch the activity. (test.getActivity() or similar)?
However, say hello to the new born Espresso-Intents, which is here to save my reputation:
Using the intending API (cousin of Mockito.when), you can provide a
response for activities that are launched with startActivityForResult
UPDATE
Below is my current solution which works fine but would need some decent code clean up:
#Test
public void testContactPickerResult(){
Intent resultData = new Intent();
resultData.setData(getContactUriByName("Joah"));
Instrumentation.ActivityResult result = new Instrumentation.ActivityResult(Activity.RESULT_OK, resultData);
intending(toPackage("com.google.android.contacts")).respondWith(result);
onView(withId(R.id.contactPickerLauncher))
.check(matches(isDisplayed()))
.perform(click());
onView(withId(R.id.pickedContact))
.check(matches(withText(getContactNumberByName("Joah"))));
}
In the launching activity, I would handle the incoming intent with the contact Uri and do whatever is necessary with it.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
TextView result = (TextView) findViewById(R.id.pickedContact);
if (requestCode == 42 && resultCode == RESULT_OK){
Uri contactUri = data.getData();
String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor cursor = getContentResolver().query(contactUri, projection, null, null, null);
cursor.moveToFirst();
int column = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String number = cursor.getString(column);
result.setText(number);
}
}
Also, the helper methods, to be modified accordingly:
public Uri getContactUriByName(String contactName) {
Cursor cursor = mActivityRule.getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if (name.equals(contactName)) {
return Uri.withAppendedPath(ContactsContract.Data.CONTENT_URI, id);
}
}
}
return null;
}

Related

Xamarin.Android: Receive View and Send actions in an already running instance of an App (LaunchMode is SingleTop)

I want my app to be a viewer and send target for PDFs but don't want it to create new instances everytime. How do I catch the view intent action in my MainActivity? I tried OnNewIntent() but it doesn't get called. Only if the app wasn't already running, I get the action in OnCreate(). What am I missing?
[Activity (Theme = "#style/MainTheme", Label = "MyPdfViewer", Icon = "#drawable/icon", /*MainLauncher = true, --> SplashActivity is now the MainLauncher */LaunchMode = LaunchMode.SingleTop, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
[IntentFilter(new[] { Intent.ActionSend }, Categories = new[] { Intent.CategoryDefault }, DataMimeType = #"application/pdf")]
[IntentFilter(new[] { Intent.ActionView }, Categories = new[] { Intent.CategoryDefault }, DataMimeType = #"application/pdf")]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
LoadApplication (new App ());
// handle clipboard data "send to" or "view document" actions
if (Intent.Type == "application/pdf")
{
HandleSendOrViewAction();
}
}
protected virtual void OnNewIntent()
{
var data = this.Intent.Data; // <-- never called
// do similar thing like in HandleSendOrViewAction()
}
private bool HandleSendOrViewAction()
{
// Get the info from ClipData
var pdf = Intent.ClipData.GetItemAt(0);
// Open a stream from the URI
byte[] bytes;
Stream inputStream;
if (Intent.Action == Intent.ActionSend)
inputStream = ContentResolver.OpenInputStream(pdf.Uri);
else if (Intent.Action == Intent.ActionView)
inputStream = ContentResolver.OpenInputStream(Intent.Data);
else
return false;
using (StreamReader sr = new StreamReader(inputStream))
{
MemoryStream ms = new MemoryStream();
inputStream.CopyTo(ms);
bytes = ms.ToArray();
}
Services.PdfReceiver.Base64Data = Convert.ToBase64String(bytes);
return true;
}
but don't want it to create new instances everytime.
The standard and singleTop of Launch Mode would create multiple instances. if you do not want create instance every time, you could use singleTask and singleInstance instead.
For singleTop Launch Mode, you need to know, if an instance of the activity already exists at the top of the target task, the system routes the intent to that instance through a call to its onNewIntent() method, rather than creating a new instance of the activity. If the instance of the activity which already exists is not at the top, it would not call onNewIntent() method.
That's why i suggest to use singleTask. The system creates the activity at the root of a new task and routes the intent to it. However, if an instance of the activity already exists, the system routes the intent to existing instance through a call to its onNewIntent() method, rather than creating a new one.
Using SingleTop launch mode is correct. The reason that OnNewIntent() is not being called is that you have declared it like this:
protected virtual void OnNewIntent()
That isn't correct. The signature is wrong. You need to declare it like this:
protected override void OnNewIntent(Intent intent)

How to give a user the option to select bsckground of a linearlayout from DxsettingsActivity that targets the MainActivity?

I want the user to be able to go into settings of my app and select from the images provided or select a photo from their internal or external storage to be applied to the background of the MainActivity. Also I want this image to stay even after the app has been killed until the user decides to change the background again. I have tried multiple codes and I run into errors every time and the main problem I'm having is sending this intent from one Activity to another. I have used code that allow me to apply an image to an ImageView within the same Activity but I cannot take that code and get it to send across to another Activity.
Targets:
LinearLayout - backgroundtop (MainActivity)
Imageview(onClick) - gallery (DxsettingsActivity)
Imageview(onClick) - dx (DxsettingsActivity)
"Gallery" and "dx" are in a customview dialog.
When "gallery" is clicked internal/external storage is opened to select background resource of "backgroundtop" and save that image until user changes it again.
When "dx" is clicked it opens DxWallpaperActivity which will have the images to be selected and saved as the background of "backgroundtop".
I hope I have explain well enough. I'll provide more info if needed. Thank you in advance. I have been struggling with this for days to no avail.
Update: I have managed to accomplish setting and saving images from in-app images to the background. I have tried everything under the sun to pull image from gallery and do the same. I have managed to open gallery and select an image but I can't figure out onActivityResult then send that to the background. Please help.
This is the only code I've got to work but it doesn't have shared preferences and it for an imageview. How can I change it for backgroundresource on linearlayout?
}
private static final String STATE_IMAGE_URI =
"STATE_IMAGE_URI";
private Uri imageUri;
public void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
if (imageUri != null ) {
state.putParcelable(STATE_IMAGE_URI, imageUri);
}
}
public void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
if(state == null || !state.containsKey(STATE_IMAGE_URI))
return;
setImage((Uri) state.getParcelable(STATE_IMAGE_URI));
}
private static final int IMAGE_REQUEST_CODE = 9;
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select picture"), IMAGE_REQUEST_CODE);
}
public void onActivityResult(int requestCode, int.
resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode != IMAGE_REQUEST_CODE) {
return;
}
if (resultCode != Activity.RESULT_OK) {
return;
}
setImage(data.getData());
}
private void setImage(Uri uri) {
imageUri = uri;
imageview1.setImageURI(uri);
}
private void nothing() {
And for the button clicked
chooseImage();

onActivityResult never fires unless I use getActivity() when calling startActivityForResult from a Fragment

My main activity opens a dialog fragment with 2 items in a listview. Clicking either one starts a new Activity. Unless I use getActivity().startActivityForResult() my code for onActivityResult never runs. Everything I've read here discourages using getActivity().startActivityForResult() and says just use startActivityForResult(). Normally I'd say "doesn't matter, code works" but its driving me nuts why its discouraged so much and why it won't work without getActivity(). I've been pouring over documentation and can't find an answer, help me stackoverflow, you're my only hope.
My onActivityResult() code located in my main activity (Landing.class):
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
String s = "";
Session current = new Session();
Gson gson = new Gson();
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
s = data.getStringExtra("SESSION_JSON");
current = gson.fromJson(s, Session.class);
}
}
sessions.add(current);
adapter.notifyDataSetChanged();
}
Code that calls startActivityForResult() located in my DialogFragment class:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
dismiss();
if (position == 0) {
Intent intent = new Intent(getActivity(), ActiveSessionActivity.class);
getActivity().startActivityForResult(intent, 1);
}
}
Code in ActiveSessionActivity class that should be returning the result to onActivityResult() in my main activity:
public void saveSession(View v) {
Session session;
Gson gson = new Gson();
String json = gson.toJson(session);
Intent intent = new Intent();
intent.putExtra("SESSION_JSON", json);
setResult(RESULT_OK, intent);
finish();
}
Android DialogFragments are still fragments, as such calling startActivityForResult from your dialog will actually be getting the result in the dialog. If you were to implement onActivityResult in your DialogFragment you'll get your callback. The reason getActivity().startActivityForResult() is discouraged is because the dialog has no control of the activity and it might not be attached anymore. Try...
if (getActivity() != null && !isDetached() && !isRemoving()) {
getActivity().startActivityForResult(...);
}

Efficient method to Update using JAX-RS

I am working on a JPA/Jersey web app and want to know if there is a better way to update a record. Currently, I am doing:
#PUT
#Path("update/{id}")
#Produces("application/json")
#Consumes("application/x-www-form-urlencoded")
public Response createDevice(
#PathParam("id") int id,
#FormParam("name") String name,
#FormParam("type") int type
/*MultivaluedMap<String, String> formParams*/
) {
try {
Devices newDevice = entityManager.find(Devices.class, id);
if(name==null){name=newDevice.getName();}
if(type != newDevice.getType()){newDevice.setType(type);}
newDevice.setName(name);
//newDevice.setType(type);
entityManager.merge(newDevice);
return Response.status(201).entity(new ResponseObject("success")).build();
} finally {
entityManager.close();
}
}
This works, but if my Devices table had more fields, I would have to check for equality of ALL fields with the values on the original object to see if they've changed, so that my
entityManager.merge(newDevice);
will only change the values passed in.
Is there a better way to do this?

How can i repeat same activity after user has chosen right option?

ImageView Iv2 = (ImageView)findViewById(R.id.imageView2);
textId++;
String imgId = "full_" + textId;
int Ivid = getResources().getIdentifier(imgId, "drawable", getPackageName());
Iv2.setImageResource(Ivid);
Iv2.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
clapping = MediaPlayer.create(textBasedquiz.this, R.raw.applause);
clapping.start();
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
return true;
}
});
*Basically im trying to build an quiz for kids and in this im selecting images randomly i want to restart same code after user has touch on right image so he/she can get another question , but activity must start after sound has been played Please Guys help me i really need your valued comments *
You can setResult and go to activity from where you have called your this activity. Pass the value along and based on result of value received, call the saem activity passing new value that you just got from the same activity.
static int RESULT_OK = 100;
STATIC INT RESULT_CANCEL = 110;
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(resultCode) {
case RESULT_OK:
// Get flags/values from intent Intent.FLAG_ACTIVITY_NO_ANIMATION
// Create new activity setting the intent to call
// and pass the values
startActivity(intent);
break;
}
}
I think this will be more straight forward rather than calling same Activity from itself only.