2017-02-19 95 views
0

IM無法獲取Facebook的個人資料圖片:如何獲得Facebook的個人資料PIC機器人工作室

package com.androidtutorialpoint.flogin.Adapter; 

import android.annotation.TargetApi; 
import android.content.Context; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.drawable.BitmapDrawable; 
import android.graphics.drawable.Drawable; 
import android.os.AsyncTask; 
import android.os.Build; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.ImageView; 
import android.widget.LinearLayout; 
import android.widget.TextView; 

import com.androidtutorialpoint.flogin.ImageHelper; 
import com.androidtutorialpoint.flogin.Model.Post_Song; 
import com.androidtutorialpoint.flogin.R; 
import com.squareup.picasso.Callback; 
import com.squareup.picasso.Picasso; 
import com.squareup.picasso.Target; 

import java.io.IOException; 
import java.io.InputStream; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.util.ArrayList; 

/** 
* Created by sravya on 19-02-2017. 
*/ 
public class SongPostListAdapter extends BaseAdapter { 


    private Context context; 
    private int layout; 
    private ArrayList<Post_Song> songlist; 

    public SongPostListAdapter(ArrayList<Post_Song> songlist, int layout, Context context) { 
     this.songlist = songlist; 
     this.layout = layout; 
     this.context = context; 
    } 

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

    @Override 
    public Object getItem(int position) { 
     return songlist.get(position); 
    } 

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

    private class ViewHolder{ 
     TextView name,time,title,artist; 
     LinearLayout song_pic; 

    } 
    ImageView profilePicImageView; 

    @Override 
    public View getView(int position, View view, ViewGroup parent) { 
     View row = view; 
     ViewHolder holder = new ViewHolder(); 
     if(row ==null){ 
      LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      row = inflater.inflate(layout,null); 
      holder.artist = (TextView)row.findViewById(R.id.artist); 
      holder.name = (TextView)row.findViewById(R.id.user_name); 
      holder.time = (TextView)row.findViewById(R.id.time); 
      holder.title = (TextView)row.findViewById(R.id.song_title); 
      holder.song_pic = (LinearLayout)row.findViewById(R.id.track_pic); 
      //holder.userImage =(ImageView) row.findViewById(R.id.user_pic); 
      profilePicImageView = (ImageView) row.findViewById(R.id.profilePicture); 
      row.setTag(holder); 
     }else{ 
      holder = (ViewHolder)row.getTag(); 
     } 

     Post_Song posts = songlist.get(position); 
     holder.artist.setText(posts.getArtist()); 
     holder.name.setText(posts.getUname()); 
     holder.time.setText(posts.getTime()); 
     holder.title.setText(posts.getTitle()); 
     new LoadProfileImage(profilePicImageView).execute(posts.getUser_pic()); 

     final ViewHolder finalHolder = holder; 
     Picasso.with(context).load(posts.getArtwork()).placeholder(R.drawable.music_placeholder).into(new Target(){ 

      @TargetApi(Build.VERSION_CODES.JELLY_BEAN) 
      @Override 
      public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { 
       finalHolder.song_pic.setBackground(new BitmapDrawable(context.getResources(), bitmap)); 
      } 

      @Override 
      public void onBitmapFailed(final Drawable errorDrawable) { 
       Log.d("TAG", "FAILED"); 
      } 

      @Override 
      public void onPrepareLoad(final Drawable placeHolderDrawable) { 
       Log.d("TAG", "Prepare Load"); 
      } 
     }); 


     return row; 
    } 


    private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> { 
     ImageView bmImage; 

     public LoadProfileImage(ImageView bmImage) { 
      this.bmImage = bmImage; 
     } 

     protected Bitmap doInBackground(String... uri) { 
      String url = uri[0]; 
      Bitmap mIcon11 = null; 
      try { 
       InputStream in = new java.net.URL(url).openStream(); 
       mIcon11 = BitmapFactory.decodeStream(in); 
      } catch (Exception e) { 
       Log.e("Error", e.getMessage()); 
       e.printStackTrace(); 
      } 
      return mIcon11; 
     } 

     protected void onPostExecute(Bitmap result) { 

      if (result != null) { 


       Bitmap resized = Bitmap.createScaledBitmap(result,90,90, true); 
       bmImage.setImageBitmap(ImageHelper.getRoundedCornerBitmap(context,resized,100,90,90, false, false, false, false)); 

      } 
     } 
    } 


} 

