如何在列表视图中获取特定单元格的名称以加载到新活动中?目前,当我单击任何箭头时,它会在单击箭头时加载的下一个活动中加载我的联系人(Yvonne)中的最后一个人。我希望相应单元格中的名称加载到下一个活动中。我怎么能这样做?
例如,在上图中,我希望Alexi加载到下一个Activity中。但我不断得到Yvonne。
目前我的代码如下:
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 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);
}
我希望Alexi加载的子活动(目前我一直得到Yvonne)看起来像这样:
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);
我被要求分享我的SelectContactAdapter
,所以在这里:
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;
}
}
答案 0 :(得分:2)
如果没有看到SelectContactAdapter
源代码,很难预测代码的工作原理。但我可以建议一个最简单的解决方案,即使用tag
您需要做的就是在适配器的getView
方法中的某个位置为箭头图像设置标记,如下所示:
youArrowImage.setTag("here_is_a_name_of_a_row");
然后在您的DisplayorEditContact(View v)
中,您可以像这样访问它:
String itemName = (String)v.getTag();
这里我假设v
是对点击箭头图像的引用
答案 1 :(得分:2)
您还可以监控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);
}
});
答案 2 :(得分:1)
你的这个方法会是这样的:
public void DisplayorEditContact(View v) {
TextView tvName = (TextView) v.findViewById(R.id.YOUR_TEXT_NAME);
System.out.println(tvName.getText().toString());
}
希望这能解决您的问题:)
答案 3 :(得分:1)
请在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());
修改您的方法,如下所示
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);
}
希望这有帮助
答案 4 :(得分:0)
您需要在列表视图中使用onItemClickListener。
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);
}
});
此外,在您的EditorNewContact活动中,您需要在onCreate方法中解决此意图,例如:
Intent intent = getIntent();
SelectContact contact = (SelectContact) intent.get("Key");
此外,您的SelectContact类可以是Serializeable,如果是can,则意图如下。
Intent secondActivity = new Intent(MainActivity.this, EditorNewContact.class);
secondActivity.putSerializeableExtra("Key", contact);
startActivity(secondActivity);
而且,要解决这个问题:
Intent intent = getIntent();
SelectContact contact = (SelectContact) intent.getSerializableExtra("Key");
我希望这会有所帮助。