我无法在Android中的自定义适配器中添加新项目。发布CommentPageActivity
班级和MyAdapter
班级以便更好地理解。
CommentPageActivity
班级填充ListView
和onclick
行动,我们正在拨打MyAdapter
package com.sk.comment;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
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 com.sk.bhangarwaala.R;
import com.sk.variable.Globals;
import com.sk.variable.Variable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.app.ActionBar;
import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class CommentPageActivity extends Activity {
MyAdapter listAdapter;
ListView commentPageLvCommentsList;
TextView commentPageTvSkid,commentPageTvLoader;
EditText commentPageEtEnterComments;
LinearLayout commentPageLlCommentsContainer;
Button commentPageBtSubmit;
List<CommentsFeedObj> data;
String key,json;
boolean isTaskCompleted,isError;
LoadComments task= new LoadComments();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comment_page);
ActionBar actionBar = getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.my_red)));
// Enabling Back navigation on Action Bar icon
actionBar.setDisplayHomeAsUpEnabled(true);
key=getIntent().getExtras().getString("skid");
System.out.println("CommentPageActivity.onCreate() | key | "+key);
data = new ArrayList<CommentsFeedObj>();
Display d = ((Activity) this).getWindowManager()
.getDefaultDisplay();
int h = d.getHeight();
int w = d.getWidth();
System.out.println("CommentPageActivity.onCreate()|h|"+h+" |w|"+w);
DisplayMetrics displayMetrics = getApplicationContext().getResources().getDisplayMetrics();
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
System.out.println("CommentPageActivity.onCreate() |height| "+height);
if(w>h){
height=height*65/100;
}else{
height=height*75/100;
}
System.out.println("CommentPageActivity.onCreate() |height| "+height);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, height);
commentPageLlCommentsContainer = (LinearLayout)findViewById(R.id.commentPageLlCommentsContainer);
commentPageLlCommentsContainer.setLayoutParams(lp);
commentPageTvSkid = (TextView)findViewById(R.id.commentPageTvSkid);
commentPageTvSkid.setVisibility(View.GONE);
commentPageEtEnterComments = (EditText)findViewById(R.id.commentPageEtEnterComments);
System.out.println("CommentPageActivity.onCreate() width | | "+width);
System.out.println("CommentPageActivity.onCreate() | 80/width*100 | "+width*80/100);
commentPageEtEnterComments.setLayoutParams(new LinearLayout.LayoutParams(width*80/100, LinearLayout.LayoutParams.WRAP_CONTENT));
commentPageLvCommentsList = (ListView)findViewById(R.id.commentPageLvCommentsList);
commentPageTvLoader=(TextView)findViewById(R.id.commentPageTvLoader);
initLoadComments();
commentPageBtSubmit = (Button)findViewById(R.id.commentPageBtSubmit);
//commentPageBtSubmit.setBackgroundResource(R.drawable.ic_email_send);
commentPageBtSubmit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
performAddCommentsOperation();
}
});
}
void initLoadComments(){
task.execute();
}
void loadCommentsView(){
try {
if(error)){
CommentsFeedObj obj = new CommentsFeedObj();
obj.setUserProfileImg("");
obj.setUserName("");
obj.setUserMsg("");
obj.setTimestamp("");
obj.setSkid(key);
obj.setResponseStatus("error");
data.add(obj);
}else{
parseJson(new JSONObject(json));
}
listAdapter= new MyAdapter(this, data);
commentPageLvCommentsList.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
void parseJson(JSONObject response){
System.out.println("CommentPageActivity.parseJson()");
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
CommentsFeedObj obj = new CommentsFeedObj();
obj.setUserProfileImg(feedObj.getString("userProfileImg"));
obj.setUserName(feedObj.getString("userName"));
obj.setUserMsg(feedObj.getString("userMsg"));
obj.setTimestamp(feedObj.getString("timestamp"));
obj.setSkid(feedObj.getString("skid"));
obj.setLogonUserId(feedObj.getString("logonUserId"));
obj.setLogonUserName(feedObj.getString("logonUserName"));
obj.setLogonUserMobileNumber(feedObj.getString("logonUserMobileNumber"));
obj.setUserLocation(feedObj.getString("userLocation"));
obj.setTs_long(Long.parseLong(feedObj.getString("ts_long")));
obj.setResponseStatus("success");
data.add(obj);
}
System.out.println("CommentPageActivity.parseJson() | "+data);
} catch (JSONException e) {
e.printStackTrace();
}
}
private class LoadComments extends AsyncTask<String, Void, String>{
@Override
protected void onPreExecute(){
super.onPreExecute();
commentPageTvLoader.setVisibility(View.VISIBLE);
commentPageTvLoader.setText("Loading...");
}
@Override
protected void onPostExecute(String result){
int i=0;
while(true){
i=i+1;
if(i==4){json=(Globals._N_LOADING_ERROR_COMMENTS); break;}
if(isTaskCompleted && (json==null || json.length()<1)){
task.execute(Variable.WS_URL_LOAD_COMMENTS);
isTaskCompleted=false;
}else if(isTaskCompleted&& (json!=null || json.length()>0))
{/*prgDialog.dismiss();*/break;}
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
}
}, 200);
}// while
loadCommentsView();
commentPageTvLoader.setVisibility(View.GONE);
}
@Override
protected String doInBackground(String... params) {
System.out.println("CommentPageActivity.LoadComments.doInBackground()");
StringBuffer response=new StringBuffer("");
List<NameValuePair> nameVauePairs=new ArrayList<NameValuePair>(1);
InputStream is=null;
nameVauePairs.add(new BasicNameValuePair("skid", key));
try {
HttpPost httppost = new HttpPost(Variable.WS_URL_LOAD_COMMENTS);
HttpClient httpclient = new DefaultHttpClient();
httppost.setEntity(new UrlEncodedFormEntity(nameVauePairs));
HttpResponse response1 = httpclient.execute(httppost);
StatusLine statusLine= response1.getStatusLine();
System.out.println("CommentPageActivity.LoadComments.doInBackground() | statusLine | "+statusLine);
{
HttpEntity entity =response1.getEntity();
is=entity.getContent();
InputStreamReader in =new InputStreamReader(is);
BufferedReader br = new BufferedReader(in);
String info="";
String nl=System.getProperty("line.separator");
while((info=br.readLine())!=null){
response.append(info.toString()+nl);
}
System.out.println("CommentPageActivity.LoadComments.doInBackground() | response.toString() | "+response.toString());
json=response.toString();
isTaskCompleted=true;
isError=false;
br.close();
}
} catch (UnsupportedEncodingException e) {
isTaskCompleted=true;
isError=true;
e.printStackTrace();
}catch (ClientProtocolException e) {
isTaskCompleted=true;
isError=true;
e.printStackTrace();
} catch (IOException e) {
isTaskCompleted=true;
isError=true;
e.printStackTrace();
}
return "";
}// doBackGroud
}// SaveComment
void performAddCommentsOperation(){
System.out.println("CommentPageActivity.performAddCommentsOperation()");
String msg=commentPageEtEnterComments.getText()+"".trim();
String logonUserName=Globals.getInstance().getLogonUserName();
String logonUserMobileNumber=Globals.getInstance().getLogonUserMobileNumber();
String logonUserId=Globals.getInstance().getLogonUserId();
if(msg==null || msg.length()<1){
Toast.makeText(this, "Please enter comments", Toast.LENGTH_SHORT).show();
commentPageEtEnterComments.setText("");
return;
}
commentPageEtEnterComments.setText("");
if(logonUserName!=null && logonUserName.trim().length()>0){
}else{
logonUserName="unknown";
}
if(msg!=null && msg.trim().length()>0){
}else{
msg="nice shop";
}
CommentsFeedObj obj = new CommentsFeedObj();
obj.setUserProfileImg("");
obj.setUserName(logonUserName);
obj.setUserMsg(msg);
obj.setTimestamp(""+new Date());
obj.setSkid(key);
obj.setLogonUserId(logonUserId);
obj.setLogonUserName(logonUserName);
obj.setLogonUserMobileNumber(logonUserMobileNumber);
obj.setUserLocation("");
obj.setTs_long(System.currentTimeMillis());
data.add(obj);
listAdapter= new MyAdapter(this, data);
//commentPageLvCommentsList.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
performSaveCommentOperation(obj);
}
void performSaveCommentOperation(CommentsFeedObj obj){
new SaveComment().execute(obj);
}
private class SaveComment extends AsyncTask<CommentsFeedObj, Void, String>{
@Override
protected void onPreExecute(){
super.onPreExecute();
}
@Override
protected void onPostExecute(String result){
}
@Override
protected String doInBackground(CommentsFeedObj... params) {
System.out.println("CommentPageActivity.SaveComment.doInBackground()");
StringBuffer response=new StringBuffer("");
List<NameValuePair> nameVauePairs=new ArrayList<NameValuePair>(1);
InputStream is=null;
CommentsFeedObj obj=params[0];
nameVauePairs.add(new BasicNameValuePair("ts_long", obj.getTs_long()+""));
nameVauePairs.add(new BasicNameValuePair("skid", obj.getSkid()));
nameVauePairs.add(new BasicNameValuePair("userName", obj.getUserName()));
nameVauePairs.add(new BasicNameValuePair("timestamp", obj.getTimestamp()));
nameVauePairs.add(new BasicNameValuePair("userProfileImg", obj.getUserProfileImg()));
nameVauePairs.add(new BasicNameValuePair("userMsg", obj.getUserMsg()));
nameVauePairs.add(new BasicNameValuePair("host_name", obj.getHost_name()));
nameVauePairs.add(new BasicNameValuePair("gallery_name", obj.getGallery_name()));
nameVauePairs.add(new BasicNameValuePair("logonUserName", obj.getLogonUserName()));
nameVauePairs.add(new BasicNameValuePair("logonUserMobileNumber", obj.getLogonUserMobileNumber()));
nameVauePairs.add(new BasicNameValuePair("logonUserId", obj.getLogonUserId()));
nameVauePairs.add(new BasicNameValuePair("userLocation", obj.getUserLocation()));
try {
HttpPost httppost = new HttpPost(Variable.WS_URL_SAVE_COMMENTS);
HttpClient httpclient = new DefaultHttpClient();
httppost.setEntity(new UrlEncodedFormEntity(nameVauePairs));
HttpResponse response1 = httpclient.execute(httppost);
StatusLine statusLine= response1.getStatusLine();
System.out.println("CommentPageActivity.SaveComment.doInBackground() | statusLine | "+statusLine);
{
HttpEntity entity =response1.getEntity();
is=entity.getContent();
InputStreamReader in =new InputStreamReader(is);
BufferedReader br = new BufferedReader(in);
String info="";
String nl=System.getProperty("line.separator");
while((info=br.readLine())!=null){
response.append(info.toString()+nl);
}
System.out.println("CommentPageActivity.SaveComment.doInBackground() | response.toString() | "+response.toString());
br.close();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}// doBackGroud
}// SaveComment
/* @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_comment_page, menu);
return true;
}*/
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
finish();
return true;
}
}
----------------- MyAdapter Class
package com.sk.comment;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.sk.bhangarwaala.R;
import com.sk.faq.AppController;
import com.sk.variable.Variable;
public class MyAdapter extends BaseAdapter {
private Context activity;
//private LayoutInflater inflater;
private List<CommentsFeedObj> feedItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private static int counter;
/*public MyAdapter(Activity activity, List<CommentsFeedObj> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
}*/
public MyAdapter(Context applicationContext, List<CommentsFeedObj> data) {
// TODO Auto-generated constructor stub
this.activity = applicationContext;
this.feedItems = data;
//inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
if(feedItems!=null)
return feedItems.size();
return 0;
}
@Override
public Object getItem(int location) {
return feedItems.get(location);
}
@Override
public long getItemId(int position) {
return position;
}
@SuppressLint("DefaultLocale")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
CompleteListViewHolder viewHolder;
View v = convertView;
counter=counter+1;
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
if (convertView == null){
LayoutInflater li = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.comment_page_list_comments, null);
viewHolder = new CompleteListViewHolder(v);
v.setTag(viewHolder);
}else{
viewHolder = (CompleteListViewHolder) v.getTag();
}
CommentsFeedObj item = feedItems.get(position);
System.out.println("MyAdapter.getView() | item | "+item.toString());
// sk id
viewHolder.commentPageTvSkid.setText(item.getSkid());
viewHolder.commentPageTvSkid.setVisibility(View.GONE);
// user profile img
if (item.getUserProfileImg()!=null && !item.getUserProfileImg().equalsIgnoreCase("null") && item.getUserProfileImg().length() >0){ // 1
String img=item.getHost_name()+"/"+item.getGallery_name()+"/"+item.getUserProfileImg();
System.out.println("MyAdapter.getView() | img | "+img);
viewHolder.commentPageNivProfileImg.setImageUrl(img, imageLoader);
}else{
System.out.println("MyAdapter.getView() | DEFAULT_PROFILE_IMG | "+imageLoader);
viewHolder.commentPageNivProfileImg.setImageUrl(Variable.DEFAULT_PROFILE_IMG, imageLoader);// 1
}
// user name
viewHolder.commentPageTvUserName.setText(item.getUserName().toUpperCase());
// time stamp
viewHolder.commentPageTvTimestamp.setText(item.getTimestamp());
// user msg
if(item.getUserMsg()!=null){
viewHolder.commentPageTvUserMsg.setText(item.getUserMsg());
}else{
viewHolder.commentPageTvUserMsg.setVisibility(View.GONE);
}
return v;
}
}//MainClass
class CompleteListViewHolder {
//http://androidadapternotifiydatasetchanged.blogspot.in/
TextView commentPageTvUserName,commentPageTvTimestamp,commentPageTvUserMsg ,commentPageTvSkid ;
NetworkImageView commentPageNivProfileImg ;
public CompleteListViewHolder(View convertView) {
commentPageTvUserName = (TextView) convertView.findViewById(R.id.commentPageListCommentsTvUserName);
commentPageTvTimestamp = (TextView) convertView.findViewById(R.id.commentPageListCommentsTvTimestamp);
commentPageTvUserMsg = (TextView) convertView.findViewById(R.id.commentPageListCommentsTvUserMsg);
commentPageTvSkid = (TextView) convertView.findViewById(R.id.commentPageListCommentsTvSkid);
commentPageNivProfileImg = (NetworkImageView) convertView.findViewById(R.id.commentPageListCommentsNivProfileImg);
}
}
答案 0 :(得分:2)
当您添加新的通讯时,请始终在data
的开头添加此评论。然后刷新ListView
data.add(0, commnent);
listAdapter.notifyDataSetChanged();
答案 1 :(得分:0)
在初始化新适配器之前,您可以这样做:
#include <iostream>
using namespace std;
int *readkid(){
int * kids = new int[4];
int counter=1;
for (int i=0; i<4 ; i++ ){
cout << "Enter the age for kid number " << counter << ":[ 1 to 10] " << endl;
cin >> kids[i];
counter++;
}
return kids;
}
void classifyKids (int * x){
int * perk = new int[20];
int * kg1 = new int[20];
int * kg2 = new int[20];
int * elementry = new int[4];
for ( int i=0; i <21; i++){
if ( x[i] < 3 ){
perk[i] = x[i];
} else if ( x[i] < 3 && x[i] > 3) {
kg1[i] = x[i];
} else if( x[i] > 6 && x[i] > 4){
kg2[i] = x[i];
} else if(x[i] > 6){
elementry[i] = (x[i]);
}
}
for(int i=0; i<4;i++)
cout << "Here is it :" << elementry[i] << endl;
}
int main() {
int *x;
x = readkid ();
classifyKids(x);
/*
for (int i=0; i<4; i++){
cout << *(x+i) << endl;
}
*/
return 0;
}
这会在列表的开头添加新值。
答案 2 :(得分:-1)
您可以通过在顶部添加标题来完成。应该有adapterView或list的方法。我去年做过。我记得每个列表只允许一个标题项。
答案 3 :(得分:-1)
最后完成后,我在onClick Action上使用了data.add(0,obj)而不是data.add(obj)。
void onClickCommentButton(){
data.add(0,obj);
listAdapter= new MyAdapter(this, data);
commentPageLvCommentsList.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}