0

我的代码如下。我在实现 Async Task 时遇到了麻烦,Async Task 的 android 文档对我来说有点令人困惑。谁能用清晰的步骤向我解释?

这是我的代码:

package com.sara.facebookappl;

import java.io.IOException;
import java.net.MalformedURLException;

import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;

public class MainActivity extends Activity implements OnClickListener, DialogListener {

Facebook fb; 
ImageView button; 
private SharedPreferences sp; 
TextView welcome; 
Button post; 

@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    post=(Button)findViewById(R.id.button1);

    String APP_ID = getString(R.string.APP_ID);
    fb= new Facebook(APP_ID);

    Looper.prepare(); 
    new PostTask().execute(fb);
    Looper.loop(); 

    sp =getPreferences(MODE_PRIVATE);
    String access_token=sp.getString("access_token", null);
    long expires=sp.getLong("access_expires", 0);

    if (access_token !=null) {
        fb.setAccessToken(access_token);
    }
    if(expires !=0) {
        fb.setAccessExpires(expires);
    }


    button=(ImageView)findViewById(R.id.login);
    button.setOnClickListener((OnClickListener) this);
    updateButtonImage();

}

private class PostTask extends AsyncTask<Facebook, Integer, String> {

    ProgressDialog dialog; 

    protected void onPreExecute() {
        dialog = new ProgressDialog(MainActivity.this);
        dialog.setProgress(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setMax(100);
        dialog.show();


    }

    @SuppressWarnings("deprecation")
    @Override
    protected String doInBackground(Facebook... params) {
        if (fb.isSessionValid()) {
            button.setImageResource(R.drawable.com_facebook_loginbutton_blue);
            // ^logout button

        JSONObject obj=null;

        try {
        String jsonUser= fb.request("me");
        obj = Util.parseJson(jsonUser);
        String name = obj.optString("name");
        welcome.setText("Welcome, " + name);
        }catch(FacebookError e) {
            e.printStackTrace();

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

        }else {
            post.setVisibility(Button.VISIBLE);
            button.setImageResource(R.drawable.com_facebook_loginbutton_blue);
        }
        return null;
    }
}

protected void onProgressUpdated(Integer...progress) {

}

@SuppressWarnings("deprecation")
protected void onPostExecute(Facebook result) {

        // ^logout button
    try {JSONObject obj=null;
    String jsonUser= fb.request("me");
    obj = Util.parseJson(jsonUser);
    String name = obj.optString("name");
    welcome.setText("Welcome, " + name);}
    catch(FacebookError e) {
        e.printStackTrace();

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


private void updateButtonImage() {
    // TODO Auto-generated method stub

    post.setVisibility(Button.VISIBLE);
    button.setImageResource(R.drawable.com_facebook_loginbutton_blue);
    //logout button


}

@SuppressWarnings("deprecation")
public void buttonClicks(View v) {
    switch (v.getId()) {
        case R.id.button1:
            //post

            Bundle params= new Bundle();

            params.putString("name", "User X"); 
            params.putString("caption", "Rating"); 
            params.putString("description", "User X Rated"); 
            params.putString("link", "http://..."); 



            fb.dialog(MainActivity.this, "feed", params, new Facebook.DialogListener() {

                @Override
                public void onFacebookError(FacebookError e) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onError(DialogError e) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onComplete(Bundle values) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onCancel() {
                    // TODO Auto-generated method stub

                }
            });
            break;
    }
}
@SuppressWarnings("deprecation")
public void onClick(View v) {
    if(fb.isSessionValid()) {

        try {
        fb.logout(getApplicationContext());
        updateButtonImage();
        //button will close our our session
    }catch(MalformedURLException e) {
        e.printStackTrace();
    } catch(IOException e) {
        e.printStackTrace();
    }
}else{
        //login into facebook
        fb.authorize(MainActivity.this, new String[] {"email"}, new Facebook.DialogListener() {

            @Override
            public void onFacebookError(FacebookError e) {
                // TODO Auto-generated method stub
                Toast.makeText(MainActivity.this, "fbError", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(DialogError e) {
                // TODO Auto-generated method stub
                Toast.makeText(MainActivity.this, "onError", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete(Bundle values) {
                // TODO Auto-generated method stub
                Editor editor=sp.edit();
                editor.putString("access_token", fb.getAccessToken());
                editor.putLong("access_expires", fb.getAccessExpires());
                editor.commit();
                updateButtonImage();
            }

            @Override
            public void onCancel() {
                // TODO Auto-generated method stub
                Toast.makeText(MainActivity.this, "onCancel", Toast.LENGTH_SHORT).show();
            }
        });

        }
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

@SuppressWarnings("deprecation")
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    fb.authorizeCallback(requestCode, resultCode, data);
}

@Override
public void onComplete(Bundle values) {
    // TODO Auto-generated method stub

}

@Override
public void onFacebookError(FacebookError e) {
    // TODO Auto-generated method stub

}

@Override
public void onError(DialogError e) {
    // TODO Auto-generated method stub

}

@Override
public void onCancel() {
    // TODO Auto-generated method stub

}

}

这是 logcat 错误:

12-17 19:24:04.886: E/AndroidRuntime(862): FATAL EXCEPTION: AsyncTask #1
12-17 19:24:04.886: E/AndroidRuntime(862): java.lang.RuntimeException: An error occured      while executing doInBackground()
12-17 19:24:04.886: E/AndroidRuntime(862):  at     android.os.AsyncTask$3.done(AsyncTask.java:299)
12-17 19:24:04.886: E/AndroidRuntime(862):  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
12-17 19:24:04.886: E/AndroidRuntime(862):  at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
12-17 19:24:04.886: E/AndroidRuntime(862):  at java.util.concurrent.FutureTask.run(FutureTask.java:239)
12-17 19:24:04.886: E/AndroidRuntime(862):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
12-17 19:24:04.886: E/AndroidRuntime(862):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
12-17 19:24:04.886: E/AndroidRuntime(862):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
12-17 19:24:04.886: E/AndroidRuntime(862):  at java.lang.Thread.run(Thread.java:856)
12-17 19:24:04.886: E/AndroidRuntime(862): Caused by: java.lang.NullPointerException
12-17 19:24:04.886: E/AndroidRuntime(862):  at com.sara.facebookappl.MainActivity$PostTask.doInBackground(MainActivity.java:97)
12-17 19:24:04.886: E/AndroidRuntime(862):  at com.sara.facebookappl.MainActivity$PostTask.doInBackground(MainActivity.java:1)
12-17 19:24:04.886: E/AndroidRuntime(862):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
12-17 19:24:04.886: E/AndroidRuntime(862):  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
12-17 19:24:04.886: E/AndroidRuntime(862):  ... 4 more

编辑:我改变了它,我仍然得到这些日志猫错误:

12-17 20:22:22.659: E/AndroidRuntime(794): FATAL EXCEPTION: main
12-17 20:22:22.659: E/AndroidRuntime(794): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sara.facebookappl/com.sara.facebookappl.MainActivity}:     java.lang.RuntimeException: Only one Looper may be created per thread
12-17 20:22:22.659: E/AndroidRuntime(794):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
12-17 20:22:22.659: E/AndroidRuntime(794):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
12-17 20:22:22.659: E/AndroidRuntime(794):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-17 20:22:22.659: E/AndroidRuntime(794):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
12-17 20:22:22.659: E/AndroidRuntime(794):  at android.os.Handler.dispatchMessage(Handler.java:99)
12-17 20:22:22.659: E/AndroidRuntime(794):  at android.os.Looper.loop(Looper.java:137)
12-17 20:22:22.659: E/AndroidRuntime(794):  at android.app.ActivityThread.main(ActivityThread.java:5039)
12-17 20:22:22.659: E/AndroidRuntime(794):  at java.lang.reflect.Method.invokeNative(Native Method)
12-17 20:22:22.659: E/AndroidRuntime(794):  at java.lang.reflect.Method.invoke(Method.java:511)
12-17 20:22:22.659: E/AndroidRuntime(794):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)

12-17 20:22:22.659: E/AndroidRuntime(794): 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 12-17 20:22:22.659: E/AndroidRuntime(794) : at dalvik.system.NativeStart.main(Native Method) 12-17 20:22:22.659: E/AndroidRuntime(794): Caused by: java.lang.RuntimeException: only one Looper may be created per thread 12-17 20 :22:22.659: E/AndroidRuntime(794): 在 android.os.Looper.prepare(Looper.java:78) 12-17 20:22:22.659: E/AndroidRuntime(794): 在 android.os.Looper。准备(Looper.java:73)12-17 20:22:22.659:E/AndroidRuntime(794):在 com.sara.facebookappl.MainActivity.onCreate(MainActivity.java:53)12-17 20:22:22.659: E/AndroidRuntime(794): 在 android.app.Activity.performCreate(Activity.java:5104) 12-17 20:22:22.659: E/AndroidRuntime(794): 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 12-17 20:22:22.659: E/AndroidRuntime(794): 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)

4

1 回答 1

0
 welcome.setText("Welcome, " + name);

除非我在某个地方错过了它,否则我不相信您曾经正确初始化“欢迎”。我认为,您应该在 onCreate 中为此找到ViewById()。我怀疑这是nullref。

于 2012-12-17T20:04:46.287 回答