I have a listview with a couple of strings in at the moment. when a user selects one it brings up an alertdialog box which gives the option to book(this is going to be a taxi app) or cancel. What i cant work out is how to get it so that when the user clicks "Book" it takes the information they've selected and loads up a new view with more contact information.
My Code is currently this -
public class ListTaxi extends ListActivity{
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] taxi = getResources().getStringArray(R.array.taxi_array);
setListAdapter(new ArrayAdapter<String>(this, R.layout.listtaxi, taxi));
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id)
{
AlertDialog.Builder adb=new AlertDialog.Builder(ListTaxi.this);
adb.setTitle("Taxi Booking");
adb.setMessage("You have chosen = "+lv.getItemAtPosition(position));
adb.setPositiveButton("Book", null);
adb.setNegativeButton("Cancel", null);
adb.show();
}
});
Any help or pointers with this would be immensely appreciated as its the last bit i need to get working before its almost done.
Thanks everyone
Oli
You need to put an onClickListener onto your positive button, which will launch the new activity and pass the data to it. Your code would become something like:
public class ListTaxi extends ListActivity{ /** Called when the activity is first created. */ public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String[] taxi = getResources().getStringArray(R.array.taxi_array);
setListAdapter(new ArrayAdapter<String>(this, R.layout.listtaxi, taxi));
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id)
{
final int selectedPosition = position;
AlertDialog.Builder adb=new AlertDialog.Builder(ListTaxi.this);
adb.setTitle("Taxi Booking");
adb.setMessage("You have chosen = "+lv.getItemAtPosition(position));
adb.setPositiveButton("Book", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getApplicationContext(), NextActivity.class);
intent.putExtra("booking", taxi[selectedPosition];
startActivity(intent);
}
});
adb.setNegativeButton("Cancel", null);
adb.show();
}
});
In your target activity, have something like this:
Intent intent = getIntent();
String booking = "";
if (intent != null) {
Bundle extras = intent.getExtras();
if (extras != null) {
booking = extras.getString("booking");
}
}
One way could be to get your item out of your taxi list:
taxi.get(position);
and pass it through an intent to a next activity:
Intent intent = new Intent(this, YOUR_NEXT_ACTIVITY.class);
intent.putExtra("booking", taxi.get(position);
on the next activity you can get it with:
intent = getIntent();
inten.getExtra("booking");
// could be (not sure): inten.getExtraString("booking");
You can use this method from alertDialog class
public void setButton (int whichButton, CharSequence text, DialogInterface.OnClickListener listener)
Refer link
http://developer.android.com/reference/android/app/AlertDialog.html
depending on positive response, say book is positive response then start another activity which shows details contact info, pass the select item from list as Bundle or extra with intent while starting another activity.
Related
I want to pass values to list view by clicking a button. Problem is I want to make a list by gaining values from different activities with several buttons.
For Example :
In EnglandActivity if I click Button Visit I want to pass "England" to ListView in MainActivity,
In MalaysiaActivity pass "Malaysia" to ListView in MainActivity.
I dont know how to do that, Can you help me??
First Of All, You should write this on your onCreate() method of MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String data;/*For Storing Country Name*/
ListView listview = (ListView)findViewById(R.id.listView); /*Finding ListView From Layout*/
ArrayList<String> list = new ArrayList<String>(); /*ArrayList To Store All The Data Of ListView*/
ArrayAdapter adapter= new ArrayAdapter<String>(this,R.layout.android.R.layout.simple_list_item_1,list);/*Defining ArrayAdapter For ListView*/
listview.setAdapter(adapter); /*Setting Adapter To ListView*/
Bundle intentExtras = getIntent().getExtras(); /*Getting The Intent Extras Sent By The Activity Which You Had Navigated From*/
if(intentExtras != null) {/*Checking For Null*/
data= intentExtras.getString("countryName");/*Extracting The Data From The Intent Extras*/
list.add(0,data);/*You Can Replace 0 With The Position Of Your Wish*/
} else {
data=null;
}
}
Now Write This In The OnClickListener() Method Of Button On Each CountryNameActivity.java
btn.setOnClickListener(new OnClickListener() {/*Setting The Click Listener*/
#Override
public void onClick(View v) {
Intent intent = new Intent(this,MainActivity.this)/*Defining The Intent*/
intent.putExtra("countryName","CountryName");/*Putting The Data To Pass To The Next Activity*/
startActivity(intent);/*Starting The Activity*/
}
});
Make an object shared by all of your activity, put your data there and read them when you must put data into your ListView's adapter
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
Intent listIntent = new Intent(getApplicationContext(), YourActivity.class);
listIntent.putExtra("country", yourList.get(position));
startActivity(listIntent);
}
});
in next activity onCreate:
String country;
Bundle extras = getIntent().getExtras();
if(extras == null) {
country= null;
} else {
country= extras.getString("country");
}
So i am having this listview in my MainActivity, which is updated every time the main activity is started or resumed.
The code for that is
#Override
public void onResume()
{
super.onResume();
Cursor array_list_patients = mydb.getAllPatientsDetails();
PatientAdapter arrayAdapter = new n
PatientAdapter(this,array_list_patients);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
}
Now for the listview in the MainActivity i have a setOnItemClickListener as shown below, which basically displays the data in another activity "ModifyPatient". Code for that is:
Cursor array_list_patients = mydb.getAllPatientsDetails();
final PatientAdapter arrayAdapter = new PatientAdapter(this,array_list_patients);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
Cursor cur = (Cursor) arrayAdapter.getItem(arg2);
cur.moveToPosition(arg2);
int id_To_Search = cur.getInt(cur.getColumnIndexOrThrow("id"));
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(),ModifyPatient.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
Now in the ModifyPatient class.. i can do Upate/Delete operations on the database entry. Now the problem is, when i do a delete operation and return back to the MainActivity, and click on any item in the listview, i get an OutOfBounds exception for the cursor. The current code for delete button in the ModifyPatient class is as follows:
deleteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(ModifyPatient.this);
builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mydb.deletePatient(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted Successfully",
Toast.LENGTH_SHORT).show();
ModifyPatient.this.finish();
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
}
});
This deletes the entry and returns to the mainactivity, but clicking on any of the items in the listview throws the error which i mentioned before.
I have done a small workaround, where i have replaced the below line:
ModifyPatient.this.finish();
with
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
But the problem with this is, the original activity remains in the background and a new MainActivity is forked. So pressing the back button, goes back to the original activity with the stale listview.
If somebody can help me out, with how to update the cursor, because i could not implement the swapcursor in my case. I am not sure what i am doing wrong.
Thank you in advance.
i set my variable "arrayAdapter" present in the onResume and onItemClickListener in the MainActivity from local to global, and that did the trick.
New code, where arrayAdapter is global:
public void onResume()
{
super.onResume();
Cursor array_list_patients = mydb.getAllPatientsDetails();
arrayAdapter = new PatientAdapter(this,array_list_patients);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
}
and
arrayAdapter = new PatientAdapter(this,array_list_patients);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
Cursor cur = (Cursor) arrayAdapter.getItem(arg2);
cur.moveToPosition(arg2);
int id_To_Search = cur.getInt(cur.getColumnIndexOrThrow("id"));
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(),ModifyPatient.class);
intent.putExtras(dataBundle);
startActivity(intent);
arrayAdapter.notifyDataSetChanged();
}
});
I have created a list. Now when I click on the list item I want to run a Java class which is another list of names.
Here is my code:
public class SecondAct extends ListActivity {
private String[] items = { "Pending Retailers", "Ordered Retailers",
"No Order Retailers", "Today's Plan", "Messages", "Daily Sales",
"Pending Invoices", "Day Close", "Tools and Updates", "Exit" };
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, items);
// Get the activity's ListView and set its choice mode as multiple choice
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
setListAdapter(adapter);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String selectionValue = "";
selectionValue = (String) getListView().getItemAtPosition(position);
Log.i("List Selection Value: ",
(String) getListView().getItemAtPosition(position));
if (selectionValue.equalsIgnoreCase("Pending Retailers")) {
Intent intent = new Intent("my.com.npi.List");
startActivity(intent);
AlertDialog alertDialog = new AlertDialog.Builder(SecondAct.this)
.create();
alertDialog.setTitle("Pending Retailers Selected");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here we i add functions
}
});
// alertDialog.setIcon(R.drawable.icon);
alertDialog.show();
}
else if (selectionValue.equalsIgnoreCase("Exit")) {
finish();
}
}
}
Now when I click on the first item, the application is forcefully closed. I used intent to start the new activity but it isn't working. Hopelessly stuck! Please help.
Thanks.
if you have Activity in your own Application then use:
Intent electIntent = new Intent();
electIntent.setClass(SecondAct.this, List.class);
startActivity(electIntent);
and in AndroidManifest
<activity
android:name = ".List" />
use this intent for starting another app Activity from your appliction:
Intent intent25 = new Intent(Intent.ACTION_MAIN).addCategory(
Intent.CATEGORY_LAUNCHER).setClassName("APP_PACKAGE_NAME",
"APP_PACKAGE_NAME.TestActivity").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.addFlags(Intent.FLAG_FROM_BACKGROUND).setComponent(new ComponentName("APP_PACKAGE_NAME",
"APP_PACKAGE_NAME.TestActivity"));
getApplicationContext().startActivity(intent25);
First Register The New Activity in Manifest as
Before the application tag in manifest declare package like
<package name="my.com.npi">
<activity android:name = ".List" />
then
give Correct Correct Class name in the Intent.don't use like my.com.npi
just import those package give the plain name as List.class
Intent intent = new Intent(this,List.class);
startActivity(intent);
Hi I was wondering how I can get my Search Activity to return a result back to the Activity that started it.
I currently have a Search Dialog implemented (meaning the search Activity starts once the Search button on the phone is clicked).
Here is my code for the Search activity which is a list view.
public class ItemFinder extends ListActivity {
public static final int REQUEST_CODE = 1; // get it?
Vector<String> upcCodes;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
upcCodes = new Vector<String>();
ListView lv = (ListView) findViewById(android.R.id.list);
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
String upc = upcCodes.elementAt(position);
setResult(RESULT_OK);
}
});
// Get the intent, verify the action and get the query
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
ProgressDialog dialog = ProgressDialog.show(ItemFinder.this, "Searching",
"Searching. Please wait...", true);
performSearch(query);
dialog.hide();
dialog.dismiss();
}
}
public void performSearch(String query){
String result = new SmartShopClient().SearchItems(query);
List<String> dataList = new ArrayList<String>();
String _parsedResult[] = result.split("\\n");
for( int i = 0; i<_parsedResult.length; i++){
String _splitData[] = _parsedResult[i].split("\\|");
String itemName = _splitData[0];
String itemUPC = _splitData[1];
dataList.add(itemName);
upcCodes.add(itemUPC);
}
ArrayAdapter<String> arr = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList);
this.setListAdapter(arr);
}
}
So the search is working all fine and dandy, but I want it so when I click one of the results in the ListView, for it to return data back to the main activity with some data, say the name of the clicked searched result.
Thanks.
What you want to do is launch the search using startActivityForResult. See an explanation here.
This way, you can pass your search results back to the activity which launched it.
That would happen in your setOnItemClickListener method, where you could launch an explicit intent naming the desired activity with extra data.
Edit : I'm not quite sure of how startActivityForResult() would be implemented since we're talking about the search activity of the application, meaning it's launched by the Android search specific module ; that's why i suggested the above solution.
I ended up doing this:
public boolean onSearchRequested() {
askSearchQuery();
return true;
}
public void sendSearchRequest(String query){
Intent mIntent = new Intent(this, ItemFinder.class);
mIntent.setAction(Intent.ACTION_SEARCH);
mIntent.putExtra(SearchManager.QUERY, query);
startActivityForResult(mIntent, ItemFinder.REQUEST_CODE);
}
public void askSearchQuery() {
final EditText input = new EditText(SmartShop.this);
AlertDialog.Builder adb = new AlertDialog.Builder(SmartShop.this);
adb.setTitle("Search Items");
adb.setMessage("Please input the name of the item you are looking for.");
adb.setView(input);
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable upc = input.getText();
sendSearchRequest(upc.toString());
dialog.cancel();
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
adb.create().show();
}
And then I hooked the
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
I have an app, that shows a list of friends (each friend haves fullName and movilephone).
I'm using a variation of the listActiviti example of android developers guide
can someone complete my code or tell me code examples of how to put a button on the right side of the items of each list, that when the user press on that button, the phone calls to the phone number of that user. Also, now, when the user press on the list item (but not on the button) it's opened a new activity for showing details of the friend... this functionality haves to be working separatedly of the button
this is my list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
and this is my code for the listActivity:
public class AllActivity extends ListActivity {
RemoteConnection con; //conexion remota
private List<Friend> friends; //lista de amigos
private List<String> usernames; //lista de usernames de amigos, para rellenar el listview
static SharedPreferences settings;
static SharedPreferences.Editor configEditor;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
settings=PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
configEditor = settings.edit();
friends = new ArrayList<Friend>();
usernames = new ArrayList<String>();
con = new RemoteConnection();
actualizar();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == 1) {
setResult(1);
finish();
}
}
public void onResume() {
super.onResume();
}
public void actualizar()
{
friends = MyApplication.getDatabaseAdapter().retrieveAllFriends();
usernames.clear();
for (int i=0;i<friends.size();i++)
{
usernames.add(i,friends.get(i).getFullName());
}
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, usernames));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Bundle bundle = new Bundle(); //bundle is like the letter
bundle.putString ("user", friends.get(position).getFullName()); //arg1 is the keyword of the txt, arg2 is the txt
bundle.putString ("email", friends.get(position).getEmail());
bundle.putString ("permission", friends.get(position).getPermission());
Intent i=null;
if (friends.get(position).getPermission().equals("total"))
i = new Intent (AllActivity.this, Locate.class);
else if (friends.get(position).getPermission().equals("perhours"))
i = new Intent (AllActivity.this, LocatePerHours.class);
else
i = new Intent (AllActivity.this, LocatePerDays.class);
i.putExtras(bundle);
startActivity(i);
}
});
}
}
To call from button click you can use this sol:
How to make a phone call in android and come back to my activity when the call is done?
and for problem solving to get back on ur activity try this sol:http://www.tutorialforandroid.com/2009/01/get-phone-state-when-someone-is-calling_22.html