18 Eylül 2012 Salı

Facebook Android TestUygulaması Hazırlanması


“TestUygulaması”
Daha önceki makalemde facebook account bilgilerinin alınması için gerekli kayıt işlemlerin nasıl gerçekleşeceğini anlatmıştık.
Şimdi gelin örnek bir uygulama ile facebook android sdk ve graph api aracılığı ile bilgilerin projemize nasıl aktarıldığına ve başkaların duvarlarında nasıl paylaşım yapabileceğimize bir göz atalım.

Temel Özellikler ;

q  Profil Bilgilerine Erişme
q  Arkadaşlarımın Listesi
q  Mesajı Duvarıma Yaz
q  Arkadaşımın Duvarına Yaz
q  Resim Yükle
TetsUygulamasının  görünümü ve çalışma şekli:


  1. Login olan kullanıcının bilgilerinin alındığı bölüm.
  2. Login olan kullanıcının arkadaş listesinin alındığı bölüm.
  3. Duvara yazılacak mesajın girildiği bölüm.
  4. Mesajın duvara yazılması için gerekli bölüm.
  5. Login olan kullanıcının duvarına mesaj yazılacak arkadaşının facebook idsi
  6. Arkadaşının duvarına yazılacak bölüm.
  7. Login olan kullanıcının duvarına resim yükleme


Button ve TextView'leri tanımlayarak başlayalım

  /** Deneme yapmadan önce uygulama kimliğini değiştirin**/
    Facebook facebook = new Facebook("396574887041318");
 
    TextView uemail;
    TextView ugender;
    TextView ufbid;
    TextView uname;
    TextView flist;
    TextView imgupload;
    Button bgetuserinfo;
    Button bfriendsinfo;
    Button bpostmessage;
    Button bpostfriend;
    Button buploadphoto;
   
    private ProgressDialog progressDialog;
    ImageView user_picture;
    private AsyncFacebookRunner mAsyncRunner;

OnCreate altında buton ve text leri View’larla birleştirelim
        uname = (TextView) this.findViewById(R.id.username);
        ugender =(TextView) this.findViewById(R.id.usergender);
        ufbid = (TextView) this.findViewById(R.id.fbid);
        uemail = (TextView) this.findViewById(R.id.useremail);
        flist = (TextView) this.findViewById(R.id.friendslist);
        imgupload=(TextView) this.findViewById(R.id.img_upload);
        bgetuserinfo = (Button) this.findViewById(R.id.getuserinfo);
        bfriendsinfo = (Button) this.findViewById(R.id.bfriends);
        bpostmessage = (Button) this.findViewById(R.id.post_message);
        bpostfriend = (Button) this.findViewById(R.id.post_friend);
        buploadphoto = (Button) this.findViewById(R.id.photo_upload);
       
        user_picture=(ImageView)findViewById(R.id.user_picture);

Bu kısıma çok dikkat ediyoruz.Facebook ile kuracağımız bağlantıda kullanıcı adına yapabileceklerimizi belirleyen bölüm burasıdır.


                 
        facebook.authorize(this, new String[] {"offline_access", "user_interests", "friends_interests","publish_stream","email"},

        mAsyncRunner = new AsyncFacebookRunner(facebook);


users_about_me

Uygulama İzin Ekranı : Profil bilgilerime erişme
Alınan Yetkiler : Bu izin ile kullanıcının hakkımda bölümünde yazan bilgilere erişebilirsiniz.

offline_access

Uygulama İzin Ekranı : Verilerime İstediği Zaman Erişime
Alınan Yetkiler : Bu izin ile kullanıcı bilgilerine istediğimiz zaman erişebiliyoruz.(Online olmasalar bile!)

publish_stream

Uygulama İzin Ekranı : Duvarıma Yazma
Alınan Yetkiler : Bu izni istediğimizde , kullanıcının duvarında içerik paylaşma yetkisini almış oluruz.

e-mail

Uygulama İzin Ekranı : Bana e-posta gönderme
Alınan Yetkiler : Bu izin ile kullanıcının e-mail adresine erişmiş oluruz.



İzinler ve yetkilendirmeler hakkında daha fazla bilgiyi
adresinden alabilir siniz.

1 – Kullanıcı Bilgileri Alma
bgetuserinfo.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
            progressDialog = ProgressDialog.show(TestUygulama.this, "", "bilgiler alınıyor!", true, false);     
              getUserinfo();
           
            }
 });

