动态地在服务器响应上从Listview添加更新和删除项目

时间:2015-05-21 04:37:20

标签: android listview android-asynctask

您好我不知道是否提出正确的问题,但我想在Facebook上发表评论,更新评论和删除评论。

当我添加评论时,它会向服务器发送请求,它将给出带有新值的响应以填写listadapter,并且在点击输入或添加按钮后,我的列表视图中可能会显示该更改,并且在删除时它会向服务器和响应填充我的listAdapter。并且更改可能会出现在我的列表视图中而不刷新列表视图。我该如何执行此操作。

谢谢你。

这是我的班级。

public class CommmentActivity extends Activity{



DatabaseHandler db = new DatabaseHandler(this);
List<CommentListInfo> list_CommentInfo = new ArrayList<CommentListInfo>();
List<String> SuggetionList;
AutoCompleteTextView aCompletView;
EditText etComment;
String strComment;
ArrayAdapter<String> mentionList;
ListCommentAdapter commentAdapter;
ImageView IvAddComment;
ListView CommentList;
SessionCreator m_session;
boolean m = false;

boolean mBuzy;

int FirstPosition;
int ItemCounted;
int CurrentScrollState;
int TotalItemCount;

String UserId;
String VidoId;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.commentvideo_main);


    SuggetionList =  new ArrayList<String>();
    String Curl = GlobalMethod.TokenGenerator() + "&action=getCommentsVideo";

    Intent data = getIntent();
    UserId = data.getStringExtra("userId");
    VidoId = data.getStringExtra("videoId");
    init();

    String strfriendsSyncDate = m_session.getfriendsSyncDate();

    Log.d("mData", strfriendsSyncDate);




    new CommentsDetail().execute(UserId,VidoId,strfriendsSyncDate,Curl,"1");


    commentAdapter = new ListCommentAdapter(getApplicationContext(), list_CommentInfo);
        CommentList.setAdapter(commentAdapter); 

    CommentList.setOnScrollListener(new OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            // TODO Auto-generated method stub

            switch (scrollState) {
            case OnScrollListener.SCROLL_STATE_IDLE:{
                commentAdapter.notifyDataSetChanged();
                //ManipulateVisibleView(view);
                break;
            }

            case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
            {
                mBuzy = true;
                break;
            }

            case OnScrollListener.SCROLL_STATE_FLING:{
                mBuzy = true;
                break;
            }


            default:
                break;
            }
        }



        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {
            // TODO Auto-generated method stub
            FirstPosition = firstVisibleItem;
            ItemCounted = visibleItemCount;
            TotalItemCount = totalItemCount;
            int LastPosition = view.getLastVisiblePosition();
            Log.d("First Position", ""+FirstPosition);
            Log.d("ItemCountes",""+ItemCounted);
            Log.d("totalItemCount",""+TotalItemCount);
            Log.d("LastPosition",""+LastPosition);


            if(visibleItemCount!=0 && ((firstVisibleItem+visibleItemCount)>=(totalItemCount))){

            Log.d("mCalled", "call");
            }
        isScrollCompleted();
        }
    });



IvAddComment.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            strComment = etComment.getText().toString();
            etComment.getText().clear();
            String strUrl = GlobalMethod.TokenGenerator() + "&action=addCommentsVideo";

            new CommentsDetail().execute(UserId,VidoId,strComment,strUrl,"0");
            commentAdapter.notifyDataSetChanged();
        }
    });



}
private void isScrollCompleted(){
if(this.ItemCounted >0 && this.CurrentScrollState == OnScrollListener.SCROLL_STATE_IDLE){
    Log.d("ItemCounted",""+ItemCounted);
    Log.d("CurrentScrollState",""+CurrentScrollState);
}   
}

private void init() {
    // TODO Auto-generated method stub
    m_session = new SessionCreator(getApplicationContext());
    etComment = (EditText)findViewById(R.id.etComments);
    CommentList = (ListView)findViewById(R.id.lvLatestComments);
    IvAddComment = (ImageView)findViewById(R.id.addComment);
}

