执行Facebook集成到我的应用程序,但它没有执行(没有错误)

时间:2013-12-26 09:33:12

标签: java android facebook facebook-graph-api android-listview

我正在尝试在Android模拟器上运行我的项目,该项目没有错误,添加了对Facebook SDK的引用。但是,当我运行应用程序时,它会显示“onerror”消息..

请任何人都可以执行我的代码并告诉我问题(或)给我解决方案

MainActivity.java

package com.example.simplelogin1;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Util;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

public class MainActivity extends Activity implements OnClickListener 
  {
     ImageView button,userImage;
     TextView textName;
     Button btnShowAccessTokens;    
      ListView listv; 

String FILENAME = "AndroidSSO_data";
String imageURL = "";
String name = "";
String userName = "";
String gender = "";
String _error;
String access_token;

private AsyncFacebookRunner mAsyncRunner=null;  
private SharedPreferences mPrefs;

Facebook fb=null;      
ArrayList<String> friends_list;    
Boolean Connectiontimeout = false;    
Bitmap profilePic;  

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String APP_ID="650535718332424"; //****************************APP_ID************************************
    fb=new Facebook(APP_ID);        
    mAsyncRunner = new AsyncFacebookRunner(fb);     
    friends_list = new ArrayList<String>(); 

    btnShowAccessTokens = (Button) findViewById(R.id.btn_show_access_tokens);       
    button=(ImageView) findViewById(R.id.login); 
    listv=(ListView) findViewById(R.id.listView1);
    userImage = (ImageView) findViewById(R.id.imageView1);
    textName = (TextView) findViewById(R.id.textView1);

    button.setOnClickListener(this);                
    updateButtonImage();        
//***************************Access Token Button*****************************************
    btnShowAccessTokens.setOnClickListener(new View.OnClickListener() 
    {
        @Override
        public void onClick(View v) 
        {
            showAccessTokens();
        }
    });         
}   
public void showAccessTokens() 
{
    String access_token = fb.getAccessToken();
    Toast.makeText(getApplicationContext(),"Access Token: " + access_token, Toast.LENGTH_LONG).show();
}
//***********************************************************************************

//*****************************Login and Logout Image Button*****************************
private void updateButtonImage() 
{
    if(fb.isSessionValid())
    {
        button.setImageResource(R.drawable.logout_button);
    }else
    {
        button.setImageResource(R.drawable.login_button);
    }
}
//***************************************************************************************

