使用facebook sdk登录共享首选项并获取有关用户的信息

时间:2016-11-28 08:22:47

标签: android facebook facebook-sdk-4.0

我正在开发一个Facebook登录的应用程序。我正在尝试获取用户信息并将其发送到我的server.i我正在使用sdk 4.我正在尝试使用共享首选项来保存信息,但我不知道共享首选项。这是我的facebook登录活动。这是发射器活动。

>>User.select("subitem -> 'item1' AS subitem1", "subitem->'item2' AS subitem2").map(&:attributes)

}

3 个答案:

答案 0 :(得分:1)

  

Android SharedPreferences允许我们存储私有原语   应用程序数据以键值对的形式。有关详细信息,请参阅this

要从共享偏好中读取,请使用类似的内容。

String dateFromSharedPreferences=getActivity().getPreferences(Context.MODE_PRIVATE);
sharedPref.getString("Username");

保存为共享偏好

    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString("Username", YourUsername);
    editor.putString("Password", YourPassword);
    editor.apply();

您正在将值从LoginActivity传递到MainActivity,因此MainActivityonCreate的代码功能如下所示,以便在textview中显示传递的值。

((TextView)findViewById(R.id.tv1)).setText(getIntent().getExtras().getString("full_name"));
((TextView)findViewById(R.id.tv2)).setText(getIntent().getExtras().getString("email_id"));
((TextView)findViewById(R.id.tv3)).setText(getIntent().getExtras().getString("gender"));

答案 1 :(得分:0)

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.Timer;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Administrator
 */
public class NewJFrame extends javax.swing.JFrame {


    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();
    }
    int b[];
    Timer timer;
    int n;
    javax.swing.JLabel []a;
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jButton1 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton2.setText("Create");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jScrollPane1.setViewportView(jList1);

        jButton1.setText("Insert Code");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton3.setText("Set min to index 0");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Start");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jScrollPane2.setViewportView(jList2);

        jTextField1.setText("10");

        jLabel1.setText("Amount:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addGap(20, 20, 20)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 69, Short.MAX_VALUE)
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton4))
                    .addComponent(jScrollPane2))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 314, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(20, 20, 20))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(62, 62, 62))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 254, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton3)
                    .addComponent(jButton4)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(74, 74, 74))
        );

        pack();
    }// </editor-fold>                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        n=Integer.parseInt(jTextField1.getText());
        b=new int[n];
        a= new javax.swing.JLabel[n];
        int x=5, y=40;
        for (int i=0; i< n; i++)
        {
            int random = (int )(Math.random()*20 + 1);
            b[i]=random;
            a[i]= new javax.swing.JLabel();
            a[i].setText(random+ "");
            a[i].setSize(20, 30);
            x=x +20;
            a[i].setBorder( BorderFactory.createRaisedBevelBorder());
            a[i].setLocation(x, y);
 //           setLayout(new java.awt.GridBagLayout());
            add(a[i], new java.awt.GridBagConstraints());
            a[i].setVisible(true);

        }
        this.repaint();
        jButton2.setVisible(false);
    }                                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        jList1.setListData(new String [0]);
        String[] strings = { "int min, i, j,temp;", "for(i = 0; i < n-1; i++){", "   min = i;", "   for(j = i+1; j < n; j++)", "         if(a[j] < a[min])","           min = j;","    if(min != i){","       temp=a[i];","       a[i]=a[j];","       a[j]=temp;","    }","}" };
        jList1.setListData(strings);

    }                                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        int min=b[0],x=0,temp1;
        for (int i=1;i<n;i++){
            if (b[i]<min) min=b[i];
        }
        for (int i=0;i<n;i++){
            if (b[i]==min) x=i;
        }
        temp1=b[x];
        b[x]=b[0];
        b[0]=temp1;
        a[x].setText(b[x]+"");
        a[0].setText(b[0]+"");
        jButton3.setVisible(false);
        DefaultListModel s=new DefaultListModel();
        s.addElement("Selection sort: - Set the smallest element in first index!");
        jList2.setModel(s);
    }                                        

    ActionListener al=new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

//    timer = new Timer(10, al);
//    timer.start();     
//    for (int k=0;k<10;k++){
//        a[k].setText(b[k]+ "");
//    }
        }
    };


    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        int min,temp2, i, j; //min là chỉ số phần tử nhỏ nhất
             for(i = 1; i < n-1; i++)
             {
                   min = i;
                   for(j = i+1; j < n; j++){
                      if(b[j] < b[min])
                         min = j; //tìm min trong các phần tử còn lại
                   }
                       temp2=b[i];
                       b[i]=b[min];
                       b[min]=temp2;
                       a[min].setText(b[min]+"");
                       a[i].setText(b[i]+"");
                      //đổi chỗ nếu tìm thấy min
             }
        a[0].setBorder(BorderFactory.createLoweredBevelBorder());
        //jButton4.addActionListener(al);

    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) throws InterruptedException {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });

    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JList jList1;
    private javax.swing.JList jList2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                   
}

在转向意图之前编写此代码。

SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;

答案 2 :(得分:0)

