public class MainActivity extends Activity {
ListView list;
LinearLayout ll;
Button loadBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ll = (LinearLayout) findViewById(R.id.LinearLayout1);
list = (ListView) findViewById(R.id.listView1);
loadBtn = (Button) findViewById(R.id.button1);
loadBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
LoadContacts lc=new LoadContacts();
if(lc.execute()!=null)
{
Toast toast=Toast.makeText(MainActivity.this, "hello", Toast.LENGTH_LONG);
toast.show();
}
}
});
}
class LoadContacts extends AsyncTask<Void, Void, ArrayList<String>>
{
ProgressDialog pd;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = ProgressDialog.show(MainActivity.this, "Loading Contacts",
"Please Wait");
}
protected ArrayList<String> doInBackground(Void... params) {
// TODO Auto-generated method stub
ArrayList<String> contacts = new ArrayList<String>();
Cursor c = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
null, null, null);
while (c.moveToNext()) {
String contactName = c
.getString(c
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phNumber = c
.getString(c
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts.add(contactName + ":" + phNumber);
}
c.close();
return contacts;
}
@Override
protected void onPostExecute(ArrayList<String> contacts) {
// TODO Auto-generated method stub
super.onPostExecute(contacts);
pd.cancel();
ll.removeView(loadBtn);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getApplicationContext(), R.layout.text, contacts);
list.setAdapter(adapter);
list.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder adb=new AlertDialog.Builder(MainActivity.this);
adb.setTitle("call & message");
adb.setPositiveButton("call", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//write here call coding
}
});
adb.setNegativeButton("message", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//write here message coding
}
});
}
});
}
}
}
這是我的MainActivity.java
文件。當我刪除對話框代碼其工作正常和加載的聯繫人,但與對話框代碼不工作,請任何人幫助我。如何在單擊由AsyncTask生成的listview項後打開對話框?
AsyncTask是異步的,所以你可以在執行 –
之前設置項目點擊監聽器是的,這就是對的。 AsyncTask是異步的,你也可以在之前調用它。 –
如果我在AsyncTask之前設置了項目點擊偵聽器,那麼它如何從我的手機加載聯繫人,因爲AsyncTask在ListView中加載聯繫人。不知道它是如何工作的,它仍然不工作 – Jeevan