gpt4 book ai didi

android - 添加新列表后如何在android中更新 ListView

转载 作者:行者123 更新时间:2023-11-29 02:00:21 25 4
gpt4 key购买 nike

我正在做类似使用 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 中?

注意:我的 ListView 使用查看器来显示内容..

真的需要帮助.. 我已经尝试了所有我知道的代码,但仍然无法更新,除非退出并再次运行应用程序

最佳答案

代码中需要的更改并将其粘贴到项目中

public class MainActivity extends ListActivity {

private ArrayList<Data> friends;
private ArrayAdapter adapter;
private ListViewlistview;

@Override
public void onCreate(Bundle savedInstanceState) {

friends = new ArrayList<Data>();
listview = (ListView) findViewById(R.id.listview_id);
adapter = new ArrayAdapter<Data>(this, R.id.list, friends);
listview.setAdapter(adapter);
}

这将更新 ListView ,因此您可以在将新 friend 添加到“ friend ”列表后调用它。

adapter.notifyDataSetChanged();

关于android - 添加新列表后如何在android中更新 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12995385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com