Java 背景任务和Facebook的上下文
我的android应用程序有问题。如果我使用我的“应用程序帐户”访问,就可以了 否则,如果我使用我的Facebook帐户凭据访问,则我的上下文为空 如何解决这个问题 下面是我的代码。先谢谢你 Login.java:Java 背景任务和Facebook的上下文,java,android,facebook,android-asynctask,android-context,Java,Android,Facebook,Android Asynctask,Android Context,我的android应用程序有问题。如果我使用我的“应用程序帐户”访问,就可以了 否则,如果我使用我的Facebook帐户凭据访问,则我的上下文为空 如何解决这个问题 下面是我的代码。先谢谢你 Login.java: 公共类登录扩展了AppCompatActivity{ 上下文ctx; 私人登录按钮登录按钮FB; 私有文本视图信息; 私人CallbackManager CallbackManager; EditText ET_NAME,ET_PASS; 字符串login\u name,login\
公共类登录扩展了AppCompatActivity{
上下文ctx;
私人登录按钮登录按钮FB;
私有文本视图信息;
私人CallbackManager CallbackManager;
EditText ET_NAME,ET_PASS;
字符串login\u name,login\u pass;
静态最终字符串USERNAME=“USER\u NAME”;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
sdkinInitialize(getApplicationContext());
setContentView(R.layout.activity\u登录);
callbackManager=callbackManager.Factory.create();
loginButtonFb=(LoginButton)findViewById(R.id.login\u button\u fb);
loginButtonFb.setReadPermissions(“用户朋友”);
ET_NAME=(EditText)findViewById(R.id.user_NAME);
ET_PASS=(EditText)findViewById(R.id.user_PASS);
info=(TextView)findViewById(R.id.info);
registerCallback(callbackManager,newfacebookcallback()){
@凌驾
成功时公共无效(LoginResult LoginResult){
新格力探索(
AccessToken.getCurrentAccessToken(),
loginResult.getAccessToken().getUserId(),
无效的
HttpMethod.GET,
新建GraphRequest.Callback(){
未完成公共空白(图形响应){
试一试{
JSONObject data=response.getJSONObject();
字符串idFb=data.getString(“id”);
字符串名称fb=data.getString(“名称”);
String method=“loginFb”;
BackgroundTask BackgroundTask=新的BackgroundTask(ctx);
backgroundTask.execute(方法、名称fb、idFb);
}捕获(JSONException e){
e、 printStackTrace();
}
}
}
).executeAsync();
}
@凌驾
公开作废{
info.setText(“登录尝试已取消”);
}
@凌驾
公共无效onError(FaceBook例外e){
info.setText(“登录尝试失败”);
}
});
}
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
callbackManager.onActivityResult(请求代码、结果代码、数据);
}
公共void userReg(视图){
意向意向=新意向(此,Registration.class);
星触觉(意向);
}
私有类BackgroundTask扩展了AsyncTask{
上下文ctx;
背景任务(上下文ctx){
this.ctx=ctx;
}
@凌驾
受保护的字符串doInBackground(字符串…参数){
字符串方法=参数[0];
if(方法等于(“登录”)){
字符串登录\u url=”http://192.168.1.118:80/webappdb/login.php";
字符串login_name=params[1];
字符串login_pass=params[2];
试一试{
URL=新URL(登录\ URL);
HttpURLConnection HttpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod(“POST”);
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream OutputStream=httpURLConnection.getOutputStream();
BufferedWriter BufferedWriter=新的BufferedWriter(新的OutputStreamWriter(outputStream,UTF-8));
字符串数据=urlcoder.encode(“登录名”,“UTF-8”)+“=”+urlcoder.encode(登录名,“UTF-8”)+“&”+
urlcoder.encode(“登录密码”,“UTF-8”)+“=”+urlcoder.encode(登录密码,“UTF-8”);
bufferedWriter.write(数据);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream InputStream=httpURLConnection.getInputStream();
BufferedReader BufferedReader=新的BufferedReader((新的InputStreamReader(inputStream,“iso-8859-1”));
字符串响应=”;
字符串行=”;
而((line=bufferedReader.readLine())!=null){
响应+=行;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
返回响应;
}捕获(格式错误){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
}
else if(方法等于(“loginFb”)){
字符串login_name=params[1];
字符串id=参数[2];
字符串loginFb_url=”http://192.168.1.118:80/webappdb/loginFb.php";
试一试{
URL URL=新URL(登录URL);
HttpURLConnection HttpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod(“POST”);
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream OutputStream=httpURLConnection.getOutputStream();
BufferedWriter BufferedWriter=新的BufferedWriter(新的OutputStreamWriter(outputStream,UTF-8));
字符串数据=urlcoder.encode(“登录名FB”、“UTF-8”)+“=”+urlcoder.encode(登录名“UTF-8”)+“&”+
urlcoder.encode(“id”,“UTF-8”)+“=”+urlcoder.encode(id,“UTF-8”);
bufferedWriter.write(数据);
bufferedWriter.flush();
缓冲写入
public class Login extends AppCompatActivity {
Context ctx;
private LoginButton loginButtonFb;
private TextView info;
private CallbackManager callbackManager;
EditText ET_NAME, ET_PASS;
String login_name, login_pass;
static final String USERNAME = "USER_NAME";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_login);
callbackManager = CallbackManager.Factory.create();
loginButtonFb = (LoginButton)findViewById(R.id.login_button_fb);
loginButtonFb.setReadPermissions("user_friends");
ET_NAME = (EditText) findViewById(R.id.user_name);
ET_PASS = (EditText) findViewById(R.id.user_pass);
info = (TextView)findViewById(R.id.info);
loginButtonFb.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
new GraphRequest(
AccessToken.getCurrentAccessToken(),
loginResult.getAccessToken().getUserId(),
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
try {
JSONObject data = response.getJSONObject();
String idFb = data.getString("id");
String nameFb = data.getString("name");
String method = "loginFb";
BackgroundTask backgroundTask = new BackgroundTask(ctx);
backgroundTask.execute(method, nameFb, idFb);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
).executeAsync();
}
@Override
public void onCancel() {
info.setText("Login attempt canceled.");
}
@Override
public void onError(FacebookException e) {
info.setText("Login attempt failed.");
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
public void userReg(View view){
Intent intent = new Intent(this, Registration.class);
startActivity(intent);
}
private class BackgroundTask extends AsyncTask<String, Void, String> {
Context ctx;
BackgroundTask(Context ctx){
this.ctx = ctx;
}
@Override
protected String doInBackground(String... params) {
String method = params[0];
if (method.equals("login")){
String login_url = "http://192.168.1.118:80/webappdb/login.php";
String login_name = params[1];
String login_pass = params[2];
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode("login_name", "UTF-8") + "=" + URLEncoder.encode(login_name, "UTF-8") + "&" +
URLEncoder.encode("login_pass", "UTF-8") + "=" + URLEncoder.encode(login_pass, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader((new InputStreamReader(inputStream, "iso-8859-1")));
String response = "";
String line = "";
while((line = bufferedReader.readLine()) != null){
response += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("loginFb")){
String login_name = params[1];
String id = params[2];
String loginFb_url = "http://192.168.1.118:80/webappdb/loginFb.php";
try {
URL url = new URL(loginFb_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode("login_nameFb", "UTF-8") + "=" + URLEncoder.encode(login_name, "UTF-8") + "&" +
URLEncoder.encode("id", "UTF-8") + "=" + URLEncoder.encode(id, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader((new InputStreamReader(inputStream, "iso-8859-1")));
String response = "";
String line = "";
while((line = bufferedReader.readLine()) != null){
response += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
if(result.equals("Login failed, try again.")){
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
if (result.equals("Login success!")){
Intent intent = new Intent(ctx,UserProfile.class);
intent.putExtra(USERNAME, login_name);
startActivity(intent);
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
}
}
public void userLogin(View view){
login_name = ET_NAME.getText().toString();
login_pass = ET_PASS.getText().toString();
String method = "login";
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute(method, login_name, login_pass);
}
}
gamingproject.sellmybooks E/AndroidRuntime: FATAL EXCEPTION: main
Process: gamingproject.sellmybooks, PID: 30637
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ComponentName.<init>(ComponentName.java:77)
at android.content.Intent.<init>(Intent.java:4144)
at gamingproject.sellmybooks.Login$BackgroundTask.onPostExecute(Login.java:228)
at gamingproject.sellmybooks.Login$BackgroundTask.onPostExecute(Login.java:123)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5536)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1397)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1192)
mContext = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
...
}
public void userLogin(View view){
login_name = ET_NAME.getText().toString();
login_pass = ET_PASS.getText().toString();
String method = "login";
BackgroundTask backgroundTask = new BackgroundTask(mContext);
backgroundTask.execute(method, login_name, login_pass);
}