我知道这是常见问题,但找不到我的错误。我需要将 Activity 的 Context 传递给非活动的 RestClient 类。我这样做:
public class RestClient {
public void setContextRest(Context ctx)
{
this.context = ctx;
}
public Context getContextRest()
{
return this.context;
}
public RestClient(Context context)
{
this.context = context;
}
}
在我的活动课上:
RestClient helper = new RestClient(LoginActivity.this);
helper.setContextRest(LoginActivity.this);
这就是我在 RestClient 中获得它的方式:
Intent i = new Intent(context, LoginActivity.class);
i.putExtra("relogin", true);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
我得到
java.lang.NullPointerException
at android.content.ComponentName.<init>(ComponentName.java:75)
at android.content.Intent.<init>(Intent.java:2823)
at com.library.RestClient.Execute(RestClient.java:276)
at com.library.JSONParser.getJSONFromUrl(JSONParser.java:46)
at com.library.UserFunctions.loginUser(UserFunctions.java:76)
at com.assignmentexpert.LoginActivity$LoginTask.doInBackground(LoginActivity.java:318)
at com.assignmentexpert.LoginActivity$LoginTask.doInBackground(LoginActivity.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
at java.lang.Thread.run(Thread.java:1019)
threadid=9: thread exiting with uncaught exception (group=0x40018578)
在Intent i = new Intent(context, LoginActivity.class);
. 问题是由于context
某种原因它是空的。请告诉我它是什么?