我知道这类问题有很多答案,但我仍然给出了这个问题的答案,我希望有人能得到帮助。如果我们创建处理所有数据的方法,这很容易。 当收到facebook JSON对象后,请执行以下操作。

try {
        Bundle bFacebookData = getFacebookData(object);
        progressDialog.dismiss();
        progressDialog.cancel();
        setSessionData(bFacebookData);

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

//在这里,您可以获取所有Facebook数据并以捆绑存储

private Bundle getFacebookData(JSONObject object)
    {
        try {
            Bundle bundle = new Bundle();
            //String id = object.getString("id");

            try
            {
                URL profile_pic = new URL("https://graph.facebook.com/" + object.getString("id") + "/picture?width=200&height=150");
                Log.i("profile_pic", profile_pic + "");
                if (profile_pic.toString() != null)
                {
                    bundle.putString("profile_pic", profile_pic.toString());
                }
                else
                {
                    bundle.putString("profile_pic", "noProfilePic");
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
                return null;
            }

            if (object.has("id"))
            {
                if (object.getString("id") != null)
                {
                    bundle.putString("userId", object.getString("id"));
                    Log.i(TAG, "Info " + object.getString("id"));
                }
                else
                {
                    bundle.putString("userId", "noUserId");
                    Log.i(TAG, "Info " + object.getString("id"));
                }
            }
            if (object.has("first_name"))
            {
                if (object.getString("first_name") != null)
                {
                    bundle.putString("first_name", object.getString("first_name"));
                    Log.i(TAG + "Info", object.getString("first_name"));
                }
                else
                {
                    bundle.putString("first_name", "noFirstName");
                    Log.i(TAG + "Info", object.getString("first_name"));
                }
            }
            if (object.has("last_name"))
            {
                if (object.getString("last_name") != null)
                {
                    bundle.putString("last_name", object.getString("last_name"));
                    Log.i(TAG + "Info", object.getString("last_name"));
                }
                else
                {
                    bundle.putString("last_name", "noLastName");
                    Log.i(TAG + "Info", object.getString("last_name"));
                }
            }

            if (object.has("email"))
            {
                if (object.getString("email") != null)
                {
                    bundle.putString("email", object.getString("email"));
                    Log.i(TAG + "Info", object.getString("email"));
                }
                else
                {
                    bundle.putString("email", "noEmail");
                    Log.i(TAG + "Info", object.getString("email"));
                }
            }


            //this is added dynamically
            bundle.putString("phone", "noPhone");

            if (object.has("gender"))
            {
                if (object.getString("gender") != null)
                {
                    bundle.putString("gender", object.getString("gender"));
                    Log.i(TAG + "Info", object.getString("gender"));
                }
                else
                {
                    bundle.putString("gender", "noGender");
                    Log.i(TAG + "Info", object.getString("gender"));
                }
            }

            if (object.has("birthday"))
            {
                if (object.getString("birthday") != null)
                {
                    bundle.putString("birthday", object.getString("birthday"));
                    Log.i(TAG + "Info", object.getString("birthday"));
                }
                else
                {
                    bundle.putString("birthday", "noDateOfBirth");
                    Log.i(TAG + "Info", object.getString("birthday"));
                }
            }

            if (object.has("location"))
            {
                if (object.getJSONObject("location").getString("name") != null)
                {
                    bundle.putString("location", object.getJSONObject("location").getString("name"));
                    Log.i(TAG + "Info", object.getJSONObject("location").getString("name"));
                }
                else
                {
                    bundle.putString("location", "noLocation");
                    Log.i(TAG + "Info", object.getJSONObject("location").getString("name"));
                }
            }

            return bundle;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return null;
    }

//在这里,您可以将数据存储在SharedPreferences中并开始新活动

String userId = "", userEmail = "", userFirstName = "", userLastName = "",
            userPhone = "", dateOfBirth = "", gender = "", profilePic = "";

    private void setSessionData(Bundle bundle)
    {
        try
        {
            userId = bundle.getString("userId");
            userEmail = bundle.getString("email");
            userFirstName = bundle.getString("first_name");
            userLastName =  bundle.getString("last_name");
            userPhone = bundle.getString("phone");
            dateOfBirth =  bundle.getString("birthday");
            gender =  bundle.getString("gender");
            profilePic =  bundle.getString("profile_pic");

            if (userId !=null)
            {

                SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("pref", MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();

                editor.putString("userId", userId);
                editor.putString("email", userEmail);
                editor.putString("first_name", userFirstName);
                editor.putString("last_name", userLastName);
                editor.putString("phone", userPhone);
                editor.putString("birthday", dateOfBirth);
                editor.putString("gender", gender);
                editor.putString("profile_pic", profilePic);

                editor.apply();


                Intent i = new Intent(activity, MainActivity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                activity.startActivity(i);
            }
            else
            {
                //"Some thing went wrong Please try again"
            }
        }
        catch (Exception e)
        {
            e.printStackTrach();
        }
    }

您从SharePreferences

接收数据的另一个班级
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("pref", MODE_PRIVATE);

((TextView)findViewById(R.id.tv1)).setText(sharedPreferences.getString("first_name", ""));
((TextView)findViewById(R.id.tv2)).setText(sharedPreferences.getString("last_name", ""));