這是我的適配器。 Iam無法在這裏獲得個人資料照片。

這是我的Facebook片段,這裏有一個與獲取的個人資料相片

package com.androidtutorialpoint.flogin; 

import android.content.Intent; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.net.Uri; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.support.annotation.Nullable; 
import android.support.v4.app.Fragment; 
import android.support.v7.app.AlertDialog; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.Button; 
import android.widget.ImageView; 
import android.widget.TextView; 
import android.widget.Toast; 
import android.content.Context; 
import android.content.SharedPreferences; 
import com.facebook.AccessToken; 
import com.facebook.CallbackManager; 
import com.facebook.FacebookAuthorizationException; 
import com.facebook.FacebookCallback; 
import com.facebook.FacebookException; 
import com.facebook.FacebookSdk; 
import com.facebook.GraphRequest; 
import com.facebook.GraphResponse; 
import com.facebook.Profile; 
import com.facebook.ProfileTracker; 
import com.facebook.appevents.AppEventsLogger; 
import com.facebook.login.LoginManager; 
import com.facebook.login.LoginResult; 
import com.facebook.login.widget.LoginButton; 
import com.facebook.share.ShareApi; 
import com.facebook.share.Sharer; 
import com.facebook.share.model.ShareLinkContent; 
import com.facebook.share.model.SharePhoto; 
import com.facebook.share.model.SharePhotoContent; 
import com.facebook.share.widget.ShareDialog; 

import org.json.JSONObject; 

import java.io.InputStream; 
import java.util.ArrayList; 
import java.util.Arrays; 

public class FacebookFragment extends Fragment{ 

    DatabaseHelper myDb; 
    private LoginButton loginButton; 
    private Button getLibrary; 
    private Button getShared; 
    private boolean postingEnabled = false; 

    private static final String PERMISSION = "publish_actions"; 
    private final String PENDING_ACTION_BUNDLE_KEY = 
      "com.example.hellofacebook:PendingAction"; 

    //private Button postStatusUpdateButton; 
    // private Button postPhotoButton; 
    private ImageView profilePicImageView; 
    private TextView greeting; 
    private PendingAction pendingAction = PendingAction.NONE; 
    private boolean canPresentShareDialog; 

    private boolean canPresentShareDialogWithPhotos; 
    private CallbackManager callbackManager; 
    private ProfileTracker profileTracker; 
    private ShareDialog shareDialog; 
    private FacebookCallback<Sharer.Result> shareCallback = new FacebookCallback<Sharer.Result>() { 
     @Override 
     public void onCancel() { 
      Log.d("FacebookFragment", "Canceled"); 
     } 

     @Override 
     public void onError(FacebookException error) { 
      Log.d("FacebookFragment", String.format("Error: %s", error.toString())); 
      String title = getString(R.string.error); 
      String alertMessage = error.getMessage(); 
      showResult(title, alertMessage); 
     } 

     @Override 
     public void onSuccess(Sharer.Result result) { 
      Log.d("FacebookFragment", "Success!"); 
      if (result.getPostId() != null) { 
       String title = getString(R.string.success); 
       String id = result.getPostId(); 
       String alertMessage = getString(R.string.successfully_posted_post, id); 
       showResult(title, alertMessage); 
      } 
     } 

     private void showResult(String title, String alertMessage) { 
      new AlertDialog.Builder(getActivity()) 
        .setTitle(title) 
        .setMessage(alertMessage) 
        .setPositiveButton(R.string.ok, null) 
        .show(); 
     } 
    }; 

    private enum PendingAction { 
     NONE, 
     POST_PHOTO, 
     POST_STATUS_UPDATE 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     myDb = new DatabaseHelper(getActivity()); 
     FacebookSdk.sdkInitialize(getActivity()); 

     // Other app specific specialization 
    } 

    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 