//**************************Login Onclick Method*****************************************
@Override
public void onClick(View v) 
{
    if(fb.isSessionValid())
    {
        //*****************Logout********************
        try{
            fb.logout(getApplicationContext());
            updateButtonImage();
            userImage.setVisibility(View.INVISIBLE);
            textName.setVisibility(View.INVISIBLE);
            btnShowAccessTokens.setVisibility(View.INVISIBLE);  
            listv.setVisibility(View.INVISIBLE);                
           }catch (MalformedURLException e) 
                {
                    e.printStackTrace();
                }catch (IOException e) 
                    {
                        e.printStackTrace();
                    }
      //************************************************************    
    }else
    {   
      //**********************Login**********************************
        mPrefs = getPreferences(MODE_PRIVATE);
        String access_token = mPrefs.getString("access_token", null);
        long expires = mPrefs.getLong("access_expires", 0);
        if (access_token != null) 
            {
                fb.setAccessToken(access_token);                    
                // Making show access tokens button visible
                //btnShowAccessTokens.setVisibility(View.VISIBLE);
                //listv.setVisibility(View.VISIBLE);
                Log.d("FB Sessions", "" + fb.isSessionValid());
            }
            if (expires != 0) 
                {
                    fb.setAccessExpires(expires);
                }   
                 { 
                    fb.authorize(this,new String[] {"email","publish_stream"} , new DialogListener() 
                    {               
                        @Override
                        public void onFacebookError(FacebookError e)
                        {                   
                            Toast.makeText(MainActivity.this, "fbError", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onError(DialogError e) 
                        {               
                            Toast.makeText(MainActivity.this, "onError", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onComplete(Bundle values)
                        {
                            updateButtonImage();
                            // Function to handle complete event Edit Preferences and update facebook acess_token                               
                            SharedPreferences.Editor editor = mPrefs.edit();
                            editor.putString("access_token",fb.getAccessToken());
                            editor.putLong("access_expires",fb.getAccessExpires());
                            editor.commit();
                            //getting user profile      
                            try {
                                JSONObject me = new JSONObject(fb.request("me"));
                                new getFacebookData().execute();
                                } catch (MalformedURLException e) 
                                    {
                                        e.printStackTrace();
                                    } catch (JSONException e) 
                                        {
                                        e.printStackTrace();
                                        } catch (IOException e) 
                                            {
                                            e.printStackTrace();
                                            }                       
                            //getting users Friend list
                            mAsyncRunner.request("me/friends", new FriendsRequestListener());
                            Toast.makeText(getApplicationContext(), "Success ", Toast.LENGTH_LONG).show();
                            userImage.setVisibility(View.VISIBLE);
                            textName.setVisibility(View.VISIBLE);
                            btnShowAccessTokens.setVisibility(View.VISIBLE);
                            listv.setVisibility(View.VISIBLE);                      
                        }               
                        @Override
                        public void onCancel()
                        {
                            Toast.makeText(MainActivity.this, "onCancel", Toast.LENGTH_SHORT).show();
                        }
                    });         
                 }
    }
}   

//***************************************onActivityResult********************************************
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    super.onActivityResult(requestCode, resultCode, data);
    fb.authorizeCallback(requestCode, resultCode, data);
}

//***********************************getting users Friend list Function*******************************
private class FriendsRequestListener implements RequestListener 
{
    String friendData;
    //Method runs when request is complete
    public void onComplete(String response, Object state)
    {
        Log.v("", "FriendListRequestONComplete");
        //Create a copy of the response so i can be read in the run() method.
        friendData = response; 
        Log.v("friendData--", ""+friendData);
        //Create method to run on UI thread
        MainActivity.this.runOnUiThread(new Runnable() 
        {
            public void run() 
            {
                try 
                {
                    //Parse JSON Data
                    JSONObject json;
                    json = Util.parseJson(friendData);
                    //Get the JSONArry from our response JSONObject
                    JSONArray friendArray = json.getJSONArray("data");
                    Log.v("friendArray--", ""+friendArray);                        
                    for(int i = 0; i< friendArray.length(); i++)
                    {
                        JSONObject frnd_obj = friendArray.getJSONObject(i);
                        friends_list.add(frnd_obj.getString("name")+"~~~"+frnd_obj.getString("id"));
                    }                        
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1,android.R.id.text1, friends_list);                        
                    listv.setAdapter(adapter);                        
                } catch (JSONException e) 
                {
                    e.printStackTrace();
                } catch (FacebookError 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)
    {          
    }
 }
//**********************************************************************************************

//**************Async class for getting facebook data in background thread**********************
public class getFacebookData extends AsyncTask<String, Void, String> 
{
    ProgressDialog pd = null;
    @Override
    protected void onPreExecute(){
        pd = ProgressDialog.show(MainActivity.this, "Please wait","Loading please wait..", true);
        pd.setCancelable(true);
    }

    @Override
    protected String doInBackground(String... params){
        fbUserProfile();
        return null;
    }

    @Override
    protected void onPostExecute(String result){
        pd.dismiss();
        if (Connectiontimeout != true) 
        {
            textName.setText(name);
            userImage.setImageBitmap(profilePic);
        } else {
            Toast.makeText(MainActivity.this, "Connection Time out",Toast.LENGTH_SHORT).show();
        }
    }
}
//**********************************************************************************************************

//**********************getting user facebook data from facebook server****************************************
public void fbUserProfile()
{
    try{
        access_token = mPrefs.getString("access_token", null);
        JSONObject jsonObj = null;
        JSONObject jsonObjData = null;
        JSONObject jsonObjUrl = null;
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 50000);
        HttpConnectionParams.setSoTimeout(httpParameters, 50000);
        HttpClient client = new DefaultHttpClient(httpParameters);
        String requestURL = "https://graph.facebook.com/me?fields=picture,id,name&access_token="+ access_token;
        Log.i("Request URL:", "---" + requestURL);
        HttpGet request = new HttpGet(requestURL);
        HttpResponse response = client.execute(request);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String webServiceInfo = "";
        while ((webServiceInfo = rd.readLine()) != null) 
        {
            Log.i("Service Response:", "---" + webServiceInfo);
            jsonObj = new JSONObject(webServiceInfo);
            jsonObjData = jsonObj.getJSONObject("picture");
            jsonObjUrl = jsonObjData.getJSONObject("data");
            name = jsonObj.getString("name");
            userName = jsonObj.getString("username");
            gender = jsonObj.getString("gender");
            imageURL = jsonObjUrl.getString("url");
            profilePic = BitmapFactory.decodeStream((InputStream) new URL(imageURL).getContent());
        }
    } catch (Exception e) 
        {
            Connectiontimeout = true;
        }
}
//***********************************************************************************************************
}

activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<ImageView 
    android:id="@+id/login"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/login_button"/>

 <Button
     android:id="@+id/btn_show_access_tokens"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignParentRight="true"
     android:layout_alignParentTop="true"
     android:text="Token"
     android:visibility="invisible" />

 <ListView
     android:id="@+id/listView1"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_alignParentRight="true"         
     android:layout_below="@+id/btn_show_access_tokens"
     android:visibility="invisible">
 </ListView>

 <ImageView
     android:id="@+id/imageView1"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignParentTop="true"
     android:layout_toRightOf="@+id/login"
     android:src="@drawable/ic_launcher"
     android:visibility="invisible" />

 <TextView
     android:id="@+id/textView1"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_above="@+id/listView1"
     android:layout_alignParentTop="true"
     android:layout_toLeftOf="@+id/btn_show_access_tokens"
     android:layout_toRightOf="@+id/imageView1"
     android:text="Name" 
     android:visibility="invisible"/>

</RelativeLayout>

manifest.file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.simplelogin1"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <activity
        android:name="com.example.simplelogin1.MainActivity"
        android:label="@string/app_name" >

        <intent-filter>

            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</manifest>

在我的drawable文件夹中:

login_button需要

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- When selected -->
<item android:drawable="@drawable/login"
      android:state_selected="true" />
<!-- When not selected-->
<item android:drawable="@drawable/login_down" />
</selector>

logout_button

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- When selected -->
<item android:drawable="@drawable/logout"
      android:state_selected="true" />
<!-- When not selected-->
<item android:drawable="@drawable/logout_down" />
</selector>

我的logcat:

12-26 15:07:01.189: D/Facebook-WebView(8330): Webview loading URL: https://m.facebook.com/dialog/oauth?display=touch&client_id=650535718332424&scope=email%2Cpublish_stream&type=user_agent&redirect_uri=fbconnect%3A%2F%2Fsuccess
12-26 15:07:01.309: D/Facebook-authorize(8330): Login failed: com.facebook.android.DialogError: The connection to the server was unsuccessful.
12-26 15:07:01.329: D/Facebook-WebView(8330): Webview loading URL: https://m.facebook.com/dialog/oauth?display=touch&client_id=650535718332424&scope=email%2Cpublish_stream&type=user_agent&redirect_uri=fbconnect%3A%2F%2Fsuccess

请有人可以帮助我......

0 个答案:

没有答案