I have three activities:
-login
-choice
-entry
I Must pass the var "Name" from login to choice (and this work well) and then,from choice to entry,and this is where i have the problem :/
I can pass name to choice,but when i try to pass it to entry,i can't!
This is the code to pass from login to choice
Intent intent;
String pkg=getPackageName();
intent=new Intent(getApplicationContext(), scelta.class);
//inseriamo i dati nell'intent
String parts[] = risp.split("/");
intent.putExtra(pkg+".myNome", parts[0]);
intent.putExtra(pkg+".myId", parts[1]);
startActivity(intent);
this is choice(where probably is the error):
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scelta);
// l'intent di questa activity
Intent intent=getIntent();
String pkg=getPackageName();
//prendiamo i dati
String nome=intent.getStringExtra(pkg+".myNome");
String Id=intent.getStringExtra(pkg+".myId");
intent.putExtra(pkg+".myNome", nome);
intent.putExtra(pkg+".myId", Id);
TextView tvNome = (TextView) findViewById(R.id.txtNome);
tvNome.setText(nome);
}
//pulsante per il checkin
public void checkin (View v){
// l'intent di questa activity
Intent intent=getIntent();
String pkg=getPackageName();
//prendiamo i dati
String nome=intent.getStringExtra(pkg+".myNome");
String Id=intent.getStringExtra(pkg+".myId");
//li reinseriamo nell'intent
intent.putExtra(pkg+".myNome", nome);
intent.putExtra(pkg+".myId", Id);
intent=new Intent(getApplicationContext(), entrata.class);
startActivity(intent);
}
checkin is the method that I use when i tap on the button for pass from choice to entry.
And this is where i take name in Entry:
Intent intent=getIntent(); // l'intent di questa activity
String pkg=getPackageName();
String nome=intent.getStringExtra(pkg+".myNome"); //prendiamo i dati
TextView tvNome = (TextView) findViewById(R.id.nome);
tvNome.setText(nome);
In your checkin() method you add the extras and then you create a new Intent which replaces the local "intent" variable, effectively clearing the extras again. Reorder the last 4 lines of your checkin() method like this:
intent=new Intent(getApplicationContext(), entrata.class);
intent.putExtra(pkg+".myNome", nome);
intent.putExtra(pkg+".myId", Id);
startActivity(intent);
Related
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;
}
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(...);
}
This is ListView
<LinearLayout
… >
<ListView
android:id="#+id/listView1" >
</ListView>
</LinearLayout>
and 3 item at the сell
<TextView
android:id="#+id/text1" />
<TextView
android:id="#+id/text2" />
<Button
android:id="#+id/button1"/>
This is code
public class Spisok extends Activity {
private ArrayList<HashMap<String, Object>> Irr;
private static final String Form1 = "form1"; // Форма1
private static final String Form2 = "form2"; // Форма2
private static final String Form3 = "form3"; // Форма3
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spisok);
setTitle("Irr");
ListView listView = (ListView) findViewById(R.id.listView1);
// создаем массив списков
Irr = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> hm;
hm = new HashMap<String, Object>();
hm.put(Form1, "1");
hm.put(Form2, "2");
hm.put(Form3, "3");
Irr.add(hm);
hm = new HashMap<String, Object>();
hm.put(Form1, "1");
hm.put(Form2, "2");
hm.put(Form3, "3");
Irr.add(hm);
SimpleAdapter adapter = new SimpleAdapter(this, Irr,
R.layout.list_item, new String[] { Form1, Form2, Form3 },
new int[] { R.id.text1, R.id.text2, R.id.text3 });
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<> arg0, View arg1, int arg2,
long arg3) {
Intent intent = new Intent(this, New.class);
intent.putExtra("arraylist", Irr);
startActivity
}
});
and this:
ArrayList<HashMap<String, String>> arl = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("arraylist");
TextView Info = (TextView)findViewById(R.id.text9);
Info.setText("view" +Irr); }
But it is work as wrong. When I use it, I have all ArrayList in the new Activity
intent.putExtra("arraylist", Irr);
I need have only "hm.put(Form3, "3");" (correctly only "3" value) in my NewActivity.
Help me to consist it correctly.
What is your problem ? It is not clear, just i considered that you have a Button in your Spisok Activity . so you need to create a Button object in your noCreate() method as like
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new onClickListener() {
#Override
public void onClick (){
Intent intent = new Intent (this, SecondActivity.class );
startActivity(intent);
}
}
SecondActivity.class is your new Activity . you need to create this Activity class manually using IDE and also need to add this Activity in Manefist file. you can put your TextView text3 SecondActivity's layout file .
You have to put the text of your R.id.text3 into your intent with the method putExtra(String key, String dataToTransfer).
Your OnItemClickListener could look like this:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<> arg0, View arg1, int position,
long arg3) {
Intent intent = new Intent (this, SecondActivity.class );
intent.putExtra("key for my item 3", "put the text you want to transfer here")
startActivity(intent);
}
});
And in the new Activity you get the transfered data like this:
#Override
public void onCreate(Bundle savedInstanceState){
Intent intent = getIntent();
String transferedText = intent.getStringExtra("key for my item 3");
}
You have a custom ListView ( without coustom listview you cant manage more items in single row), in every row there are two text view and one button. you want if user click the button then open new activity that shows second textview
In your adapter class's getView() method write this code
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View row = convertView;
Button button1 = (Button) convertView.findViewById(R.id.button1);
TextView text1 = (TextView)convertView.findViewById(R.id.textview1);
TextView text2 = (TextView)convertView.findViewById(R.id.textview2);
button1.setOnClickListener(new OnClickListener()
{
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent (this, SecondActivity.class );
String text = text2.getText().toString();
intent.putExtra("name", "text");
startActivity(intent);
}
});
}
and SecondActivity write this code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.intent);
Textv = (TextView)findViewById(R.id.tv2);
Intent iin= getIntent();
Bundle b = iin.getExtras();
if(b!=null)
{
String j =(String) b.get("name");
Textv.setText(j);
}
}
Hope this would help you
I have a listview, I want to pass the Text of the listview to edittext of the another Activity.Can u help?
public class MainActivity extends Activity {
private ListView listView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Weather weather_data[] = new Weather[]
{
new Weather(R.drawable.weather_cloudy, "Cloudy"),
new Weather(R.drawable.weather_showers, "Showers"),
new Weather(R.drawable.weather_snow, "Snow"),
new Weather(R.drawable.weather_storm, "Storm"),
new Weather(R.drawable.weather_sunny, "Sunny")
};
WeatherAdapter adapter = new WeatherAdapter(this,
R.layout.listview_item_row, weather_data);
listView1 = (ListView)findViewById(R.id.listView1);
View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
}
When I click the first row,the next activity will show "Cloudy" as in the edittext.
You can create a listview onItemClickListener for ur listview and when user clicks on list item/row u can get the text from that row and u can pass it to next Activity that u r going to call and u r passing data via bundle and Intent like below
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
String text= arg0.getItemAtPosition(position)
Bundle bundle = new Bundle();
bundle.putString("URTEXT", text);
Intent intent = new Intent(MainActivity.this,
NextActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
});
In Next Activity U can get that data that u passed through bundle like this
Intent intent = getIntent();
String tEXT = intent.getIntExtra("URTEXT", 0);
EditText et= (EditText)findViewById(editTextID);
et.setText(tEXT, TextView.BufferType EDITABLE);
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.