public class CommentsDetail extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub


        ServiceHandler serviceClient;
        String mJsonString;

        try{

            String userId = (String)params[0];
            String vId = (String)params[1];
            if(params[4].equals("0")){


                String comment = (String)params[2];
                String strUrl = (String)params[3];

                List<NameValuePair> paramsNameValuePairs = new ArrayList<NameValuePair>();

                paramsNameValuePairs.add(new BasicNameValuePair("userId", userId));
                paramsNameValuePairs.add(new BasicNameValuePair("videoId", vId));
                paramsNameValuePairs.add(new BasicNameValuePair("commentText", comment));

                serviceClient = new ServiceHandler();
                mJsonString = serviceClient.makeServiceCall(strUrl,
                        ServiceHandler.POST, paramsNameValuePairs);

                Log.i("---->>>>>>>>>>", paramsNameValuePairs + "");
            }else{

                String syncdate = (String)params[2];
                String strUrl = (String)params[3];

                List<NameValuePair> paramsNameValuePairs = new ArrayList<NameValuePair>();

                paramsNameValuePairs.add(new BasicNameValuePair("userId", userId));
                paramsNameValuePairs.add(new BasicNameValuePair("videoId", vId));
                paramsNameValuePairs.add(new BasicNameValuePair("friendsSyncDate", syncdate));

                serviceClient = new ServiceHandler();
                mJsonString = serviceClient.makeServiceCall(strUrl,
                        ServiceHandler.POST, paramsNameValuePairs);

                Log.i("---->>>>>>>>>>", paramsNameValuePairs + "");
            }



        Log.d("Response Json-----------------------",mJsonString );


        return mJsonString;

    }catch (Exception e) {
        e.getStackTrace();
    }

    return null;
    }

    @SuppressWarnings({ "unchecked", "unchecked", "unchecked" })
    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);


        try{
        if (result != null) {
            JSONObject responsJsonObj = new JSONObject(result);
            JSONObject jsonObj = (JSONObject) responsJsonObj
                    .optJSONObject("data");

            try {
                String str = jsonObj.getString("error");
                if ( str != null || str.length() != 0) {
                    // error
                    //Toast.makeText(NewsfeedActivity.this, jsonObj.getString("error"),Toast.LENGTH_LONG).show();
                    return;
                }
            } catch (JSONException je) {
                Log.d("jex ------>", "" + je.getMessage());
                try {
                    String str = jsonObj.getString("message");
                    Log.d("message=", "" + str);
                    if ( str != null || str.length() != 0) {
                        // VALID RESPONSE, NOW PARSE IT
                        if (jsonObj.has("comments")) {
                            JSONArray colArray = jsonObj.getJSONArray("comments");
                            Log.d("Colunm Array", ""+colArray);
                            int nComments = colArray.length();
                            Log.d("# comments", "" + nComments);
                            for(int i=0; i<nComments; i++){
                                JSONObject obj = colArray.getJSONObject(i);
                                Gson Comments = new Gson();
                                String strComments = Comments.toJson(obj);
                                Log.d("# obj=", "" + obj.toString());               
                                CommentListInfo cmtInfo = new CommentListInfo();                
                                cmtInfo.c_userId = obj.getString("userId");
                                cmtInfo.c_name = obj.getString("name");
                                cmtInfo.DateAdded = obj.getString("dateAdded");
                                cmtInfo.CommentId = obj.getString("commentId");
                                cmtInfo.CommentText = obj.getString("text");
                                cmtInfo.ImageUrl = obj.getString("imageLink");
                                list_CommentInfo.add(cmtInfo);  
                            }
                        }
                    }

                    if ( str != null || str.length() != 0) {
                        // VALID RESPONSE, NOW PARSE IT
                        if (jsonObj.has("addPosition")) {
                                Log.d("# obj=", "" + jsonObj.toString());   
                                Log.d("Add Position", jsonObj.getString("addPosition"));
                        }
                    }

//                      
                    if ( str != null || str.length() != 0) {
                        // VALID RESPONSE, NOW PARSE IT
                        if (jsonObj.has("friendsSyncDate")) {
                            Log.d("# friendsDeleted", "" + jsonObj);
                                Log.d("# obj=", "" + jsonObj.toString());   

                                String myString = m_session.getfriendsSyncDate();
                                Log.d("myString", myString);

                                m_session.putfriendsSyncDate(jsonObj.getString("friendsSyncDate"));
                                Log.d("Sync Date "," "+jsonObj.getString("friendsSyncDate"));
                        }
                    }

                } catch (JSONException je2) {
                    je2.printStackTrace();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    }

   }

 }

这是我的适配器类。

public class ListCommentAdapter extends BaseAdapter{

private Context mContext;
private List<CommentListInfo> CommentsInfo;
private LayoutInflater inflater;
private String szUserId;
private String szVideoID;

private boolean mBuzy = false;



public ListCommentAdapter(Context context, List<CommentListInfo> cmtInfo) {
    // TODO Auto-generated constructor stub
    mContext = context;
    CommentsInfo = cmtInfo;
    AppData mmap = (AppData)this.mContext.getApplicationContext();
    szUserId = mmap.getUserId();
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return CommentsInfo.size();
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return CommentsInfo.get(position);
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    Holder holder = new Holder();


    CommentListInfo c = CommentsInfo.get(position);


    try{

        Log.i("nUserId", c.c_userId);
        Log.i("nName", c.c_name);
        Log.i("nCommentId", c.CommentId);
        Log.i("nCommnet", c.CommentText);
        Log.i("nImageUrl",c.ImageUrl);

    }catch(Exception e){
        Log.e("Erore is",""+e);
    }


    try{
            if(inflater==null){
                inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            }

            if(convertView==null){
                convertView = inflater.inflate(R.layout.comment_list_item, null);
                holder.ciProfileImage = (CircleImageView)convertView.findViewById(R.id.civCFLeftPic);
                holder.tvComments = (TextView)convertView.findViewById(R.id.tvCommentbox);
                holder.tvCDate = (TextView)convertView.findViewById(R.id.tvCfNotifyDate);
                holder.tvName = (TextView)convertView.findViewById(R.id.tvCommentName);
                convertView.setTag(holder);
            }else{
                holder = (Holder)convertView.getTag();
            }


            if(!mBuzy){

                RemoteImageLoader task = new RemoteImageLoader();
                task.setImageView(holder.ciProfileImage);
                task.execute(c.ImageUrl);

                Log.d("ImagerUrl", c.ImageUrl);
                if(c.ImageUrl!=null){
                    Picasso.with(mContext)
                    .load(R.drawable.world1)
                    .placeholder(R.drawable.world1)
                    .error(R.drawable.world1)
                    .into(holder.ciProfileImage);

                }else{
                    Picasso.with(mContext)
                    .load(R.drawable.world1)
                    .placeholder(R.drawable.world1)
                    .error(R.drawable.world1)
                    .into(holder.ciProfileImage);
                }
            holder.tvComments.setText(c.CommentText);
            holder.tvCDate.setText(c.DateAdded);
            holder.tvName.setText(c.c_name);
            holder.tvComments.setTag(null);

            }else{
                holder.tvComments.setText("Loading...");
                holder.tvComments.setTag(this);
            }

            return convertView;
        }catch(Exception e){
            System.out.println("Error IS :- "+ e);
        }

    return convertView;
}

private static class Holder{
    private TextView tvName,tvComments,tvCDate;
    private CircleImageView ciProfileImage;     
 }
}

2 个答案:

答案 0 :(得分:2)

你可能已经解决了这个问题,但我正在使用Java开发一个不同的应用程序并遇到类似的问题。我有点简单,因为我使用的是本地数据库,但同样的事情。在 CommmentActivity的onCreate 方法中,拉出commentAdapter声明和CommentList.setOnScrollListener并将它们放在自己的方法中。然后在onCreate中调用新定义的commentAdapter方法,然后解析响应。  像这样的东西

public void myAdaperMethod(Context context, List<CommentListInfo>      list_CommentInfo){
commentAdapter = new ListCommentAdapter(this, list_CommentInfo);
CommentList.setAdapter(commentAdapter);
CommentList.setOnScrollListener(new OnScrollListener(){...}
}

onCreate{
myAdapterMethod(...);
}

post{...}
get{myAdapterMethod(...);}

希望有所帮助。

答案 1 :(得分:0)

在listadapter具有新数据集之后,您只需要重新绑定控件。

CommentList.DataBind();