2016-05-15 20 views
0

enter image description here如何获取我的列表视图中单击的单元格的名称以加载到新的活动中?

如何在我的列表视图中获取特定单元的名称以加载到新的活动中?目前,当我单击任何箭头时,会在下一个单击箭头时加载的活动中加载联系人中的最后一个人(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", "[email protected]" }; 
             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); 
} 

而且孩子的活动,到了我想阿列克谢加载(在现在我不断收到伊冯娜)看起来是这样的:

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

请分享您的SelectContactAdapter.java – Harsh4789

+0

@ Harsh4789我已添加了我的SelectContactsAdapter,谢谢。 – CHarris

+0

您总是希望从适配器获取数据。这应该给你点击项目的准确位置 – Eenvincible

回答

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); 
    } 

希望这有助于

+0

作品美丽! – CHarris

2

很难预测你的代码是如何工作的,而没有看到SelectContactAdapter源代码。但是,我可以提出一个也许最简单的解决方案,它使用tag

所有你需要做的就是在你的适配器的getView方法的地方设置一个标记,即可箭头形象是这样的:

youArrowImage.setTag("here_is_a_name_of_a_row"); 

,然后在DisplayorEditContact(View v),你可以这样访问:

String itemName = (String)v.getTag(); 

这里我想这v是一个参考点击箭头图像

+0

欢呼声,现在正在寻找你的答案,同时我已经添加了我的SelectContactAdapter问题,如果你认为这可以提供帮助。 – CHarris

+0

干杯R.,我以上述苛刻行事,因为它确切地说明了需要完成的事情。 +1 – CHarris

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); 
    } 
}); 
+0

感谢Akash的努力,我跟着Harsh的......我在上面的代码中遇到了问题(位置)。 +1 – CHarris

+1

没问题,很高兴我贡献了! – AkashBhave

1

你这个方法是这样的:

public void DisplayorEditContact(View v) { 

TextView tvName = (TextView) v.findViewById(R.id.YOUR_TEXT_NAME); 
    System.out.println(tvName.getText().toString()); 
} 

希望这将解决您的问题:)

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类可以被序列化,如果是这样就可以了,意图看起来像。

Intent secondActivity = new Intent(MainActivity.this, EditorNewContact.class); 
      secondActivity.putSerializeableExtra("Key", contact); 
      startActivity(secondActivity); 

而且,为了解决此问题:

Intent intent = getIntent(); 
    SelectContact contact = (SelectContact) intent.getSerializableExtra("Key"); 

我希望这有助于。

相关问题