     callbackManager.onActivityResult(requestCode, resultCode, data); 
    } 


    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { 

     View v = inflater.inflate(R.layout.fragment_facebook, parent, false); 
     loginButton = (LoginButton) v.findViewById(R.id.loginButton); 

     // If using in a fragment 
     loginButton.setFragment(this); 
     callbackManager = CallbackManager.Factory.create(); 

     // Callback registration 
     loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { 
      @Override 
      public void onSuccess(LoginResult loginResult) { 

       Toast toast = Toast.makeText(getActivity(), "Logged In", Toast.LENGTH_SHORT); 
       postingEnabled = true; 
    //   postPhotoButton.setVisibility(View.VISIBLE); 
     //   postStatusUpdateButton.setVisibility(View.VISIBLE); 
       getLibrary.setVisibility(View.VISIBLE); 
       getShared.setVisibility(View.VISIBLE); 

       toast.show(); 
       handlePendingAction(); 
       updateUI(); 
      } 

      @Override 
      public void onCancel() { 
       // App code 
       if (pendingAction != PendingAction.NONE) { 
        showAlert(); 
        pendingAction = PendingAction.NONE; 
       } 
       updateUI(); 
      } 

      @Override 
      public void onError(FacebookException exception) { 
       if (pendingAction != PendingAction.NONE 
         && exception instanceof FacebookAuthorizationException) { 
        showAlert(); 
        pendingAction = PendingAction.NONE; 
       } 
       updateUI(); 

      } 

      private void showAlert() { 
       new AlertDialog.Builder(getActivity()) 
         .setTitle(R.string.cancelled) 
         .setMessage(R.string.permission_not_granted) 
         .setPositiveButton(R.string.ok, null) 
         .show(); 
      } 

     }); 
     shareDialog = new ShareDialog(this); 
     shareDialog.registerCallback(
       callbackManager, 
       shareCallback); 

     if (savedInstanceState != null) { 
      String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY); 
      pendingAction = PendingAction.valueOf(name); 
     } 


     profileTracker = new ProfileTracker() { 
      @Override 
      protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) { 
       updateUI(); 
       handlePendingAction(); 
      } 
     }; 


    profilePicImageView = (ImageView) v.findViewById(R.id.profilePicture); 
    greeting = (TextView) v.findViewById(R.id.greeting); 

     //postStatusUpdateButton = (Button) v.findViewById(R.id.postStatusUpdateButton); 
     /*postStatusUpdateButton.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View view) { 
       onClickPostStatusUpdate(); 
      } 
     });*/ 

     /*postPhotoButton = (Button) v.findViewById(R.id.postPhotoButton); 
     postPhotoButton.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View view) { 
       onClickPostPhoto(); 
      } 
     });*/ 

     getLibrary = (Button) v.findViewById(R.id.getLibraryButton); 
     getShared = (Button)v.findViewById(R.id.getSharedButton); 
     getShared.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       startActivity(new Intent(getActivity(), SongPostList.class)); 

      } 
     }); 

     getLibrary.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       startActivity(new Intent(getActivity(), MainActivity.class)); 

      } 
     }); 


     // Can we present the share dialog for regular links? 
     canPresentShareDialog = ShareDialog.canShow(
       ShareLinkContent.class); 

     // Can we present the share dialog for photos? 
     canPresentShareDialogWithPhotos = ShareDialog.canShow(
       SharePhotoContent.class); 


    loginButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      LoginManager.getInstance().logInWithReadPermissions(getActivity(), Arrays.asList("public_profile")); 
      if(!postingEnabled) { 

       postingEnabled = true; 
      //  postPhotoButton.setVisibility(View.VISIBLE); 
      // postStatusUpdateButton.setVisibility(View.VISIBLE); 
       getLibrary.setVisibility(View.VISIBLE); 
       getShared.setVisibility(View.VISIBLE); 
      }else{ 

       postingEnabled = false; 
       // postPhotoButton.setVisibility(View.GONE); 
       //postStatusUpdateButton.setVisibility(View.GONE); 
       getLibrary.setVisibility(View.GONE); 
       getShared.setVisibility(View.GONE); 

      } 

