0

I want to wait till i get my user name and my id, and also to wait until I get the user names and users id of my friends in facebook. how can I implement it?

I wrote a code after these two Request however sometimes one Request didn't finish and I get null in one of the variables (for example the userName variable)

therefor I want to wait till these two requests finish.

Or maybe there is another better implementation?

this is my code:

    final CountDownLatch isForFinish = new CountDownLatch(1);

 private class SessionStatusCallback implements Session.StatusCallback {

        @Override
        public void call(Session session, SessionState state, Exception exception) {
            if( session.isOpened() ){

                Request.executeMyFriendsRequestAsync(session, new Request.GraphUserListCallback() {

                    @Override
                    public void onCompleted(List<GraphUser> users, Response response) {


                        for (int i=0;i<users.size();i++){

                            friendsId+= (users.get(i).getId()+",");
                            friendsName+=(users.get(i).getName()+",");

                        }

                        isForFinish.countDown();

                    }
                });


                Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

                    @Override
                    public void onCompleted(GraphUser user, Response response) {

                        String userName = user.getName();
                        String userId = user.getId();


                        Intent i = new Intent(getApplicationContext(), TabMainActivity.class);
                        String email=null;
                        try {
                            email = (String) user.getInnerJSONObject().getString("email");
                        } catch (JSONException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                        if(email!=null){

                            String newemail=new String(email);
                            newemail = email.replace("@", "_");
                            newemail = newemail.replace(".", "_");

                            TelephonyManager mTelephonyMgr;    
                             mTelephonyMgr = (TelephonyManager) getSystemService  
                               (Context.TELEPHONY_SERVICE);     

                             String phoneNumber = mTelephonyMgr.getLine1Number();  

                            String password = "facebook";

                            ParseUser Puser = new ParseUser();
                            Puser.setUsername(userId);
                            Puser.setPassword("facebook");
                            Puser.setEmail(email);
                            Puser.put("Name", userName);

                            try {
                                isForFinish.await();
                            } catch (InterruptedException e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                            }
                            Puser.put("friendsId",friendsId );
                            Puser.put("friendsName",friendsName );

                            try {
                                Puser.signUp();
                                ParseObject saleObj =new ParseObject("sale_"+idOfUser);
                                saleObj.saveInBackground();
                                ParseObject deliverObj =new ParseObject("deliver_"+idOfUser);
                                deliverObj.saveInBackground();
                                ParseObject group =new ParseObject("group_"+idOfUser);
                                group.saveInBackground();
                                ParseObject freind =new ParseObject("freind"+idOfUser);
                                freind.saveInBackground();
                            } catch (ParseException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }


                            i.putExtra("friendsId", friendsId);
                            i.putExtra("emailOwner", newemail);
                            i.putExtra("phone", phoneNumber);
                            i.putExtra("email",email  );
                            i.putExtra("password",password  );
                            i.putExtra("id",userId  );
                            i.putExtra("name",userName  );

                            startActivity(i);

                        }
                    }
                });
            }
Cœur
  • 37,241
  • 25
  • 195
  • 267
Adir Rahamim
  • 453
  • 1
  • 12
  • 31

2 Answers2

0

For dependent threads, you can use a countdown latch : http://developer.android.com/reference/java/util/concurrent/CountDownLatch.html

Here is an example:

http://www.javacodegeeks.com/2011/09/java-concurrency-tutorial.html

Ankur Aggarwal
  • 2,210
  • 2
  • 34
  • 39
  • hi, thanks for answer, in these link there are examples in threads however here i have a AsyncTask...i didnt understand how can i implement it here? can you please give me an example? thanks alot – Adir Rahamim Mar 18 '13 at 11:44
  • I've always used countdownLatch with threads. But I did try something similar to this: http://stackoverflow.com/questions/9774792/asynctask-onpostexecute-not-called-in-unit-test-case Give it a go – Ankur Aggarwal Mar 18 '13 at 11:49
  • hi, in the link http://stackoverflow.com/questions/9774792/asynctask-onpostexecute-not-called-in-unit-test-case the example is for thread and i am not sure it will work with AsyncTask? also, how can i know how much time do i need to count down? – Adir Rahamim Mar 18 '13 at 12:02
  • Async task also works on threads. You can have a run method there and can use an await() method in AsyncTask as well. The coutdownLatch does not count down time, rather, it waits for the number of "countdown()" calls specified in the constructor. So, it essentially waits for the number of threads to complete – Ankur Aggarwal Mar 18 '13 at 15:25
  • i added my new code with coutdown, however several times the second Request doesnt wait to the for in the first request to be finish...what is the problem with my new code? – Adir Rahamim Mar 18 '13 at 16:25
  • and sometimes its stuck and doesnt even start the activity..do you know why?(not all times) and after some seconds that the app doesnt respont it show a popup that the app doesnt react do you want to wait or close the app? here is the logcat : 03-18 16:40:45.062: I/dalvikvm(886): threadid=3: reacting to signal 3 03-18 16:40:45.142: I/dalvikvm(886): Wrote stack traces to '/data/anr/traces.txt' – Adir Rahamim Mar 18 '13 at 16:39
0

Using Android Facebook 3.0 setup the Fragment to manage the states using this tutorial

https://developers.facebook.com/docs/tutorials/androidsdk/3.0/scrumptious/authenticate/

You can use the prebuilt facebook login button to also login using the xml

<com.facebook.widget.LoginButton
    android:id="@+id/authButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="51dp" />

Then either using the Session StatusCallback

https://developers.facebook.com/docs/reference/android/3.0/Session.StatusCallback or the overrides you created in the fragment in the previous tutorial you can initiate a call to retrieve your friends which would look like this

void getFriendsWithApp(final Intent intent){
       final ProgressDialog mDialog = new ProgressDialog(this);
       mDialog.setMessage("Loading...");
       mDialog.setCancelable(false);
       mDialog.show();
       String fqlQuery = "SELECT uid, name, pic_square FROM user WHERE uid IN " +
              "(SELECT uid2 FROM friend WHERE uid1 = me())";
        Bundle params = new Bundle();
        params.putString("q", fqlQuery);
        Session session = Session.getActiveSession();
        Request request = new Request(session,
            "/fql",                         
            params,                         
            HttpMethod.GET,                 
            new Request.Callback(){         
                public void onCompleted(Response response) {
                    try {
                        mDialog.dismiss();
                        Type listType = new TypeToken<ArrayList<Friend>>(){}.getType();
                        Utils.friends = new Gson().fromJson(response.getGraphObject().getInnerJSONObject().getJSONArray("data").toString(), listType);
                        startActivity(intent);
//This is where you would do what you want after you retrieve your json with friends
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }                  
        }); 
      Request.executeBatchAsync(request);          
}
Darussian
  • 1,573
  • 1
  • 16
  • 28
  • thanks alot for answer!! however i didnt understand some points: 1. how can i get my user name and my id? 2. how can i get the id of my freinds? thanks alot again :) – Adir Rahamim Mar 18 '13 at 12:45
  • Your friends Id and name are in the json from on the completed response. I bind the json to a premade class using GSon https://code.google.com/p/google-gson/ – Darussian Mar 18 '13 at 12:55
  • You can get your userId and name from using the answer from http://stackoverflow.com/questions/15127783/facebook-sdk-3-0-get-facebook-user-id-and-access-token – Darussian Mar 18 '13 at 12:56
  • thanks, in the answer here: http://stackoverflow.com/questions/15127783/facebook-sdk-3-0-get-facebook-user-id-and-access-token there is a Graphuser in the onComplete method, however in your code there is no a GraphUser object? and also, in this link there is no answer of how get the freinds id? – Adir Rahamim Mar 18 '13 at 13:02
  • They are two different calls, one is a FQL query which is facebooks querying language. The answer i linked wraps the query for you in a nice callback – Darussian Mar 18 '13 at 13:06
  • So if i want to query the freinds id and my user name and my id, i need to use the code that i posted in the main thread and the problem is still alive, not? so, how does your code help me to solve my problem? thanks – Adir Rahamim Mar 18 '13 at 13:10
  • hi, maybe i didnt understand you? i will be glad for clarification? thanks alot – Adir Rahamim Mar 18 '13 at 13:26