0

MessagesActivity.java

package org.example.fbapp;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.AsyncFacebookRunner.RequestListener;

import android.app.ListActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MessagesActivity extends ListActivity {

    // Your Facebook APP ID
    private static String APP_ID = "549603678442054";
    ListAdapter adapter;
    // 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
    @SuppressWarnings("deprecation")
    private Facebook facebook = new Facebook(APP_ID);
    @SuppressWarnings("deprecation")
    private AsyncFacebookRunner mAsyncRunner;
    String FILENAME = "AndroidSSO_data";
    private SharedPreferences mPrefs;

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

    ListView mylistview;
    ArrayList<String> array_months;
    ArrayAdapter<String> listAdapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.contacts_view);
        mAsyncRunner = new AsyncFacebookRunner(facebook);
        ListAdapter adapter = createAdapter();
        setListAdapter(adapter);
    }

    /**
     * Creates and returns a list adapter for the current list activity
     * 
     * @return
     */
    @SuppressWarnings("deprecation")
    protected ListAdapter createAdapter()
    {
        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");
                    array_months = new ArrayList<String>();

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

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

                        array_months.add(message);

                        runOnUiThread(new Runnable() {

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

                        });
                    }

                    // Create a simple array adapter (of type string) with the test values
                    //ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, adapter);
                    adapter = new ArrayAdapter<String>(MessagesActivity.this,
                            android.R.layout.simple_list_item_1, array_months);

                } 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) {
            }
        });


        //setListAdapter(listAdapter);
        return adapter;
    }
}

FBAppActivity.java

package org.example.fbapp;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

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

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

    // 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>>();
    private ListView lv;
    // Buttons
    Button btnFbLogin;
    Button btnFbGetProfile;
    Button btnPostToWall;
    Button btnShowAccessTokens;
    Button btnFbLogout;
    Button btnGetPost;

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

        // facebook = new Facebook(APP_ID);
        btnFbLogin = (Button) findViewById(R.id.btn_fblogin);
        btnFbGetProfile = (Button) findViewById(R.id.btn_get_profile);
        btnPostToWall = (Button) findViewById(R.id.btn_fb_post_to_wall);
        btnShowAccessTokens = (Button) findViewById(R.id.btn_show_access_tokens);
        btnFbLogout = (Button) findViewById(R.id.btn_logout);
        btnGetPost = (Button) findViewById(R.id.btn_group_posts);
        mAsyncRunner = new AsyncFacebookRunner(facebook);




        /**
         * Login button Click event
         * */
        btnFbLogin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.d("Image Button", "button Clicked");
                loginToFacebook();
            }
        });

        /**
         * Logout button Click event
         * */
        btnFbLogout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.d("Logout Button", "button Clicked");
                logoutFromFacebook();
            }
        });
        /**
         * Getting facebook Profile info
         * */
        btnFbGetProfile.setOnClickListener(new View.OnClickListener() {

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

        /**
         * Posting to Facebook Wall
         * */
        btnPostToWall.setOnClickListener(new View.OnClickListener() {

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

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

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

                startActivity(new Intent(FBAppActivity.this, MessagesActivity.class));
            }
        });

        /**
         * Showing Access Tokens
         * */
        btnShowAccessTokens.setOnClickListener(new View.OnClickListener() {

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

    /**
     * Function to login into facebook
     * */
    @SuppressWarnings("deprecation")
    public void loginToFacebook() {

        mPrefs = getPreferences(MODE_PRIVATE);
        String access_token = mPrefs.getString("access_token", null);
        long expires = mPrefs.getLong("access_expires", 0);

        if (access_token != null) {
            facebook.setAccessToken(access_token);

            btnFbLogin.setVisibility(View.INVISIBLE);

            // Making get profile button visible
            btnFbGetProfile.setVisibility(View.VISIBLE);

            // Making post to wall visible
            btnPostToWall.setVisibility(View.VISIBLE);

            // Making show access tokens button visible
            btnShowAccessTokens.setVisibility(View.VISIBLE);

            // Making logout button visible
            btnFbLogout.setVisibility(View.VISIBLE);

            // Making group posts button visible
            btnGetPost.setVisibility(View.VISIBLE);

            Log.d("FB Sessions", "" + facebook.isSessionValid());
        }

        if (expires != 0) {
            facebook.setAccessExpires(expires);
        }

        if (!facebook.isSessionValid()) {
            facebook.authorize(this, new String[] { "email", "publish_stream",
                    "user_groups" }, new DialogListener() {

                @Override
                public void onCancel() {
                    // Function to handle cancel event
                }

                @Override
                public void onComplete(Bundle values) {
                    // Function to handle complete event
                    // Edit Preferences and update facebook acess_token
                    SharedPreferences.Editor editor = mPrefs.edit();
                    editor.putString("access_token", facebook.getAccessToken());
                    editor.putLong("access_expires",
                            facebook.getAccessExpires());
                    editor.commit();

                    // Making Login button invisible
                    btnFbLogin.setVisibility(View.INVISIBLE);

                    // Making logout Button visible
                    btnFbGetProfile.setVisibility(View.VISIBLE);

                    // Making post to wall visible
                    btnPostToWall.setVisibility(View.VISIBLE);

                    // Making show access tokens button visible
                    btnShowAccessTokens.setVisibility(View.VISIBLE);

                    // Making logout button visible
                    btnFbLogout.setVisibility(View.VISIBLE);

                    // Making group posts button visible
                    btnGetPost.setVisibility(View.VISIBLE);
                }

                @Override
                public void onError(DialogError error) {
                    // Function to handle error

                }

                @Override
                public void onFacebookError(FacebookError fberror) {
                    // Function to handle Facebook errors

                }

            });
        }
    }

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

    /**
     * Get Profile information by making request to Facebook Graph API
     * */
    @SuppressWarnings("deprecation")
    public void getProfileInformation() {
        mAsyncRunner.request("me", new RequestListener() {
            @Override
            public void onComplete(String response, Object state) {
                Log.d("Profile", response);
                String json = response;
                try {
                    // Facebook Profile JSON data
                    JSONObject profile = new JSONObject(json);

                    // getting name of the user
                    final String name = profile.getString("name");

                    // getting email of the user
                    final String email = profile.getString("email");

                    JSONObject birthday = profile.getJSONObject("location");

                    final String location = birthday.getString("name");

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            Toast.makeText(
                                    getApplicationContext(),
                                    "Name: " + name + "\nEmail: " + email
                                            + "\nLocation: " + location,
                                    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) {
            }
        });
    }

    /**
     * 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) {
            }
        });

        ListAdapter adapter = new SimpleAdapter(FBAppActivity.this, messages,
                R.layout.list_item,
                new String[] { TAG_MESSAGE }, new int[] {
                        R.id.name });
        //FBAppActivity.this.setListAdapter(adapter);
    }

    /**
     * Function to post to facebook wall
     * */
    @SuppressWarnings("deprecation")
    public void postToWall() {
        // post on user's wall.
        facebook.dialog(this, "feed", new DialogListener() {

            @Override
            public void onFacebookError(FacebookError e) {
            }

            @Override
            public void onError(DialogError e) {
            }

            @Override
            public void onComplete(Bundle values) {
            }

            @Override
            public void onCancel() {
            }
        });

    }

    /**
     * Function to show Access Tokens
     * */
    @SuppressWarnings("deprecation")
    public void showAccessTokens() {
        String access_token = facebook.getAccessToken();

        Toast.makeText(getApplicationContext(),
                "Access Token: " + access_token, Toast.LENGTH_LONG).show();
    }

    /**
     * Function to Logout user from Facebook
     * */
    @SuppressWarnings("deprecation")
    public void logoutFromFacebook() {
        mAsyncRunner.logout(this, new RequestListener() {
            @Override
            public void onComplete(String response, Object state) {
                Log.d("Logout from Facebook", response);
                if (Boolean.parseBoolean(response) == true) {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            // make Login button visible
                            btnFbLogin.setVisibility(View.VISIBLE);

                            // making all remaining buttons invisible
                            btnFbGetProfile.setVisibility(View.INVISIBLE);
                            btnPostToWall.setVisibility(View.INVISIBLE);
                            btnShowAccessTokens.setVisibility(View.INVISIBLE);
                            btnFbLogout.setVisibility(View.INVISIBLE);
                            btnGetPost.setVisibility(View.INVISIBLE);
                        }

                    });

                }
            }

            @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) {
            }
        });
    }

    /*
     * @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the
     * menu; this adds items to the action bar if it is present.
     * getMenuInflater().inflate(R.menu.fbapp, menu); return true; }
     */

}

