大家好我已经创建了一个自定义列表适配器,我使用JSON填充数据,Json是通过查询数据库生成的,然后数据显示在列表中查看我面临的问题是,当我添加数据到数据库应该立即显示在列表视图上,但它没有这样做,而是我需要去清除缓存然后清除数据然后才显示我添加的内容
Fragment One Activity在这里使用JSON解析器
public class FragmentOne extends BaseActivity {
private static final String TAG = FragmentOne.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://ops.esy.es/android_app_api/json.php";
public int pid;
private Button b1;
public CursorAdapter me;
public ArrayAdapter my;
int global_position =0;
FeedListAdapter feedi;
public static Integer length;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.fragment_layout_one, frameLayout);
session = new SessionManager(getApplicationContext());
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
mDrawerList.setItemChecked(position, true);
setTitle(listArray[position]);
listView = (ListView) findViewById(R.id.feedlist);
b1 = (Button) findViewById(R.id.button);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("Clicked item id", " " + position);
}
});
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FF6600")));
getActionBar().setIcon(
new ColorDrawable(getResources().getColor(android.R.color.transparent)));
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
b1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent myIntent = new Intent(FragmentOne.this, Post.class);
FragmentOne.this.startActivity(myIntent);
}
});
listView.invalidateViews();
}
/**
* Parsing json reponse and passing the data to feed view list adapter
* */
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0 ; i <feedArray.length() ; i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
int pid = feedObj.getInt("id");
String pname = feedObj.getString("name");
String pimage = feedObj.isNull("image") ? null : feedObj.getString("image");
String pstatus = feedObj.getString("status");
String profilep =feedObj.getString("profilePic");
String timestamp= feedObj.getString("timeStamp");
db.addpost(pid,pname,pimage,pstatus,profilep,timestamp);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
我的自定义列表适配器
public class FeedListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<FeedItem> feedItems;
private ListView lv;
private SQLiteHandler db;
public static Integer pos;
public FragmentOne f2 = new FragmentOne();
public AdapterView.OnItemClickListener onItemClickListener =
new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
};
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public FeedListAdapter(Activity activity, List<FeedItem> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
}
@Override
public int getCount() {
return feedItems.size();
}
@Override
public Object getItem(int location) {
return feedItems.get(location);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.feed_item, null);
viewHolder = new ViewHolder();
viewHolder.name=(TextView) convertView.findViewById(R.id.name);
viewHolder.timestamp = (TextView) convertView
.findViewById(R.id.timestamp);
viewHolder.statusmsg = (TextView) convertView
.findViewById(R.id.txtStatusMsg);
viewHolder.url = (TextView) convertView.findViewById(R.id.txtUrl);
viewHolder.profilePic = (NetworkImageView) convertView
.findViewById(R.id.profilePic);
viewHolder.feedImageView = (FeedImageView) convertView
.findViewById(R.id.feedImage1);
viewHolder.ops = (Button) convertView.findViewById(R.id.ops);
convertView.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) convertView.getTag();
viewHolder.ops.setTag(null);
}
FeedItem f = new FeedItem();
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView timestamp = (TextView) convertView
.findViewById(R.id.timestamp);
TextView statusMsg = (TextView) convertView
.findViewById(R.id.txtStatusMsg);
TextView url = (TextView) convertView.findViewById(R.id.txtUrl);
NetworkImageView profilePic = (NetworkImageView) convertView
.findViewById(R.id.profilePic);
FeedImageView feedImageView = (FeedImageView) convertView
.findViewById(R.id.feedImage1);
db = new SQLiteHandler(activity.getApplicationContext());
final FeedItem item = feedItems.get(position);
Button ops= (Button) convertView.findViewById(R.id.ops);
name.setText(item.getName());
ops.setTag(position);
ops.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pos = (Integer) v.getTag();
db.deletecom();
pos = pos+1;
String posi = String.valueOf(pos);
Intent i = new Intent(activity.getApplicationContext(), CommentMain.class);
i.putExtra("position",posi);
activity.startActivity(i);
Log.d("Clicked item id", " " + pos);
}
});
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
statusMsg.setText(item.getStatus());
statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
url.setMovementMethod(LinkMovementMethod.getInstance());
url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
url.setVisibility(View.GONE);
}
// user profile pic
profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
feedImageView.setImageUrl(item.getImge(), imageLoader);
feedImageView.setVisibility(View.VISIBLE);
feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
@Override
public void onError() {
}
@Override
public void onSuccess() {
}
});
} else {
feedImageView.setVisibility(View.GONE);
}
return convertView;
}
public void setMyList(List myListOfObjects) {
this.feedItems = myListOfObjects;
this.notifyDataSetChanged();
}
public class ViewHolder {
TextView name;
TextView timestamp;
TextView statusmsg;
TextView url;
FeedImageView feedImageView;
NetworkImageView profilePic;
Button ops;
}
}
我尝试过使用notifydatasetchange()并使视图无效,但它们都没有为我工作所以你们可以指导我完成这个以及我出错的地方
json.php
<?php
$con = mysql_connect($host, $uname, $pwd) or die ("connection failed");
mysql_select_db($db,$con) or die(" db selection failed");
$result = mysql_query("select * from thoughts order by id desc", $con);
$json_response =array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$row_array['id'] = utf8_encode($row['id']);
$row_array['name'] = utf8_encode($row['name']);
$row_array['image'] =utf8_encode( $row['image']);
$row_array['status'] = utf8_encode($row['status']);
$row_array['profilePic'] = utf8_encode($row['profilepic']);
$row_array['timeStamp'] =utf8_encode($row['timestamp']);
$row_array['url'] = utf8_encode($row['url']);
array_push($json_response,$row_array);
}
$my= json_encode(array('feed' =>$json_response));
echo $my;
$fp = fopen('results.json', 'w');
fwrite($fp, $my);
fclose($fp);
?>
编辑
FeedItem
public class FeedItem {
private int id;
private String name, status, image, profilePic, timeStamp, url;
public FeedItem() {
}
public FeedItem(int id, String name, String image, String status,
String profilePic, String timeStamp, String url) {
super();
this.id = id;
this.name = name;
this.image = image;
this.status = status;
this.profilePic = profilePic;
this.timeStamp = timeStamp;
this.url = url;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImge() {
return image;
}
public void setImge(String image) {
this.image = image;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getProfilePic() {
return profilePic;
}
public void setProfilePic(String profilePic) {
this.profilePic = profilePic;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
答案 0 :(得分:0)
在为listview设置适配器之前,您必须获取FeedItems列表。
当列表更新或删除时,您应该使用相同的arrayList引用,然后只有notifyDataSetChanged()才能工作。
并使用以下代码作为适配器。
public class FeedListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<FeedItem> feedItems;
private ListView lv;
private SQLiteHandler db;
public static Integer pos;
public FragmentOne f2 = new FragmentOne();
public AdapterView.OnItemClickListener onItemClickListener =
new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
};
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public FeedListAdapter(Activity activity, List<FeedItem> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
inflater = LayoutInflater.from(activity);
}
@Override
public int getCount() {
return feedItems.size();
}
@Override
public Object getItem(int location) {
return feedItems.get(location);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.feed_item, null);
viewHolder = new ViewHolder();
viewHolder.name=(TextView) convertView.findViewById(R.id.name);
viewHolder.timestamp = (TextView) convertView
.findViewById(R.id.timestamp);
viewHolder.statusmsg = (TextView) convertView
.findViewById(R.id.txtStatusMsg);
viewHolder.url = (TextView) convertView.findViewById(R.id.txtUrl);
viewHolder.profilePic = (NetworkImageView) convertView
.findViewById(R.id.profilePic);
viewHolder.feedImageView = (FeedImageView) convertView
.findViewById(R.id.feedImage1);
viewHolder.ops = (Button) convertView.findViewById(R.id.ops);
convertView.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) convertView.getTag();
}
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView timestamp = (TextView) convertView
.findViewById(R.id.timestamp);
TextView statusMsg = (TextView) convertView
.findViewById(R.id.txtStatusMsg);
TextView url = (TextView) convertView.findViewById(R.id.txtUrl);
NetworkImageView profilePic = (NetworkImageView) convertView
.findViewById(R.id.profilePic);
FeedImageView feedImageView = (FeedImageView) convertView
.findViewById(R.id.feedImage1);
db = new SQLiteHandler(activity);
final FeedItem item = feedItems.get(position);
Button ops= (Button) convertView.findViewById(R.id.ops);
name.setText(item.getName());
ops.setTag(position);
ops.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pos = (Integer) v.getTag();
db.deletecom();
pos = pos+1;
String posi = String.valueOf(pos);
Intent i = new Intent(activity.getApplicationContext(), CommentMain.class);
i.putExtra("position",posi);
activity.startActivity(i);
Log.d("Clicked item id", " " + pos);
}
});
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
statusMsg.setText(item.getStatus());
statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
url.setMovementMethod(LinkMovementMethod.getInstance());
url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
url.setVisibility(View.GONE);
}
// user profile pic
profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
feedImageView.setImageUrl(item.getImge(), imageLoader);
feedImageView.setVisibility(View.VISIBLE);
feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
@Override
public void onError() {
}
@Override
public void onSuccess() {
}
});
} else {
feedImageView.setVisibility(View.GONE);
}
return convertView;
}
public void setMyList(List myListOfObjects) {
this.feedItems = myListOfObjects;
this.notifyDataSetChanged();
}
public class ViewHolder {
TextView name;
TextView timestamp;
TextView statusmsg;
TextView url;
FeedImageView feedImageView;
NetworkImageView profilePic;
Button ops;
}
}