I want to retrieve an objectID of an item (to be specific, it's a class called "Room" in our Parse Model) clicked within a ListView.
And after that, I want to pass the retrieved ObjectID to another class using Intent.
I tried parse docs' getObjectId(); method but seems like it won't work.
How should I retrieve it?
Here's my code.
Button createBtn;
Button searchBtn;
Button myGroupBtn;
Button settingBtn;
String[] courses;
List<String> listItems;
ArrayAdapter<String> adapter;
ListView listView;
TextView textView;
// when CREAT button is tapped
public void createBtn(View view){
Intent i = new Intent(getApplicationContext(), Create.class);
// Removes animation
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(i);
}
// when Setting button is tapped
public void settingBtn(View view) {
Intent i = new Intent(getApplicationContext(), Setting.class);
// Removes animation
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(i);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String courseName = intent.getStringExtra("courseName");
String courseNumber = intent.getStringExtra("courseNumber");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
// Making Links to Buttons on Create
createBtn = (Button) findViewById(R.id.createBtn);
searchBtn = (Button) findViewById(R.id.searchBtn);
myGroupBtn = (Button) findViewById(R.id.myGroupBtn);
settingBtn = (Button) findViewById(R.id.settingBtn);
//Chaning the button colors
searchBtn.setTextColor(0xFFFFFFFF);
createBtn.setTextColor(0xFFBFBFBF);
myGroupBtn.setTextColor(0xFFBFBFBF);
settingBtn.setTextColor(0xFFBFBFBF);
listView= (ListView)findViewById(R.id.listView);
textView= (TextView)findViewById(R.id.textView2);
textView.setText(courseName + " " + courseNumber);
listItems = new ArrayList<>();
ParseQuery<ParseObject> roomQuery = ParseQuery.getQuery("Room");
roomQuery.whereEqualTo("course" , courseName);
roomQuery.whereEqualTo("number" , courseNumber);
roomQuery.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
for (ParseObject room : objects) {
Log.i("Appinfo", String.valueOf(room.get("title")));
String stringToAdd = "";
String opened = String.valueOf(room.get("opened"));
String x;
if(opened.equals(true)){
x = "Open";
}else{
x = "Closed";
}
stringToAdd = stringToAdd + String.valueOf(room.get("studyDate")) + " " +
String.valueOf(room.get("category")) + " " + x + "\n"
+ String.valueOf(room.get("title")) +
" "
;
listItems.add(stringToAdd);
Log.i("Appinfo", "A");
}
} else {
Log.i("Appinfo", "B");
e.printStackTrace();
}
}
});
initList();
}
public void initList() {
Log.i("Appinfo", "C");
adapter = new ArrayAdapter<String>(this, R.layout.list_two, R.id.txtvw, listItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), Room.class);
String category = listItems.get(position);
}
}
Your problem is that you loose the objectId of Parse in your "Adapter": you use Strings and the basic android Adapter (there: new ArrayAdapter<String>(this, R.layout.list_two, R.id.txtvw, listItems);) to display your elements; the problem is that converting your complicated Room object into String which does not contain a lot of informations makes you loose the objectId you want to keep.
The solution to your problem is a very Android-ish pattern called Adapter or more specifically for this case a Custom Adapter which will explain to the device how to render your Room elements into every cell of your app's ListView.
It is extremely well documented (much better that everything I could possibility write in this post) so here is the generic official doc and here is, to me, the best tutorial to get the concept.
PS: for a beginner, I recommend the Base Adapter, it is, to me, the simplest :)
Related
I'm trying to select an item in a ListView based on a value I get from an Intent. I've tried ListView.setSelection, but it's not working.
Intent i = this.getIntent();
String sp = i.getStringExtra("Sport");
for (int position = 0; position < sports.length; position++)
if (sports[position].equals(sp)) {
listView.setSelection(position);
}
Here is the rest of the code, for context:
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sport_item);
ListView listView = findViewById(R.id.listview);
String[] sports = new String[] {
"Soccer",
"Running",
"Swimming",
"Volleyball",
"Tennis"
};
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.listview, R.id.textView, sports);
listView.setAdapter(arrayAdapter);
Button btnSelect = findViewById(R.id.btnSelect);
listView.setChoiceMode(listView.CHOICE_MODE_SINGLE);
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ListView.getCheckedItemPosition() != -1) {
Intent i = new Intent(SportActivity.this, InformationActivity.class);
i.putExtra("Sport", sports[listView.getCheckedItemPosition()]); |
i.putExtra("Position", listView.getCheckedItemPosition());
setResult(Activity.RESULT_OK, i);
finish();
} else
Toast.makeText(SportActivity.this, "Ban chua lya chon", Toast.LENGTH_SHORT).show();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(SportActivity.this, "Sport selected :" + sports[i], Toast.LENGTH_SHORT).show();
}
});
Intent i = this.getIntent();
String sp = i.getStringExtra("Sport");
for (int position = 0; position < sports.length; position++)
if (sports[position].equals(sp)) {
listView.setSelection(position);
}
}
show more code, post it in here. you should call setSelected only after setting adapter, before there is no content on list so nothing gets selected
in your case your problem is caused probably by comparing Strings with == operator. in Java it compares objects and one obtained from intent and second one from array arent same objects, even if they have same content (they still are two objects in two separated placed in memory). use equals method for comparing only content
if(sports[position].equals(sp))
Hi I have been working through several different tutorials on getting data from a sql database into a listview. I can add data, get data from database and populate the list view, and have a working onclick listener (will fire off a Toast message). However I can not get any data from the listview when clicked. I have tried different combinations of getitem and getItemAtPosition but they all return a empty string(blank toast). Would someone be kind enough to look at my code and tell me if what I am trying to do is possible. In my listview i have four items in each entry, I would like to either get the fourth item directly or get all the items (as string?) then I can pull out the data I need.
Thanks in advance for your time.
public class ListViewActivity extends Activity {
SQLiteHelper SQLITEHELPER;
SQLiteDatabase SQLITEDATABASE;
Cursor cursor;
SQLiteListAdapter ListAdapter ;
ArrayList<String> ID_ArrayList = new ArrayList<String>();
ArrayList<String> GENRE_ArrayList = new ArrayList<String>();
ArrayList<String> NAME_ArrayList = new ArrayList<String>();
ArrayList<String> URL_ArrayList = new ArrayList<String>();
ListView LISTVIEW;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
LISTVIEW = (ListView) findViewById(R.id.listView1);
SQLITEHELPER = new SQLiteHelper(this);
}
#Override
protected void onResume() {
ShowSQLiteDBdata() ;
super.onResume();
}
private void ShowSQLiteDBdata() {
SQLITEDATABASE = SQLITEHELPER.getWritableDatabase();
cursor = SQLITEDATABASE.rawQuery("SELECT * FROM demoTable1", null);
ID_ArrayList.clear();
GENRE_ArrayList.clear();
NAME_ArrayList.clear();
URL_ArrayList.clear();
if (cursor.moveToFirst()) {
do {
ID_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_ID)));
GENRE_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Genre)));
NAME_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Name)));
URL_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Url)));
} while (cursor.moveToNext());
}
ListAdapter = new SQLiteListAdapter(ListViewActivity.this,
ID_ArrayList,
GENRE_ArrayList,
NAME_ArrayList,
URL_ArrayList
);
LISTVIEW.setAdapter(ListAdapter);
LISTVIEW.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// String text = (String) LISTVIEW.getAdapter().getItem(position);
String text = (String) LISTVIEW.getItemAtPosition(position);
//String text = (String) lv.getItemAtPosition(0);
// Object item = (Object) LISTVIEW.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
});
cursor.close();
}
}
LISTVIEW.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String value1 = ID_ArrayList.get(position);
String value2 = GENRE_ArrayList.get(position);
String value3 = NAME_ArrayList.get(position);
String value4 = URL_ArrayList.get(position);
Toast.makeText(getApplicationContext(),value1+" "+value2+" "+value3+" "+value4, Toast.LENGTH_SHORT).show();
}
});
try to change the line
String text = (String) LISTVIEW.getItemAtPosition(position);
with
String text = (String) parent.getItemAtPosition(position);
this should be the way ListView works.
Also i suggest you to not use Capital Cases with variables, usually in Java is used a CamelCase convention. And also have a look at RecyclerView, that usually is implemented today much more than ListView, because allow a great level of customization
Pls use below code within listview setOnItemClickListener :-
String genreID = ID_ArrayList.get(position);
String genre = GENRE_ArrayList.get(position);
String genreName = NAME_ArrayList.get(position);
String genreUrl = URL_ArrayList.get(position);
Toast.makeText(getApplicationContext(), genreID+", "+genre+","+genreName+", "+genreUrl+", "+, Toast.LENGTH_SHORT).show();
its return render data of listview.
try this,
ShowSQLiteDBdata() in onCreate() instead of onResume() method
I am an android beginner.
I am trying to give onClick event to the data in the listview. The data is getting from the mysql database and storing in the sqlite and it was displaying on the screen. I am not getting any idea how to give onClick event for that data. Please give me suggestion.
Thanks in advance.
I am trying develop a time table app. When the user clicks on a button the classes he have to attend on that day have to be display in a listview. When he clicks on the class he have to get details of that class.
public class tuesday extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
private String DATABASE_TABLE = SQLiteDB.DATABASE_TABLE;
private SQLiteDatabase newDB;
private static final String KEY_PERIODNO = "periodno";
private static final String KEY_PERIODNAME = "periodname";
private String id;
TextView periodno,periodname;
SQLiteDB sqlite_obj;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tuesday);
sqlite_obj = new SQLiteDB(tuesday.this);
Intent previous = getIntent();
id = previous.getStringExtra("id");
Log.i("id: ", " " + id);
select_seqlite();
}
private void select_seqlite() {
sqlite_obj.open();
Cursor c = sqlite_obj.gettuesdayData();
if (c.moveToFirst())
{
do {
DisplayContact(c);
} while (c.moveToNext());
}
sqlite_obj.close();
}
private void DisplayContact(Cursor c) {
Toast.makeText(getBaseContext(),
"\n" +"periodno: " + c.getString(2)+ "\n"+"periodname: " + c.getString(3)+ "\n", Toast.LENGTH_LONG).show();
TextView tview = new TextView(this);
tview.setText(" " + c.getString(2) +
" "+ c.getString(3));
getListView().addHeaderView(tview);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.activity_list_item,results));
getListView().setTextFilterEnabled(true);}}
In your activity, where you defined your listview
write this below code
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
ItemClicked item = adapter.getItemAtPosition(position);
Intent intent = new Intent(Activity.this,destinationActivity.class);
//based on item add info to intent
startActivity(intent);
}
});
And In your adapter's getItem you write
public ItemClicked getItem(int position){
return items.get(position);
}
I hope it might help you!
How can I get the name of a specific cell in my listview to load into a new activity ? At present, when I click any of the arrows it loads the last person in my contacts (Yvonne) in the next activity that loads when the arrow is clicked. I want the name in the corresponding cell to load in the next activity. How can I do this?
For example, in the image above, I want Alexi to load into the next Activity. But instead I keep getting Yvonne.
At present my code looks like this:
public class MainActivity extends Activity {
// ArrayList called selectContacts that will contain SelectContact info
ArrayList<SelectContact> selectContacts;
ListView listView;
SearchView search;
SelectContactAdapter adapter;
String name;
String phoneNumber;
String lookupkey;
CharSequence nameofcontact;
// *****18-04-2016***
Cursor cursor;
// ListView mainListView;
// ArrayList hashMapsArrayList;
public String cleartext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//selectContacts is an empty array list that will hold our SelectContct info
selectContacts = new ArrayList<SelectContact>();
listView = (ListView) findViewById(R.id.contacts_list);
search = (SearchView) findViewById(R.id.searchView);
//*** setOnQueryTextListener ***
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
adapter.filter(newText);
return false;
}
});
}
// Load data on background
class LoadContact extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
// Perhaps running this thread on the UI thread has solved the issue of the app
// crashing? ListView had not been updating properly, I think.
runOnUiThread(new Runnable() {
public void run() {
// we want to delete the old selectContacts from the listview when the Activity loads
// because it may need to be updated and we want the user to see the updated listview,
// like if the user adds new names and numbers to their phone contacts.
selectContacts.clear();
// we have this here to avoid cursor errors
if (cursor != null) {
cursor.moveToFirst();
}
try {
// get a handle on the Content Resolver, so we can query the provider,
cursor = getApplicationContext().getContentResolver()
// the table to query
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
// Null. This means that we are not making any conditional query into the contacts table.
// Hence, all data is returned into the cursor.
// Projection - the columns you want to query
null,
// Selection - with this you are extracting records with assigned (by you) conditions and rules
null,
// SelectionArgs - This replaces any question marks (?) in the selection string
// if you have something like String[] args = { "first string", "second#string.com" };
null,
// display in ascending order
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
// get the column number of the Contact_ID column, make it an integer.
// I think having it stored as a number makes for faster operations later on.
int Idx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
// get the column number of the DISPLAY_NAME column
int nameIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
// get the column number of the NUMBER column
int phoneNumberIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
// ****
int contactlookupkey = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY);
// ****
cursor.moveToFirst();
// We make a new Hashset to hold all our contact_ids, including duplicates, if they come up
Set<String> ids = new HashSet<>();
do {
System.out.println("=====>in while");
// get a handle on the contactid, which is a string. Loop through all the contact_ids
String contactid = cursor.getString(Idx);
// if our Hashset doesn't already contain the contactid string,
// then add it to the hashset
if (!ids.contains(contactid)) {
ids.add(contactid);
HashMap<String, String> hashMap = new HashMap<String, String>();
// get a handle on the display name, which is a string
name = cursor.getString(nameIdx);
// get a handle on the phone number, which is a string
phoneNumber = cursor.getString(phoneNumberIdx);
// String image = cursor.getString(photoIdIdx);
lookupkey = cursor.getString(contactlookupkey);
System.out.println("Id--->" + contactid + " Name--->" + name);
System.out.println("Id--->" + contactid + " Number--->" + phoneNumber);
System.out.println("Id--->" + contactid + " lookupkey--->" + lookupkey);
SelectContact selectContact = new SelectContact();
selectContact.setName(name);
selectContact.setPhone(phoneNumber);
selectContacts.add(selectContact);
}
} while (cursor.moveToNext());
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}});
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//into each inflate_listview, put a name and phone number, which are the details making
// our SelectContact, above. And SelectContacts is all these inflate_listviews together
// This is the first property of our SelectContactAdapter, a list
// The next part, MainActivity.this, is our context, which is where we want the list to appear
adapter = new SelectContactAdapter(selectContacts, MainActivity.this);
// adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
// Select item on listclick
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
listView.setFastScrollEnabled(true);
// we need to notify the listview that changes may have been made on
// the background thread, doInBackground, like adding or deleting contacts,
// and these changes need to be reflected visibly in the listview. It works
// in conjunction with selectContacts.clear()
// adapter.notifyDataSetChanged();
}
});
}}
//the is the arrow image, it opens the activity for show and edit
public void DisplayorEditContact(View v) {
System.out.println("works so far");
System.out.println(name);
Intent intent = new Intent(getApplicationContext(), EditorNewContact.class).putExtra("thecontactname",name);
startActivity(intent);
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onResume() {
//I want to clear the searchview text when my app resumes or closes, but I keep getting an error, my app shuts down
// cleartext = findViewById(R.id.searchView).toString();
// cleartext.isEmpty();
// search.setQuery("", false);
super.onResume();
// load the contacts again, refresh them, when the user resumes the activity
LoadContact loadContact = new LoadContact();
loadContact.execute();
// cursor.close();
}
}
The salient part of the code I believe is :
//the is the arrow image, it opens the activity for show and edit
public void DisplayorEditContact(View v) {
System.out.println("works so far");
System.out.println(name);
Intent intent = new Intent(getApplicationContext(), EditorNewContact.class).putExtra("thecontactname",name);
startActivity(intent);
}
And the child activity, into which I want Alexi to load (at present I keep getting Yvonne) looks like this :
public class EditorNewContact extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_contact);
String s= getIntent().getStringExtra("thecontactname");
System.out.println("the name is" + s);
EditText edittext = (EditText) findViewById(R.id.editText);
edittext.setText(s);
I was asked to share my SelectContactAdapter, so here it is :
public class SelectContactAdapter extends BaseAdapter {
//define a list made out of SelectContacts and call it _data
public List<SelectContact> _data;
//define an array list made out of SelectContacts and call it arraylist
private ArrayList<SelectContact> arraylist;
Context _c;
//define a ViewHolder to hold our name and number info, instead of constantly querying
// findviewbyid. Makes the ListView run smoother
ViewHolder v;
// RoundImage roundedImage;
public SelectContactAdapter(List<SelectContact> selectContacts, Context context) {
_data = selectContacts;
_c = context;
this.arraylist = new ArrayList<SelectContact>();
this.arraylist.addAll(_data);
}
#Override
public int getCount() {
return _data.size();
}
#Override
public Object getItem(int i) {
return _data.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
//we're naming our convertView as view
View view = convertView;
//if there is nothing there (if it's null) inflate the layout for each row
if (view == null) {
LayoutInflater li = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.inflate_listview, null);
// Log.e("Inside", "here--------------------------- In view1");
//or else use the view (what we can see in each row) that is already there
} else {
view = convertView;
// Log.e("Inside", "here--------------------------- In view2");
}
v = new ViewHolder();
// So, for example, title is cast to the name id, in activity main,
// phone is cast to the id called no etc
v.title = (TextView) view.findViewById(R.id.name);
// v.check = (CheckBox) view.findViewById(R.id.check);
v.phone = (TextView) view.findViewById(R.id.no);
v.imageView = (ImageView) view.findViewById(R.id.arrowright);
// for each new cell with title, name, number etc...
//
final SelectContact data = (SelectContact) _data.get(i);
v.title.setText(data.getName());
// v.check.setChecked(data.getCheckedBox());
v.phone.setText(data.getPhone());
view.setTag(data);
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
// _data is our list of contacts
_data.clear();
// If there is nothing in the searchview, if the charText length is 0,
// then show all the contacts
if (charText.length() == 0) {
_data.addAll(arraylist);
// or else....
} else {
for (SelectContact wp : arraylist) {
// If a contact's name matches the input thus far, which is charText,
// then include it in the listview.
if ((wp.getName().toLowerCase(Locale.getDefault())
.contains(charText)) || (wp.getPhone().toLowerCase(Locale.getDefault())
.contains(charText)))
{
_data.add(wp);
}
}
}
notifyDataSetChanged();
}
static class ViewHolder {
// In each cell in the listview show the items you want to have
ImageView imageView;
TextView title, phone;
// CheckBox check;
}
}
It is hard to predict how your code works without seeing the SelectContactAdapter source code. But I can suggest a probably easiest solution, which is using a tag
all you need to do is to set a tag to your arrow image somewhere in your adapter's getView method like this:
youArrowImage.setTag("here_is_a_name_of_a_row");
and then in your DisplayorEditContact(View v) you can access it like this:
String itemName = (String)v.getTag();
here I suppose that v is a reference to clicked arrow image
You could also just monitor the click in your ListView setOnItemClickListener.
// Click listener to bring to profile
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent viewProfileIntent = new Intent(getApplicationContext(), UserProfile.class);
viewProfileIntent.putExtra("name", selectContacts.get(position));
Log.i("User Tapped", selectContacts.get(position));
startActivity(viewProfileIntent);
}
});
Please add following line to your SelectContactsAdapter.java
final SelectContact data = (SelectContact) _data.get(i);
v.title.setText(data.getName());
v.phone.setText(data.getPhone());
// Please add this line to your existing code right after above lines
v.imageView.setTag(data.getName());
Modify your method as below
public void DisplayorEditContact(View v) {
System.out.println("works so far");
System.out.println(v.getTag().toString());
Intent intent = new Intent(getApplicationContext(), EditorNewContact.class).putExtra("thecontactname",v.getTag().toString());
startActivity(intent);
}
Hope this helps
Your this method will like this:
public void DisplayorEditContact(View v) {
TextView tvName = (TextView) v.findViewById(R.id.YOUR_TEXT_NAME);
System.out.println(tvName.getText().toString());
}
Hope this will solve your problem :)
You need to use onItemClickListener on your list view.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SelectContact contact = (SelectContact)parent.getItemAtPosition(position);
Intent secondActivity = new Intent(MainActivity.this, EditorNewContact.class);
secondActivity.putExtra("Key", contact);
startActivity(secondActivity);
}
});
Also, in your EditorNewContact activity, you will need to resolve this intent in the onCreate method, like:
Intent intent = getIntent();
SelectContact contact = (SelectContact) intent.get("Key");
Also, your SelectContact class can be Serializeable, If that is the can, the the intent will look like.
Intent secondActivity = new Intent(MainActivity.this, EditorNewContact.class);
secondActivity.putSerializeableExtra("Key", contact);
startActivity(secondActivity);
And, to resolve this:
Intent intent = getIntent();
SelectContact contact = (SelectContact) intent.getSerializableExtra("Key");
i hope this helps.
I have a menu (fishcombovaluemeals), and when the user select more than 1 item i want those
items to appear in a list in another activity (shopping cart) ,i have tried alot but the data
never appears in the shopping cart ! what is wrong in the onitemclick !? ,
I have
fishcombovaluemeal.java
RowItem.java
CustomListViewAdapter.java
fishcombovaluemealsactivitycode:
package com.example.newlist;
public class FishComboValueMeals extends Activity implements
OnItemClickListener {
ImageButton Ib2;
public static final String[] titles = new String[] {
" Fillet-O-Fish (Medium Value Meals) ",
"Fillet-O-Fish (Large Value Meals) ",
"Double Fillet-O-Fish (Medium Value Meals)",
" Double Fillet-O-Fish (Large Value Meals) ",
};
public static final String[] descriptions = new String[] {
"Light, flaky filet of white fish topped with tangy tartar ",
"Light, flaky filet of white fish topped with tangy tartar ",
"2 patties of tender fish filet over a layer of cheese, ",
" 2 patties of tender fish filet over a layer of "
};
public static final Integer[] images = {
R.drawable.imfc1,
R.drawable.imfc2,
R.drawable.imfc3,
R.drawable.imfc4 };
public static final Double[] prices = { 20.0, 22.73, 24.77, 27.04 };
ListView listView;
List<RowItem> rowItems;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_breakfast);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem (images[i], titles[i], descriptions[i],
prices[i]);
rowItems.add(item);
}
listView = (ListView) findViewById(R.id.list);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
Ib2 = (ImageButton) findViewById (R.id.Button02);
Ib2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generatedmethod stub
Intent openStartingPoint = new Intent (getApplicationContext(),ShoppingCart.class);
startActivity (openStartingPoint);
}
});}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent i = new Intent(getApplicationContext(), ShoppingCart.class);
i.putExtra("EXTRA", "Item " + (position + 1) + ": " + rowItems.get(position));
startActivity(i);
}
}
get the selected item of list view and send the value via intent
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String value = lv1.getItemAtPosition(position).toString();
Intent i = new Intent(getApplicationContext(), ShoppingCart.class);
i.putExtra("EXTRA", value);
startActivity(i);
}
and get the value in other activity
Bundle bundle=getIntent().getExtras();
String value=bundle.getString("EXTRA");
You can use a very simple Class which will store your data into it.
I warn you that this class is just a simple proposition how to solve your problem.
It has many weaknesses but it works ; )
You can improve it : )
Just init it at Application Class.
Here is example:
/**
* Manager to handle passing data between Activities
*
* #author Klawikowski
*
*/
public class ManagerBundle implements IConstants
{
public static final String TAG = "ManagerBundle";
private static Hashtable< Integer , Object > sDataTable;
public static void init()
{
Log.i( TAG , "[ManagerBundle] Initializing ..." );
sDataTable = new Hashtable< Integer , Object >();
}
public static void addBundle( int pKey , Object pObjectToPass )
{
Log.i( TAG , "[ManagerBundle] Adding Object to Manager using key: " + pKey );
sDataTable.put( pKey , pObjectToPass );
}
public static Object getBundle( int pKey )
{
Log.i( TAG , "[ManagerBundle] Getting Object from Manager using key: " + pKey );
Object lData = sDataTable.get( pKey );
sDataTable.remove( pKey );
return lData;
}
}
Just simply put an Table / Array or any other container before starting Activity, and collect it from 2nd one ; )
You need to create a singleton array of the menu items. When user performs multi select jst store the selectedindex to an array and then pass that array to the intent.
Here is the tutorial for multi-select listview
http://www.vogella.com/articles/AndroidListView/article.html
Here is the code to send array in intent
Bundle b=new Bundle();
b.putStringArray(key, new String[]{value1, value2});
Intent i=new Intent(context, Class);
i.putExtras(b);
Bundle b=this.getIntent().getExtras();
String[] array=b.getStringArray(key);
You can try this
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
RowItem selItem = rowItems.get(position);//get the selected RowItem from the list
String[] selValues= selItem.getMethodName();//your method name in RowItem.java class
//which returns array
//if you have getter and setters you can access them and put them in array
//String[] selArray = new String[size];//size = number of value you want to supply
//String[0]= selItem.getTitle();//for title
//String[1] = selItem.getDescription();//for description and so on
//then send the array as parameter
// remaining is same as answered by the Jay Gajjar
Bundle b=new Bundle();
b.putStringArray("EXTRA", selArray);
Intent i = new Intent(getApplicationContext(), ShoppingCart.class);
i.putExtras(b);
startActivity(i);
}
and to retrieve the values in the ShoppingCart class
Bundle b=this.getIntent().getExtras();
String[] array=b.getStringArray("EXTRA");