//Kullanını profil bilglerinin facebooktan alınması
private void getUserinfo(){

        try
        {
              
            JSONObject json = Util.parseJson(facebook.request("me"));
                    
            final String id = json.getString("id");
            final String name = json.getString("name");
            final String email =json.getString("email");
            final String gender  =json.getString("gender");
            Log.w("my info", name);
            uname.setText(name);
            ugender.setText(gender);
            ufbid.setText(id);
            uemail.setText(email);
           
            //profil resminin alınıp yüklenmesi
            URL img_value = null;
            img_value = new URL("http://graph.facebook.com/"+id+"/picture?type=large");
            Bitmap mIcon1 = BitmapFactory.decodeStream(img_value.openConnection().getInputStream());
            user_picture.setImageBitmap(mIcon1);

           
            progressDialog.dismiss();
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (FacebookError e)
        {
            e.printStackTrace();
        }

   
       
    }

Kullanıcı bilgilerin alınması


2- Kullanıcı Arkadaş Listesinin Alınması

bfriendsinfo.setOnClickListener(new OnClickListener(){
             public void onClick(View v){
                    progressDialog = ProgressDialog.show(TestUygulama.this, "", "bilgiler alınıyor!", true, false);
                    getFriends();
             }
        });

//Kullanıcı arkadaş listesinin alınması işlemini gerçekleştirir.
    private void getFriends(){
       String returnString = null;
        JSONObject json_data = null;

        try
        {
            JSONObject response = Util.parseJson(facebook.request("me/friends"));
            JSONArray jArray = response.getJSONArray("data");

            json_data = jArray.getJSONObject(0);
   
           
           
          
            for(int i=0;i<jArray.length();i++){
                   
                    Log.i("log_tag","User Name: "+json_data.getString("name")+
                            ", user_id: "+json_data.getString("id"));

                            returnString += "\n\t" + jArray.getJSONObject(i);

            };
           
      
            flist.setText(returnString);
            progressDialog.dismiss();
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (FacebookError e)
        {
            e.printStackTrace();
        }
      
    }
Arkadaş listesinin alınması
4-Duvarada Yazı Yayınlamak
        bpostfriend.setOnClickListener(new OnClickListener(){
             public void onClick(View v){
                    friend_post_message();
             }
        });
//Kendi duvarına yazma
    private void Userpost_message(){
      
      
       try {
    TextView post_edit = (TextView)findViewById(R.id.write_message);
    String message = String.valueOf(post_edit.getText());
    Bundle parameters = new Bundle();
    parameters.putString("message", message);
    facebook.request("me/feed", parameters, "POST");
       } catch (Exception e) {
          e.printStackTrace();
       }



    }

3 nolu alanda yazdığımız yazı facebook duvarımızda yayınlanacaktır.
facebook duvarımda TestUygulaması ile paylaşım
6-Arkadaşlarımın DuvarındaYazı Paylaşmak
        bpostfriend.setOnClickListener(new OnClickListener(){
             public void onClick(View v){
                    friend_post_message();
             }
        });
   //Arkadaşımın duvarına yazma
    private void friend_post_message(){
      

    TextView post_edit = (TextView)findViewById(R.id.write_message);
    TextView friend_id = (TextView)findViewById(R.id.friend_id);
   
    String friend_post = String.valueOf(friend_id.getText());
    String message = String.valueOf(post_edit.getText());
    postOnFriendsWall(message, friend_post, "Test yapıyoruz");
  

    }
    public void postOnFriendsWall(String msg, String toID, String description) {
        try {
         
                String response = facebook.request(toID);
                Bundle parameters = new Bundle();
                parameters.putString("message", msg);
                parameters.putString("description", description);
                response = facebook.request(toID+"/feed", parameters, "POST");
                Log.d("FACEBOOK RESPONSE",response);
                if (response == null || response.equals("") ||
                        response.equals("false")) {
                    Log.v("Error", "Blank response");
                }

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


5 nolu alanda yazdığımız yazı arkadaşımızın duvarında yayınlanacak.

7-Resim Yükleme
        //Duvara resim yükleme
        buploadphoto.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Bundle params = new Bundle();
                params.putString("method", "photos.upload");

                URL uploadFileUrl = null;
                try {
                    uploadFileUrl = new URL(
                        "http://www.facebook.com/images/devsite/iphone_connect_btn.jpg");
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                try {
                    HttpURLConnection conn= (HttpURLConnection)uploadFileUrl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    int length = conn.getContentLength();

                    byte[] imgData =new byte[length];
                    InputStream is = conn.getInputStream();
                    is.read(imgData);
                    params.putByteArray("picture", imgData);

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

                mAsyncRunner.request(null, params, "POST",
                        new SampleUploadListener(), null);
            }
        });

http://www.facebook.com/images/devsite/iphone_connect_btn.jpggöndereceğiniz resim buraya ekleyelim.

TestUygulaması Kodları(Tamamı):
public class TestUygulama extends Activity {
    /** Deneme yapmadan önce uygulama kimliğini değiştirin**/
    Facebook facebook = new Facebook("396574887041318");
 
    TextView uemail;
    TextView ugender;
    TextView ufbid;
    TextView uname;
    TextView flist;
    TextView imgupload;
    Button bgetuserinfo;
    Button bfriendsinfo;
    Button bpostmessage;
    Button bpostfriend;
    Button buploadphoto;
   
    private ProgressDialog progressDialog;
    ImageView user_picture;
    private AsyncFacebookRunner mAsyncRunner;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

   
       
        uname = (TextView) this.findViewById(R.id.username);
        ugender =(TextView) this.findViewById(R.id.usergender);
        ufbid = (TextView) this.findViewById(R.id.fbid);
        uemail = (TextView) this.findViewById(R.id.useremail);
        flist = (TextView) this.findViewById(R.id.friendslist);
        imgupload=(TextView) this.findViewById(R.id.img_upload);
        bgetuserinfo = (Button) this.findViewById(R.id.getuserinfo);
        bfriendsinfo = (Button) this.findViewById(R.id.bfriends);
        bpostmessage = (Button) this.findViewById(R.id.post_message);
        bpostfriend = (Button) this.findViewById(R.id.post_friend);
        buploadphoto = (Button) this.findViewById(R.id.photo_upload);
       
        user_picture=(ImageView)findViewById(R.id.user_picture);

               
        facebook.authorize(this, new String[] {"offline_access", "user_interests", "friends_interests","publish_stream","email"},

             new DialogListener() {
            public void onComplete(Bundle values) {
              Log.w("Test","Facebaglandi");
        
            }

            public void onFacebookError(FacebookError error) {}

            public void onError(DialogError e) {
           
            Log.w("Test","FaceError");
               
           
            }

            public void onCancel() {}
        });
       
       mAsyncRunner = new AsyncFacebookRunner(facebook);
      
        bgetuserinfo.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            progressDialog = ProgressDialog.show(TestUygulama.this, "", "bilgiler alınıyor!", true, false);     
              getUserinfo();
           
            }
        });
        bfriendsinfo.setOnClickListener(new OnClickListener(){
             public void onClick(View v){
                    progressDialog = ProgressDialog.show(TestUygulama.this, "", "bilgiler alınıyor!", true, false);
                    getFriends();
             }
        });
        bpostmessage.setOnClickListener(new OnClickListener(){
             public void onClick(View v){
                    Userpost_message();
             }
        });
        bpostfriend.setOnClickListener(new OnClickListener(){
             public void onClick(View v){
                    friend_post_message();
             }
        });
        //Duvara resim yükleme
        buploadphoto.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Bundle params = new Bundle();
                params.putString("method", "photos.upload");

                URL uploadFileUrl = null;
                try {
                    uploadFileUrl = new URL(
                        "http://www.facebook.com/images/devsite/iphone_connect_btn.jpg");
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                try {
                    HttpURLConnection conn= (HttpURLConnection)uploadFileUrl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    int length = conn.getContentLength();

                    byte[] imgData =new byte[length];
                    InputStream is = conn.getInputStream();
                    is.read(imgData);
                    params.putByteArray("picture", imgData);

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

                mAsyncRunner.request(null, params, "POST",
                        new SampleUploadListener(), null);
            }
        });
       
       
    }
   
    public class SampleUploadListener extends BaseRequestListener {

        public void onComplete(final String response, final Object state) {
            try {
                Log.d("Facebook-Example", "Response: " + response.toString());
                JSONObject json = Util.parseJson(response);
                final String src = json.getString("src");

                TestUygulama.this.runOnUiThread(new Runnable() {
                    public void run() {
                           imgupload.setText("Hello there, photo has been uploaded at \n" + src);
                    }
                });
            } catch (JSONException e) {
                Log.w("Facebook-Example", "JSON Error in response");
            } catch (FacebookError e) {
                Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
            }
        }
    }
    //Arkadaşımın duvarına yazma
    private void friend_post_message(){
      

    TextView post_edit = (TextView)findViewById(R.id.write_message);
    TextView friend_id = (TextView)findViewById(R.id.friend_id);
   
    String friend_post = String.valueOf(friend_id.getText());
    String message = String.valueOf(post_edit.getText());
    postOnFriendsWall(message, friend_post, "Test yapıyoruz");
  

    }
   
    public void postOnFriendsWall(String msg, String toID, String description) {
        try {
         
                String response = facebook.request(toID);
                Bundle parameters = new Bundle();
                parameters.putString("message", msg);
                parameters.putString("description", description);
                response = facebook.request(toID+"/feed", parameters, "POST");
                Log.d("FACEBOOK RESPONSE",response);
                if (response == null || response.equals("") ||
                        response.equals("false")) {
                    Log.v("Error", "Blank response");
                }

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

    //Kendi duvarına yazma
    private void Userpost_message(){
      
      
       try {
    TextView post_edit = (TextView)findViewById(R.id.write_message);
    String message = String.valueOf(post_edit.getText());
    Bundle parameters = new Bundle();
    parameters.putString("message", message);
    facebook.request("me/feed", parameters, "POST");
       } catch (Exception e) {
          e.printStackTrace();
       }



    }
    //Kullanını profil bilglerinin facebooktan alınması
    private void getUserinfo(){

        try
        {
              
            JSONObject json = Util.parseJson(facebook.request("me"));
                    
            final String id = json.getString("id");
            final String name = json.getString("name");
            final String email =json.getString("email");
            final String gender  =json.getString("gender");
            Log.w("my info", name);
            uname.setText(name);
            ugender.setText(gender);
            ufbid.setText(id);
            uemail.setText(email);
           
            //profil resminin alınıp yüklenmesi
            URL img_value = null;
            img_value = new URL("http://graph.facebook.com/"+id+"/picture?type=large");
            Bitmap mIcon1 = BitmapFactory.decodeStream(img_value.openConnection().getInputStream());
            user_picture.setImageBitmap(mIcon1);

           
            progressDialog.dismiss();
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (FacebookError e)
        {
            e.printStackTrace();
        }

   
       
    }

    //Kullanıcı arkadaş listesinin alınması işlemini gerçekleştirir.
    private void getFriends(){
       String returnString = null;
        JSONObject json_data = null;

        try
        {
            JSONObject response = Util.parseJson(facebook.request("me/friends"));
            JSONArray jArray = response.getJSONArray("data");

            json_data = jArray.getJSONObject(0);
   
           
           
          
            for(int i=0;i<jArray.length();i++){
                   
                    Log.i("log_tag","User Name: "+json_data.getString("name")+
                            ", user_id: "+json_data.getString("id"));

                            returnString += "\n\t" + jArray.getJSONObject(i);

            };
           
      
            flist.setText(returnString);
            progressDialog.dismiss();
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (FacebookError e)
        {
            e.printStackTrace();
        }
      
    }


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

        facebook.authorizeCallback(requestCode, resultCode, data);
    }
   
    public abstract class BaseRequestListener implements RequestListener {

        public void onFacebookError(FacebookError e, final Object state) {
            Log.e("Facebook", e.getMessage());
            e.printStackTrace();
        }

        public void onFileNotFoundException(FileNotFoundException e,
                                            final Object state) {
            Log.e("Facebook", e.getMessage());
            e.printStackTrace();
        }

        public void onIOException(IOException e, final Object state) {
            Log.e("Facebook", e.getMessage());
            e.printStackTrace();
        }

        public void onMalformedURLException(MalformedURLException e,
                                            final Object state) {
            Log.e("Facebook", e.getMessage());
            e.printStackTrace();
        }
       
    }


}










3 yorum:

  1. merablar.
    öncelikle telefonumdan facebook uygulamasını silince hiçbir tepki alamadım. bu örneğin çalışması için facebook uygulamasının yüklümü olması gerek. ikincisi login oluyor ama (facebook un kendi uygulaması yüklüyken) profil bilgilerini çekerken donuyor. proje dosyalarını tamamen paylaşmanız mümkün mü acaba... teşekkürler

    YanıtlaSil
  2. Merhaba
    Facebook Android api ' de yapmış olduğu değişikliklerden dolayı, profil bilgileri alınma yöntemleri tamamen değişti.Çok yakında bununla ilgili yeni bir örnek hazırlamaya düşünüyorum.

    YanıtlaSil
  3. merhaba ,
    Yeni yöntem hakkında bilgi verebilir misiniz

    YanıtlaSil