简体   繁体   中英

Adding new item on top of listview

When i insert my parsed data into the listview, the added items appear at the bottom i want to put them on top like on facebook new posts are added on top. here is my code:
I am retrieving my comments from a server. Pls help me out

This is the Readpost.java

private static final String TAG_SUCCESS = "success";
private static final String TAG_TITLE = "title";
private static final String TAG_POSTS = "posts";
private static final String TAG_POST_ID = "post_id";
private static final String TAG_USERNAME = "username";
private static final String TAG_MESSAGE = "message";

private JSONArray mComments = null;

private ArrayList<HashMap<String, String>> mCommentList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.newsfeed);
}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    // loading the comments via AsyncTask
    new LoadComments().execute();
}

public void addComment(View v) {
    Intent i = new Intent(Readpost.this, Addpost.class);
    startActivity(i);
}

/**
 * Retrieves recent post data from the server.
 */
public void updateJSONdata() {
    mCommentList = new ArrayList<HashMap<String, String>>();
    JSONParser jParser = new JSONParser();

    JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);

    try {


        mComments = json.getJSONArray(TAG_POSTS);
        for (int i = 0; i < mComments.length(); i++) {
            JSONObject c = mComments.getJSONObject(i);              
            String title = c.getString(TAG_TITLE);
            String content = c.getString(TAG_MESSAGE);
            String username = c.getString(TAG_USERNAME);


            HashMap<String, String> map = new HashMap<String, String>();

            map.put(TAG_TITLE, title);
            map.put(TAG_MESSAGE, content);
            map.put(TAG_USERNAME, username);


            mCommentList.add(map);

        }

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

private void updateList() {

    ListAdapter adapter = new SimpleAdapter(this, mCommentList,
            R.layout.singlepost, new String[] { TAG_TITLE, TAG_MESSAGE,
                    TAG_USERNAME }, new int[] { R.id.title, R.id.message,
                    R.id.username });


    setListAdapter(adapter);

    ListView lv = getListView();

    lv.scrollTo(0, 0);


    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

        }
    });
} 

And this is the Addpost.java

private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

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

    title = (EditText)findViewById(R.id.title);
    message = (EditText)findViewById(R.id.message);

    mSubmit = (Button)findViewById(R.id.submit);
    mSubmit.setOnClickListener(this);

}

@Override
public void onClick(View v) {
            new PostComment().execute();
}


class PostComment extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Addpost.this);
        pDialog.setMessage("Posting...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
         // Check for success tag
        int success;

        String post_title = title.getText().toString();
        String post_message = message.getText().toString();

        try {
            final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext()); 
            String value =(mSharedPreference.getString("username", "anon"));
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", value));      
            params.add(new BasicNameValuePair("title", post_title));
            params.add(new BasicNameValuePair("message", post_message));

            Log.d("request!", "starting");


            JSONObject json = jsonParser.makeHttpRequest(
                    POST_COMMENT_URL, "POST", params);


            Log.d("Post Comment attempt", json.toString());


            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("Comment Added!", json.toString());    
                finish();
                return json.getString(TAG_MESSAGE);
            }else{
                Log.d("Comment Failure!", json.getString(TAG_MESSAGE));
                return json.getString(TAG_MESSAGE);

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

        return null;

    }

    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        if (file_url != null){
            Toast.makeText(Addpost.this, file_url, Toast.LENGTH_LONG).show();
        }

    }

}

}

Assuming you retain your ListAdapter as follows:

ListAdapter mAdapter;

You can add a new item like this.

HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, "New Title");
map.put(TAG_MESSAGE, "new content");
map.put(TAG_USERNAME, "someone");

mCommentList.add(0, map);
mAdapter.notifyDatasetChanged();

Use this:

mCommentList.add(0, obj);
listAdapter.notifyDataSetChanged();
listView.scrollTo(0, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM