我正在使用 json 执行类似联系应用程序的操作
我可以查看联系人并添加新联系人,但在添加新联系人后无法自动更新联系人(在我的数据库中已更新)。我必须在 Eclipse 中再次运行我的应用程序才能看到新联系人
我的一些主要代码是这样的
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.*;
import android.content.*;
import android.database.Cursor;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
public class MainActivity extends ListActivity {
private Cursor friendsCursor = null;
int position;
private ArrayList<Data> friends = null;
DateFormat fDateTimeDisplay = new SimpleDateFormat("dd-MM-yyyy");
DateFormat fDateTime = new SimpleDateFormat("yyyy-MM-dd");
public static String friendURL = "http://-----/friend.php";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
friends = new ArrayList<Data>();
setListAdapter(new DataAdapter());
try
{
JSONArray jArray = new JSONArray(getServerData());
String name, address, gender;
long code;
Date DOB;
friends.clear();
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
code = json_data.getLong("FriendCode");
name = json_data.getString("FriendName");
address = json_data.getString("FriendAddress");
gender = json_data.getString("FriendGender");
DOB = fDateTime.parse(json_data.getString("FriendDOB"));
Data data = new Data(name, address, gender, DOB,code);
friends.add(data); }
}catch(JSONException e){
//Display error message
Toast.makeText(this, "Error parsing data " + e.toString(), Toast.LENGTH_LONG).show();
}
catch (ParseException pe) {
Toast.makeText(this, "Error parsing data " + pe.toString(), Toast.LENGTH_LONG).show();
}
registerForContextMenu(getListView());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.option, menu);
return(super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add:
Intent intent = new Intent(this, AddActivity.class);
intent.putExtra("code", 1);
startActivityForResult(intent, 1);
return(true);
}
return(super.onOptionsItemSelected(item));
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK)
{
}
}
private String getServerData() {
InputStream is = null;
String result = "";
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(friendURL);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Toast.makeText(this, "Error in http connection " + e.toString(), Toast.LENGTH_LONG).show();
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Toast.makeText(this, "Error converting result " + e.toString(), Toast.LENGTH_LONG).show();
}
return result;
}
class DataAdapter extends ArrayAdapter<Data> {
DataAdapter() {
super(MainActivity.this, R.layout.row, friends);
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.row, parent, false);
}
ViewHolder holder = (ViewHolder)row.getTag();
if (holder == null) {
holder = new ViewHolder(row);
row.setTag(holder);
}
holder.code.setText(Long.toString((friends.get(position).getcode())));
holder.txtName.setText(friends.get(position).getName());
holder.txtAddress.setText(friends.get(position).getAddress());
holder.txtGender.setText(friends.get(position).getGender());
holder.txtDOB.setText(fDateTimeDisplay.format(friends.get(position).getDOB()));
return(row);
}
}
}
当我想添加一个新联系人时,我使用 Intent AddActivity 打开一个新的布局调用添加
这是我的 AddActivity 的一些代码
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.*;
import java.util.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.*;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
public class AddActivity extends Activity {
public static String friendInsertURL = "http://----/friendInsert.php";
Calendar calendar = Calendar.getInstance();
DateFormat fDateTime = new SimpleDateFormat("yyyy-MM-dd");
DateFormat fDateTimeDisplay = new SimpleDateFormat("dd-MM-yyyy");
long code;
EditText editName, editAddress;
RadioButton rbMale, rbFemale;
TextView txtDOBEdit;
String gender;
int position;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
editName = (EditText)findViewById(R.id.editName);
editAddress = (EditText)findViewById(R.id.editAddress);
txtDOBEdit = (TextView)findViewById(R.id.txtDOBEdit);
rbMale = (RadioButton)findViewById(R.id.rbMale);
rbFemale = (RadioButton)findViewById(R.id.rbFemale);
editName.setText("");
editAddress.setText("");
calendar = Calendar.getInstance();
txtDOBEdit.setText(fDateTimeDisplay.format(calendar.getTime()));
rbMale.setChecked(true);
}
private String setServerData(String mode, String name, String address, String gender, String dob) {
InputStream is = null;
String save = "";
ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
if (mode.equals("INSERT")) {
parameters.add(new BasicNameValuePair("FriendName", name));
parameters.add(new BasicNameValuePair("FriendAddress", address));
parameters.add(new BasicNameValuePair("FriendGender", gender));
parameters.add(new BasicNameValuePair("FriendDOB", dob));
friendInsertURL = "http://----/friendInsert.php";
}
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(friendInsertURL );
httppost.setEntity(new UrlEncodedFormEntity(parameters));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Toast.makeText(this, "Error in http connection " + e.toString(), Toast.LENGTH_LONG).show();
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
save=sb.toString();
}catch(Exception e){
Toast.makeText(this, "Error converting result " + e.toString(), Toast.LENGTH_LONG).show();
}
return save;
}
public void chooseDate(View v) {
new DatePickerDialog(this, d,
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH))
.show();
}
DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, monthOfYear);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
TextView txtDOBEdit = (TextView)findViewById(R.id.txtDOBEdit);
txtDOBEdit.setText(fDateTimeDisplay.format(calendar.getTime()));
}
};
public void setSave(View view){
String save;
EditText editName = (EditText)findViewById(R.id.editName);
EditText editAddress = (EditText)findViewById(R.id.editAddress);
RadioButton rbMale = (RadioButton)findViewById(R.id.rbMale);
if (rbMale.isChecked()){
gender = "Male";}
else{
gender = "Female";
}
save = setServerData("INSERT", editName.getText().toString(), editAddress.getText().toString(), gender, fDateTime.format(calendar.getTime()));
finish();
}
}
我已经搜索并发现我必须使用adapter.notifyDataSetChanged()
来更新我的适配器但是当我将此代码放入我的 AddActivity
ArrayAdapter<Data> adapter = (ArrayAdapter<Data>)getListAdapter();
那里的getListAdapter
错误,我不能放一个ListActivity
,当我运行它时它会导致我的应用程序错误。
我的问题是如何更新我的适配器,以便在添加新适配器时始终可以看到我的联系人更新?
发现了一些东西:
我的添加代码是添加到数据库而不是适配器中..是因为那个吗?那么如何添加到适配器中是真的吗?它在 MainActivity 还是 AddActivity 中?
注意:我的列表视图正在使用查看器来显示内容..
真的需要帮助..我已经尝试了所有我知道的代码,但除了退出并再次运行应用程序之外仍然无法更新