ListView加载没有数据 - Android

时间:2013-10-27 20:47:38

标签: android android-listview

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()会调用FBAppActivitycreateAdapter()会调用MessagesActivitygetGPosts()虽然有效但createAdapter()没有。请帮助我理解为什么会这样。

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

2 个答案:

答案 0 :(得分:0)

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

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

你应该没事!祝你好运!

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

  

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

来自Google's documentation

答案 1 :(得分:0)

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

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

您应该使用onComplete方法下面的代码;

setListAdapter(adapter);

getListView().setAdapter(adapter);