Facebook feedDailog不使用Asynctask

时间:2012-12-27 14:16:03

标签: android facebook android-asynctask

在我的Android应用程序中,我打开了facebook提要对话框,因为加载需要时间我尝试在提示对话框启动之前实现进度对话框,在oncreate()中我打开了progressdialog但它是没有在这里工作对话框是打开但没有进度对话框,然后我试图放入AsyncTask,现在我可以看到progressDialog但fb feeddialog没有显示..下面是我的代码

public class ShareOnFacebook extends Activity {
    private String TAG = ShareOnFacebook.class.getSimpleName();
    private static final String APP_ID = "130985523722347";
    private static final String[] PERMISSIONS = new String[] { "publish_stream" };

    private static final String TOKEN = "access_token";
    private static final String EXPIRES = "expires_in";
    private static final String KEY = "facebook-credentials";

     private ProgressDialog pd = null;
     private Object data = null;

    private Facebook facebook;
    private String messageToPost;
    private ProgressDialog dialogFBMessage;
    public boolean saveCredentials(Facebook facebook) {
        Editor editor = getApplicationContext().getSharedPreferences(KEY,
                Context.MODE_PRIVATE).edit();
        editor.putString(TOKEN, facebook.getAccessToken());
        editor.putLong(EXPIRES, facebook.getAccessExpires());
        return editor.commit();
    }