//    GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), 
//      new GraphRequest.GraphJSONObjectCallback() { 
//       @Override 
//       public void onCompleted(
//         JSONObject object, 
//         GraphResponse response) { 
//        if (object != null) { 
//         Log.d("Me Request",object.toString()); 
//         Toast t = Toast.makeText(getActivity(), object.toString(), Toast.LENGTH_SHORT); 
//         t.show(); 
//        } 
// 
//       } 
//      }); 
//    Bundle parameters = new Bundle(); 
//    parameters.putString("fields", "id,name,link,email"); 
//    request.setParameters(parameters); 
//    request.executeAsync(); 
     } 
    }); 


//  loginButton.setOnClickListener(new View.OnClickListener() { 
//   @Override 
//   public void onClick(View v) { 
// 
//    LoginManager.getInstance().logInWithReadPermissions(getActivity(), Arrays.asList("public_profile", "user_friends")); 
// 
// 
// 
//   } 
//  }); 
     return v; 
    } 

    @Override 
    public void onResume() { 
     super.onResume(); 

     // Call the 'activateApp' method to log an app event for use in analytics and advertising 
     // reporting. Do so in the onResume methods of the primary Activities that an app may be 
     // launched into. 
     AppEventsLogger.activateApp(getActivity()); 

     updateUI(); 
    } 

    @Override 
    public void onPause() { 
     super.onPause(); 

     // Call the 'deactivateApp' method to log an app event for use in analytics and advertising 
     // reporting. Do so in the onPause methods of the primary Activities that an app may be 
     // launched into. 
     AppEventsLogger.deactivateApp(getActivity()); 
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     profileTracker.stopTracking(); 
    } 



    private void updateUI() { 
     boolean enableButtons = AccessToken.getCurrentAccessToken() != null; 

     //postStatusUpdateButton.setEnabled(enableButtons || canPresentShareDialog); 
     //postPhotoButton.setEnabled(enableButtons || canPresentShareDialogWithPhotos); 

     Profile profile = Profile.getCurrentProfile(); 
     if (enableButtons && profile != null) { 
      new LoadProfileImage(profilePicImageView).execute(profile.getProfilePictureUri(200, 200).toString()); 
      greeting.setText(getString(R.string.hello_user, profile.getName())); 
      boolean isInserted =myDb.insertData(profile.getId(),profile.getName(),profile.getProfilePictureUri(200,200).toString()); 
      if(isInserted == true){ 
       Toast.makeText(getActivity(),"Data Inserted",Toast.LENGTH_LONG).show(); 

       SharedPreferences settings = getActivity().getSharedPreferences("mysettings", 
         Context.MODE_PRIVATE); 

       SharedPreferences.Editor editor = settings.edit(); 
       editor.putString("uid", profile.getId()); 
       editor.putString("name",profile.getName()); 
       editor.putString("pic",profile.getProfilePictureUri(200,200).toString()); 
       editor.commit(); 
      }else{ 
       Toast.makeText(getActivity(),"Not Inserted",Toast.LENGTH_LONG).show(); 
      } 
      postingEnabled = true; 
      //postPhotoButton.setVisibility(View.VISIBLE); 
      //postStatusUpdateButton.setVisibility(View.VISIBLE); 
      getLibrary.setVisibility(View.VISIBLE); 
      getShared.setVisibility(View.VISIBLE); 
     } else { 
      Bitmap icon = BitmapFactory.decodeResource(getContext().getResources(),R.drawable.user_default); 
      profilePicImageView.setImageBitmap(ImageHelper.getRoundedCornerBitmap(getContext(), icon, 200, 200, 200, false, false, false, false)); 
      greeting.setText(null); 
      postingEnabled = false; 
      // postPhotoButton.setVisibility(View.GONE); 
      //postStatusUpdateButton.setVisibility(View.GONE); 
      getLibrary.setVisibility(View.GONE); 
      getShared.setVisibility(View.GONE); 
     } 
    } 


    @Override 
    public void onSaveInstanceState(Bundle outState) { 
     super.onSaveInstanceState(outState); 

     outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name()); 
    } 

    private void handlePendingAction() { 
     PendingAction previouslyPendingAction = pendingAction; 
     // These actions may re-set pendingAction if they are still pending, but we assume they 
     // will succeed. 
     pendingAction = PendingAction.NONE; 

     switch (previouslyPendingAction) { 
      case NONE: 
       break; 
      case POST_PHOTO: 
       postPhoto(); 
       break; 
      case POST_STATUS_UPDATE: 
       postStatusUpdate(); 
       break; 
     } 
    } 

    private void onClickPostStatusUpdate() { 
     performPublish(PendingAction.POST_STATUS_UPDATE, canPresentShareDialog); 
    } 

    private void postStatusUpdate() { 
     Profile profile = Profile.getCurrentProfile(); 
     ShareLinkContent linkContent = new ShareLinkContent.Builder() 
       .setContentTitle("Integrate Facebook Login to your Android App") 
       .setContentDescription(
         "This app shows how to integrate Facebook Login to your Android App") 
       .setContentUrl(Uri.parse("http://www.androidtutorialpoint.com/material-design/adding-facebook-login-to-android-app/")) 
       .build(); 
     if (canPresentShareDialog) { 
      shareDialog.show(linkContent); 
     } else if (profile != null && hasPublishPermission()) { 
      ShareApi.share(linkContent, shareCallback); 
     } else { 
      pendingAction = PendingAction.POST_STATUS_UPDATE; 
     } 
    } 

    private void onClickPostPhoto() { 
     performPublish(PendingAction.POST_PHOTO, canPresentShareDialogWithPhotos); 
    } 

    private void postPhoto() { 
     Bitmap image = BitmapFactory.decodeResource(this.getResources(), R.drawable.androidlogo); 
     SharePhoto sharePhoto = new SharePhoto.Builder().setBitmap(image).build(); 
     ArrayList<SharePhoto> photos = new ArrayList<>(); 
     photos.add(sharePhoto); 

     SharePhotoContent sharePhotoContent = 
       new SharePhotoContent.Builder().setPhotos(photos).build(); 
     if (canPresentShareDialogWithPhotos) { 
      shareDialog.show(sharePhotoContent); 
     } else if (hasPublishPermission()) { 
      ShareApi.share(sharePhotoContent, shareCallback); 
     } else { 
      pendingAction = PendingAction.POST_PHOTO; 
      // We need to get new permissions, then complete the action when we get called back. 
      LoginManager.getInstance().logInWithPublishPermissions(
        this, 
        Arrays.asList(PERMISSION)); 
     } 
    } 

    private boolean hasPublishPermission() { 
     AccessToken accessToken = AccessToken.getCurrentAccessToken(); 
     return accessToken != null && accessToken.getPermissions().contains("publish_actions"); 
    } 

    private void performPublish(PendingAction action, boolean allowNoToken) { 
     AccessToken accessToken = AccessToken.getCurrentAccessToken(); 
     if (accessToken != null || allowNoToken) { 
      pendingAction = action; 
      handlePendingAction(); 
     } 
    } 

    /** 
    * Background Async task to load user profile picture from url 
    * */ 
    private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> { 
     ImageView bmImage; 

     public LoadProfileImage(ImageView bmImage) { 
      this.bmImage = bmImage; 
     } 

     protected Bitmap doInBackground(String... uri) { 
      String url = uri[0]; 
      Bitmap mIcon11 = null; 
      try { 
       InputStream in = new java.net.URL(url).openStream(); 
       mIcon11 = BitmapFactory.decodeStream(in); 
      } catch (Exception e) { 
       Log.e("Error", e.getMessage()); 
       e.printStackTrace(); 
      } 
      return mIcon11; 
     } 

     protected void onPostExecute(Bitmap result) { 

      if (result != null) { 


       Bitmap resized = Bitmap.createScaledBitmap(result,200,200, true); 
       bmImage.setImageBitmap(ImageHelper.getRoundedCornerBitmap(getContext(),resized,250,200,200, false, false, false, false)); 

      } 
     } 
    } 


} 

請幫忙沒問題,IAM無法弄清楚什麼是錯

回答

0

而不是使用自定義類下載圖像從AsyncTask擴展,您可以使用Picasso加載它。

Uri image = Profile.getCurrentProfile().getProfilePictureUri(200, 200); 
Picasso.with(context).load(image).placeholder(R.drawable.placeholder).into(imageView); 
+0

謝謝,我現在明白了 –