所以我很高兴获得联系。我将联系人分配到列表视图,并能够看到它们。当我点击某个联系人时,它会启动一个新活动,目前我只想显示该联系人的ID。所以我所做的是将联系人ID设置为" set_id",当您点击某个联系人时,它会调用" get_id",将该ID分配给contactId,并将其传递给putextra。 ..
import java.util.ArrayList;
import android.app.Activity; import android.content.CursorLoader; import android.content.Intent; import android.database.Cursor;进口 android.net.Uri; import android.os.Bundle;进口 android.provider.ContactsContract; import android.view.Menu;进口 android.view.View; import android.widget.AdapterView;进口 android.widget.ListView;
公共类ListViewActivity扩展了Activity {
ListItemDetails Detail; ListView mListView; ArrayList<ListItemDetails> details; Uri contacts; String contactName; int contactPic; int contactId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mListView = (ListView)findViewById(R.id.listView); details = new ArrayList<ListItemDetails>(); contacts = ContactsContract.Contacts.CONTENT_URI; CursorLoader cursorLoader = new CursorLoader( this, contacts, null, null, null, null); Cursor c = cursorLoader.loadInBackground(); while (c.moveToNext()) { contactId = c.getColumnIndex(ContactsContract.Contacts._ID); contactName = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); Detail = new ListItemDetails(); Detail.setImage(R.drawable.ic_launcher); Detail.setName(contactName); Detail.set_id(contactId); details.add(Detail); } c.close(); mListView.setAdapter(new CustomListAdapter(details, this)); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { Intent i = new Intent(ListViewActivity.this, ContactDetails.class); i.putExtra("contactId", contactId); startActivity(i); } }); }
现在,在新的Activity中,我只是希望它现在显示联系人ID(仍然在学习)。所以我调用Bundle getInt,将int值赋给&#34; contactId&#34;并在屏幕上显示...并且无论我选择什么联系,我都会显示id = 0.我做错了什么?这是第二项活动:
import android.app.Activity; import android.os.Bundle;进口 android.widget.TextView;
公共类ContactDetails扩展了Activity {
int contactId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.contactinfo); Bundle extras = new Bundle(); contactId = extras.getInt("contactId"); TextView contactName = (TextView)findViewById(R.id.contactName); contactName.setText("You clicked " + contactId); } }
tl; dr无论我在listview中选择什么联系人,它都说联系人ID = 0,为什么?
答案 0 :(得分:0)
Bundle extras = new Bundle();
当你这样做时,你创建一个名为extras的新Bundle而不是你添加到activivty的额外内容。
而不是尝试:
contactId = getIntent().getIntExtra("contactId",0);