    public boolean restoreCredentials(Facebook facebook) {
        SharedPreferences sharedPreferences = getApplicationContext()
                .getSharedPreferences(KEY, Context.MODE_PRIVATE);
        facebook.setAccessToken(sharedPreferences.getString(TOKEN, null));
        facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0));
        return facebook.isSessionValid();
    }

    @TargetApi(9)
    @SuppressLint({ "NewApi", "NewApi", "NewApi" })
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

         //this.pd = ProgressDialog.show(this, "Working..", "Downloading Data...", true, false);


        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        dialogFBMessage = new ProgressDialog(this);
        dialogFBMessage.setCanceledOnTouchOutside(false);
        dialogFBMessage.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialogFBMessage.setMessage("Please Wait.............. ");
        dialogFBMessage.show();
        Log.d(TAG, "FBMessage Loading Step 01");
        facebook = new Facebook(APP_ID);
        restoreCredentials(facebook);

        requestWindowFeature(Window.FEATURE_NO_TITLE);

        // setContentView(R.layout.facebookdialog);
        //Looper.prepare();
        //new MyFetchTask().execute();
        //Looper.loop(); 



    String facebookMessage = getIntent().getStringExtra("facebookMessage");
    if (facebookMessage == null) {
        facebookMessage = "Post From My Neighborhood "
                + new java.util.Date().getTime();
    }
    messageToPost = facebookMessage;
    if (!facebook.isSessionValid()) {
        loginAndPostToWall();
    } else {
        try {
            postToWall(messageToPost);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }}
    public void loginAndPostToWall() {
        facebook.authorize(ShareOnFacebook.this, PERMISSIONS,
                Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());
    }





    /* public class MyFetchTask extends AsyncTask<Object, Object, Object>
    {

        @Override
        protected Object doInBackground(Object... params) {
            // TODO Auto-generated method stub

            String facebookMessage = getIntent().getStringExtra("facebookMessage");
            if (facebookMessage == null) {
                facebookMessage = "Post From My Neighborhood "
                        + new java.util.Date().getTime();
            }
            messageToPost = facebookMessage;
            if (!facebook.isSessionValid()) {
                loginAndPostToWall();
            } else {
                try {
                    postToWall(messageToPost);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }





            }

            return null;
        }

        @Override
        protected void onPostExecute(Object result) {

            ShareOnFacebook.this.data = result;

            if (ShareOnFacebook.this.pd != null) {
                ShareOnFacebook.this.pd.dismiss();


        }

    }

    }
*/






     public void postToWall(String message) {


         final Dialog dialog = new Dialog(this, R.style.FullHeightDialog);
        dialog.setContentView(R.layout.customdialog);
        String fbUser = "";
        String neighbourhood = "";
        final Bundle parameters = new Bundle();
        try {




            JSONObject me = new JSONObject(facebook.request("me"));     
            String id = me.getString("id");
            // String namespace=me.getString("namespace");
            // Log.d(TAG, "FB namespace----->"+namespace);
            ImageView picture;
            ImageView map;
            TextView properties;
            TextView details;
            String lang = Constants.searchLocation.getLongitude() + "";
            String lat = Constants.searchLocation.getLatitude() + "";
            String url = Constants.fbindexURL + "lang=" + lang + "&lat=" + lat
                    + "&userid=" + fbUser;
            String mapKey = Constants.API_KEY;
            neighbourhood = Constants.loadedNeighborhood.getName();

            details = (TextView) dialog.findViewById(R.id.textView1);
            details.setText(parameters.getString("properties"));

            fbUser = me.getString("name");
            picture = (ImageView) dialog.findViewById(R.id.imageView1);
            properties = (TextView) dialog.findViewById(R.id.textView2);
            URL image_value = new URL("http://graph.facebook.com/" + id + "/picture");
            Bitmap profPic = BitmapFactory.decodeStream(image_value.openConnection().getInputStream());
            picture.setImageBitmap(profPic);
            properties.setText(getString(R.string.app_name));
            map = (ImageView) dialog.findViewById(R.id.imageView5);
            URL image_map = new URL("http://maps.googleapis.com/maps/api/staticmap?markers=" + lat + "%2C" + lang + "&zoom=12&size=300x300&key=" + mapKey + "&sensor=false&callback=myCallback&param=myParam");
            Bitmap mapimg = BitmapFactory.decodeStream(image_map.openConnection().getInputStream());
            map.setImageBitmap(mapimg);

            TextView via = (TextView) dialog.findViewById(R.id.textView3);
            via.setText("Via");

            Log.d(TAG, "FB User----->" + fbUser);
        } catch (Exception e) {
            Log.e(TAG, "FB User----->", e);

        }

        String lang = Constants.searchLocation.getLongitude() + "";
        String lat = Constants.searchLocation.getLatitude() + "";
        String url = Constants.fbindexURL + "lang=" + lang + "&lat=" + lat
                + "&userid=" + fbUser;
        String mapKey = Constants.API_KEY;// getResources().getString(R.string.apikey)
        String mapUrl = "http://maps.googleapis.com/maps/api/staticmap?markers="+ lat+ "%2C"+ lang+ "&zoom=12&size=300x300&key="+ mapKey+ "&sensor=false&callback=myCallback&param=myParam";
        Log.e(TAG, "url----->" + url);
        Log.e(TAG, "mapUrl" + mapUrl);

        neighbourhood = Constants.loadedNeighborhood.getName();

        parameters.putString("name", neighbourhood);
        parameters.putString("caption", "my neighborhood");
        parameters.putString("description", "click on below link..");
        parameters.putString("link", mapUrl);
        parameters.putString("properties", "{\" \": {\"text\":\"Reply / Recommend\", \"href\": \"" + url + "\"}}");
        try {



            final EditText edittext = (EditText) dialog.findViewById(R.id.fbedittext);

            Button dialogButton = (Button) dialog.findViewById(R.id.fbshare);
            Button dialogcancelButton = (Button) dialog.findViewById(R.id.fbcancel);

            dialogcancelButton.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    dialog.dismiss();

                    finish();
                }

            });
            dialogButton.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {

                    String messageText = edittext.getText().toString();
                    if (messageText != null) {

                        parameters.putString("message", messageText);
                        try {
                            facebook.request("me");
                            String response = facebook.request("me/feed",
                                    parameters, "POST");
                            Log.d("Tests", "got response: " + response);
                            if (response == null || response.equals("")
                                    || response.equals("false")) {
                                showToast("Blank response.");
                            } else {
                                showToast("Message posted to your facebook wall!");
                            }
                            finish();
                        } catch (Exception e) {
                            showToast("Failed to post to wall!");
                        }

                    }
                }

            });

            try {
                dialog.show();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            dialogFBMessage.dismiss();
            Log.d(TAG, "FBMessage Loading Step 02");
        } catch (Exception e) {
            showToast("Failed to post to wall!");
            e.printStackTrace();
            finish();
        }
    } 

    class LoginDialogListener implements DialogListener {
        public void onComplete(Bundle values) {
            saveCredentials(facebook);
            if (messageToPost != null) {


                postToWall(messageToPost);


            }
        }

我很震惊,不知道我哪里出错了......得到以下错误日志

 FATAL EXCEPTION: main
12-27 18:52:38.235: E/AndroidRuntime(6693): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.appright.myapp/org.apps.myapp.activity.ShareOnFacebook}: java.lang.RuntimeException: Only one Looper may be created per thread
12-27 18:52:38.235: E/AndroidRuntime(6693):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
12-27 18:52:38.235: E/AndroidRuntime(6693):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
12-27 18:52:38.235: E/AndroidRuntime(6693):     at android.app.ActivityThread.access$600(ActivityThread.java:140)
12-27 18:52:38.235: E/AndroidRuntime(6693):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
12-27 18:52:38.235: E/AndroidRuntime(6693):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-27 18:52:38.235: E/AndroidRuntime(6693):     at android.os.Looper.loop(Looper.java:137)
12-27 18:52:38.235: E/AndroidRuntime(6693):     at android.app.ActivityThread.main(ActivityThread.java:4898)
12-27 18:52:38.235: E/AndroidRuntime(6693):     at java.lang.reflect.Method.invokeNative(Native Method)
12-27 18:52:38.235: E/AndroidRuntime(6693):     at java.lang.reflect.Method.invoke(Method.java:511)
12-27 18:52:38.235: E/AndroidRuntime(6693):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1008)
12-27 18:52:38.235: E/AndroidRuntime(6693):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:775)
12-27 18:52:38.235: E/AndroidRuntime(6693):     at dalvik.system.NativeStart.main(Native Method)
12-27 18:52:38.235: E/AndroidRuntime(6693): Caused by: java.lang.RuntimeException: Only one Looper may be created per thread
12-27 18:52:38.235: E/AndroidRuntime(6693):     at android.os.Looper.prepare(Looper.java:78)
12-27 18:52:38.235: E/AndroidRuntime(6693):     at android.os.Looper.prepare(Looper.java:73)
12-27 18:52:38.235: E/AndroidRuntime(6693):     at org.appright.myapp.activity.ShareOnFacebook.onCreate(ShareOnFacebook.java:96)

非常感谢任何帮助或建议。

1 个答案:

答案 0 :(得分:0)

如果你正确实现了它,加载弹出对话框时,Facebook提要对话框已经有了自己的加载/进度微调器。

我的应用使用了Feed对话框,它已经有了自己的进度对话框。尝试下载our sample app并验证当您点按“更新状态”时是否看到进度对话框。