如何从其他活动中刷新光标?
在我的主要活动中,我启动光标查询手机通讯录并显示在列表视图中。
在这个主要活动中,我还有一个菜单“添加新联系人”,它启动添加新的联系活动。正确添加新联系人(我可以在手机上的其他联系人应用中看到它),但当用户返回主要活动时,我的列表视图中看不到它。
有没有办法从“添加新联系人”活动中刷新光标,以便用户在返回主要活动时可以在列表视图中看到它?
我在我的主要活动中使用AsyncTask,如果这是任何有用的信息。我读到了swapcursor和changecursor,但是当我尝试使用它们时它没有用。这是我的“添加新联系人”代码:
(我在“联系保存”吐司之前调用了变焦,但我确定它没有正确完成。
package com.example.chris.contactlistcustomlistview;
import android.content.ContentProviderOperation;
import android.content.OperationApplicationException;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Chris on 06/05/2016.
*/
public class AddContact extends AppCompatActivity {
EditText nameofcontact;
EditText numberofcontact;
public String contactname;
public String contactnumber;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addcontact);
nameofcontact = (EditText) findViewById(R.id.edittextname);
numberofcontact = (EditText) findViewById(R.id.edittextnumber);
}
public void createButton(View view) {
contactname = nameofcontact.getText().toString();
contactnumber = numberofcontact.getText().toString();
if (contactname.length() == 0) {
Toast.makeText(this, "Please enter a name",
Toast.LENGTH_LONG).show();
return;
}
ArrayList<ContentProviderOperation> contentProviderOperations = new ArrayList<ContentProviderOperation>();
//insert raw contact using RawContacts.CONTENT_URI
contentProviderOperations.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null).withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build());
//insert contact display name using Data.CONTENT_URI
Log.d("ffff","wwww");
contentProviderOperations.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,contactname ).build());
//insert mobile number using Data.CONTENT_URI
contentProviderOperations.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, contactnumber).withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE).build());
try {
//apply the changes
getApplicationContext().getContentResolver().
applyBatch(ContactsContract.AUTHORITY, contentProviderOperations);
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
// SelectContactAdapter.changeCursor(cursor);
Toast.makeText(this, "Contact saved",
Toast.LENGTH_SHORT).show();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
//This clears the edittext next time user starts the application, rather than
// having the same numbers there, which the user probably doesn't want anymore
protected void onResume() {
final EditText editText = (EditText) findViewById(R.id.edittextname);
super.onResume();
editText.setText("");
}
}
这是我的MainActivity代码:
package com.example.chris.contactlistcustomlistview;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MainActivity extends Activity implements PopupMenu.OnMenuItemClickListener {
// ArrayList
ArrayList<SelectContact> selectContacts;
List<SelectContact> temp;
// Contact List
ListView listView;
// Cursor to load contacts list
// Cursor phones, email;
Cursor pCur;
// Pop up
// ContentResolver resolver;
SearchView search;
SelectContactAdapter adapter;
String phoneContactId;
String name;
String phoneNumber;
CharSequence nameofcontact;
// String phoneNumber;
// *****18-04-2016***
Cursor cursor;
ListView mainListView;
ArrayList hashMapsArrayList;
// String contactid;
// *****
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectContacts = new ArrayList<SelectContact>();
// resolver = this.getContentResolver();
listView = (ListView) findViewById(R.id.contacts_list);
LoadContact loadContact = new LoadContact();
loadContact.execute();
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) {
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 photoIdIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI);
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);
// System.out.println("Id--->"+contactid+"Name--->"+name);
System.out.println("Id--->" + contactid + " Name--->" + name);
System.out.println("Id--->" + contactid + " Number--->" + phoneNumber);
SelectContact selectContact = new SelectContact();
// selectContact.setThumb(bit_thumb);
selectContact.setName(name);
selectContact.setPhone(phoneNumber);
// selectContact.setEmail(id);
// selectContact.setCheckedBox(false);
selectContacts.add(selectContact);
}
} while (cursor.moveToNext());
} catch (Exception e) {
e.printStackTrace();
} finally {
// if (cursor != null) {
// }
}
cursor.close();
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);
listView.setAdapter(adapter);
// Select item on listclick
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
nameofcontact = ((TextView)view.findViewById(R.id.name)).getText();
// }
// Creates a new Intent to edit a contact
Intent intent = new Intent(Intent.ACTION_EDIT);
startActivity(intent);
listView.setFastScrollEnabled(true);
}
});
}}
//the is the arrow image, it opens the activity for edit or new contact
public void EditorCreateContact(View v) {
}
@Override
protected void onStop() {
super.onStop();
}
// this is for the settings menu
public void settingsPopUp(View view) {
PopupMenu popup = new PopupMenu(this,view);
popup.setOnMenuItemClickListener(MainActivity.this);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.popup_actions, popup.getMenu());
popup.show();
}
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
// from the popup_actions.xml, identify the New_contact id and make it
// open the AddContact class
case R.id.New_contact:{
Intent intent = new Intent(this, AddContact.class);
startActivity(intent);
// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(intent);
// finish(); // Call once you redirect to another activity
}
// Toast.makeText(getBaseContext(), "You slected New Contact",Toast.LENGTH_SHORT).show();
//
return true;
}
return false;
}
}
答案 0 :(得分:2)
首先声明行
final EditText editText = (EditText) findViewById(R.id.edittextname);
在OnCreate()
中...因为每次在活动恢复时初始化视图都是不好的做法。
并查询您活动的OnResume中的数据。这是在您回到活动时刷新数据的更好方法。
答案 1 :(得分:1)
您可以使用startActivityForResult()
代替startActivity
并覆盖onActivityResult()
来重新查询您的光标是否成功。敬酒后,setResult()
至RESULT_OK
并完成AddContact
活动。
setResult(RESULT_OK);
finish();
答案 2 :(得分:1)
您可以按照我在评论中提到的onResume()
方法刷新您的联系人,因为您可以在onResume()
本身中执行以下操作
LoadContact loadContact = new LoadContact();
loadContact.execute();
您可以从onCreate()
移除上述内容,因为调用将是多余的onResume()
每次都会调用Activity LifeCycle。
如果您使用此方法,只需在第一行的ArrayList
中执行selectContacts
清除selectContacts.clear()
doInBackground()
,否则它会将联系人列出两次,然后三次等等...
除此之外,正如您可以使用startActivityForResult()
和onActivityResult()
方法在同一主题中的另一个答案中所述,您可以更新联系人列表。