当我单击按钮时,ListView打开但没有数据,即Empty set

Contacts_View.xml

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     >
     <ListView  
         android:id="@android:id/list"
         android:layout_width="fill_parent" 
         android:layout_height="wrap_content" 
         />
     <TextView android:id="@android:id/empty"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="Empty set"
         />
 </LinearLayout>

我的意思是这两个功能是相同的。getGPosts()在中被调用,FBAppActivity而在createAdapter()中被调用MessagesActivitygetGPosts()工作,但createAdapter()没有。请帮助我了解为什么会发生这种情况。

基本上我正在尝试从 facebook 组导入帖子。我Toast objectgetGPosts()[它在 FBAppActivity 类] 函数中工作正常。此函数getGPosts()在按钮单击时调用。我验证我正在使用Toast object. 现在我想将数据填充到ListView. 这是我做不到的。我尝试了各种方法,但没有一个对我有用。

4

2 回答 2

0

正如我所见,您正在扩展 ListActivity。所以下面的代码必须抛出一个 NPE。

lv = (ListView)findViewById(R.id.list);
lv.setAdapter(adapter);

您应该在方法中使用以下代码onComplete

setListAdapter(adapter);

或者

getListView().setAdapter(adapter);
于 2013-10-27T21:15:35.273 回答
0

因为您在方法中调用setListAdapter(adapter)隐式(Activity 的)ListView,onCreate(Bundle savedInstanceState)并且在getGPosts()您引用正确(可见)ListView 的方法中。只需将方法中提到的调用更改onCreate(Bundle savedInstanceState)为:

myListView = getListView();
myListView.setAdapter(adapter);

你应该没事!祝你好运!

PS 如果您的 ListActivity 遵循以下要求,此解决方案将起作用:

你自己的视图必须包含一个 ID 为“@android:id/list”的 ListView 对象

来自谷歌的文档

于 2013-10-27T20:54:34.850 回答