0

I am trying to bind ListView with ArrayList on a button click (btnGetPost) . I am very very very new to Android programming. Right now i am able to retrieve the Facebook Group Posts as a JSON Response. Then i am looping through this JSON object and adding all the messages to an ArrayList.

Now my question is, how do i display all the messages in a ListView on a button click. I mean how do i bind this ArrayList to a ListView ? Kindly point me in the right direction.

package org.example.fbapp;



@SuppressWarnings("deprecation")
public class FBAppActivity extends Activity {

    // Your Facebook APP ID
    private static String APP_ID = "********************";

    // JSON Node names
    private static final String TAG_DATA = "data";
    private static final String TAG_MESSAGE = "message";

    // data JSONArray
    JSONArray data = null;

    // Instance of Facebook Class
    private Facebook facebook = new Facebook(APP_ID);
    private AsyncFacebookRunner mAsyncRunner;
    String FILENAME = "AndroidSSO_data";
    private SharedPreferences mPrefs;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> messages = new ArrayList<HashMap<String, String>>();

    // Buttons

    Button btnGetPost;

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fbapp);


        btnGetPost = (Button) findViewById(R.id.btn_group_posts);
        mAsyncRunner = new AsyncFacebookRunner(facebook);


        /**
         * Get Posts from Group
         * */
        btnGetPost.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                getGPosts();
            }
        });


    }



    @SuppressWarnings("deprecation")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        facebook.authorizeCallback(requestCode, resultCode, data);
    }



    /**
     * Get Group Posts by making request to Facebook Graph API
     * */
    @SuppressWarnings("deprecation")
    public void getGPosts() {
        mAsyncRunner.request("203153109726651/feed", new RequestListener() {
            @Override
            public void onComplete(String response, Object state) {
                Log.d("GET POSTS", response);
                String json = response;

                try {

                    // Facebook Profile JSON data
                    JSONObject obj = new JSONObject(json);
                    JSONArray finalObj = obj.getJSONArray("data");

                    for (int i = 0; i < finalObj.length(); i++) {

                        final String message = finalObj.getJSONObject(i)
                                .getString("message");

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

                        // adding each child node to HashMap key => value
                        map.put(TAG_MESSAGE, message);

                        // adding HashList to ArrayList
                        messages.add(map);


                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(),
                                        "Name: " + message, Toast.LENGTH_LONG)
                                        .show();
                            }

                        });
                    }

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

        }

            @Override
            public void onIOException(IOException e, Object state) {
            }

            @Override
            public void onFileNotFoundException(FileNotFoundException e,
                    Object state) {
            }

            @Override
            public void onMalformedURLException(MalformedURLException e,
                    Object state) {
            }

            @Override
            public void onFacebookError(FacebookError e, Object state) {
            }
        });
    }


    }



}

2 Answers 2

1

Basically if you have data in your arraylist,

then you can put it into adapter which will load data to views in listview

ListView and Adapter BasicsHow it works:

  1. ListView asks adapter “give me a view” (getView) for each item of the list
  2. A new View is returned and displayed

So you can try to override BaseAdapter

An example of overriding BaseAdapter: You can just Pay Attention to getView method. That's pretty much the essence of adapter.

private class MyCustomAdapter extends BaseAdapter {


    private ArrayList mData = new ArrayList();
    private LayoutInflater mInflater;

    public MyCustomAdapter() {
        mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public void addItem(final String item) {
        mData.add(item);
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public String getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        System.out.println("getView " + position + " " + convertView);
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.item1, null);
            holder = new ViewHolder();
            holder.textView = (TextView)convertView.findViewById(R.id.text);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder)convertView.getTag();
        }
        holder.textView.setText(mData.get(position));
        return convertView;
    }

}

Then you can simply do the following to your ListView view;

view.setAdapter(myAdapter);

More detailed explanation in this blog http://android.amberfog.com/?p=296

(which isn't mine. i copied the sample code and some of the explanation from this page)

Sign up to request clarification or add additional context in comments.

Comments

0

You bind your data to the ListView through its Adapter. In this case it would be useful to write your own Adapter derived from ArrayAdapter You can keep a reference of your data as a member of the custom Adapter.

1 Comment

Please show me some sample code. As i mentioned in the question that i am new to Android Programming, I am unable to follow you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.