Java Android接口回调引发空指针异常
我的所有活动/片段等都有一个asyntask,但现在我正在为每个活动实现一个接口,但是我的接口回调总是空的,我不知道为什么。每个调用asyncTask的活动都实现接口 实现接口并调用异步任务的我的类Java Android接口回调引发空指针异常,java,android,interface,android-asynctask,nullpointerexception,Java,Android,Interface,Android Asynctask,Nullpointerexception,我的所有活动/片段等都有一个asyntask,但现在我正在为每个活动实现一个接口,但是我的接口回调总是空的,我不知道为什么。每个调用asyncTask的活动都实现接口 实现接口并调用异步任务的我的类 public class MainActivity extends Activity implements MainActivityAsyncInterface, OnClickListener, UserPictureDialogInterface { private DrawerLayout
public class MainActivity extends Activity implements MainActivityAsyncInterface, OnClickListener, UserPictureDialogInterface {
private DrawerLayout moodydrawerLayout;
private HashMap<String, String> organizedCourses = new HashMap<String, String>();
// ManSession Manager Class
ManSession session;
private long startTime;
private long endTime;
private ModDevice md;
private float screenX;
private float screenY;
private int shotType = ShowcaseView.TYPE_ONE_SHOT;
private MoodleUser currentUser;
private String url;
private String token;
private String userId;
private static long backPressed;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The following line triggers the initialization of ACRA
.......
session = new ManSession(getApplicationContext());
url = session.getValues(ModConstants.KEY_URL, null);
token = session.getValues(ModConstants.KEY_TOKEN, null);
userId = session.getValues(ModConstants.KEY_ID, null);
new DataAsyncTask(this,).execute(url, token, EXAMPLE.CORE_USER_GET_USERS_BY_ID, userId, MainActivity.class.getSimpleName());
populateLeft();
populateRight();
receiveNotification();
initDemoOverlay();
drawerLayoutListener();
warningMessage(checkConnection(), Toast.LENGTH_LONG, null, getString(R.string.no_internet));
ChangeLogListView sad = new ChangeLogListView(getApplicationContext());
}
public class DataAsyncTask extends AsyncTask<Object, Void, Object> {
Object jObj = null;
public MainActivityAsyncInterface mainActivityInterface;
private ProgressDialog dialog;
private CountDownTimer cvt = createCountDownTimer();
private Context context;
private MoodleServices webService;
private String parentActivity;
private String fillTheSpace;
public DataAsyncTask(Context context) {
this.context = context;
dialog = new ProgressDialog(context);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
cvt.start();
}
@Override
protected Object doInBackground(Object... params) {
String urlString = (String) params[0];
String token = (String) params[1];
webService = (MoodleServices) params[2];
Object webServiceParams = params[3];
parentActivity = (String) params[4];
case EXAMPLE:
InputStream inputStream = new URL(urlString).openStream();
Drawable drawable = Drawable.createFromStream(inputStream, null);
inputStream.close();
return drawable;
default:
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* <p>
* Method that parses a supposed id list object
* </p>
*
* @param Object
* ids - The object to be parsed to Long[].
* @return resultList - The ids List
*/
private Long[] parseIds(Object ids) {
Long[] resultList = null;
try {
resultList = (Long[]) ids;
} catch (Exception e) {
resultList = new Long[1];
resultList[0] = (Long) ids;
}
return resultList;
}
@Override
protected void onPostExecute(Object obj) {
cvt.cancel();
if (dialog != null && dialog.isShowing())
dialog.dismiss();
switch (webService) {
case EXAMPLE:
if (parentActivity.equalsIgnoreCase(MainActivity.class.getSimpleName()))
mainActivityInterface.userAsyncTaskResult(obj); \\This the line 173 and the obj != null and mainActivityInterface is null
if (parentActivity.equalsIgnoreCase(UserDetailsActivity.class.getSimpleName()))
fillTheSpace = "TODO - Interface for each parent class";
if (parentActivity.equalsIgnoreCase(FragTopicsPreview.class.getSimpleName()))
fillTheSpace = "TODO - Interface for each parent class";
if (parentActivity.equalsIgnoreCase(FragTopics.class.getSimpleName()))
fillTheSpace = "TODO - Interface for each parent class";
break;
case EXAMPLE2:
if (parentActivity.equalsIgnoreCase(MainActivity.class.getSimpleName()))
mainActivityInterface.userAsyncTaskResult(obj);
if (parentActivity.equalsIgnoreCase(UserDetailsActivity.class.getSimpleName()))
fillTheSpace = "TODO - Interface for each parent class";
if (parentActivity.equalsIgnoreCase(FragTopicsPreview.class.getSimpleName()))
fillTheSpace = "TODO - Interface for each parent class";
if (parentActivity.equalsIgnoreCase(FragTopics.class.getSimpleName()))
fillTheSpace = "TODO - Interface for each parent class";
break;
default:
break;
}
}
private CountDownTimer createCountDownTimer() {
return new CountDownTimer(250, 10) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
dialog = new ProgressDialog(context);
dialog.setMessage("Loading...");
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
};
}
根据我的经验,接口不应该在我的代码中发送nullPointer异常,接口也不需要初始化,但在这一点上,我将所有选项都放在了表上。这是因为您从未将侦听器传递到任务中 您只发送构造函数中的上下文,但它应该如下所示:
public DataAsyncTask(Context context , MainActivityAsyncInterface mainActivityInterface) {
this.context = context;
this.mainActivityInterface = mainActivityInterface;
dialog = new ProgressDialog(context);
}
在活动中,将此添加到开始任务的位置
YourAcivity.this.
更新:
回答你的问题,
您可以创建BaseActivity,它将扩展活动并实现侦听器。
然后,所有活动都必须重写侦听器函数。如果
MainActivityAsyncInterface
是活动实现的接口,则需要将其传递给异步任务。当前,mainActivityInterface
从未初始化,并且始终为空,因此您会得到异常
您可以在构造函数中传递引用
public DataAsyncTask(Context context, MainActivityAsyncInterface mainActivityInterface) {
this.context = context;
this.mainActivityInterface = mainActivityInterface;
dialog = new ProgressDialog(context);
}
哪一行是onPostExecute(DataAsyncTask.java:173)?我对标记行mainActivityInterface.userAsyncTaskResult(obj)的代码有评论\\这是第173行和obj!=null且mainActivityInterface为null您没有初始化mainActivityInterface,如果您在哪里?您从未将
mainActivityInterface
设置为值,因此它为null。值?!mainActivityInterface这是一个接口,你建议初始化接口吗?!像mainActivityInterface=toSomething?我已经看到了这种可能性,但问题是我会有6个以上的接口,每个活动的每个接口,所以唯一的解决方案是有6个构造函数,接口有一个泛型类型吗?你必须先了解,除非在某个地方初始化侦听器,否则无法使用它。@firetrap您似乎只在界面中使用了userAsyncTaskResult
方法。它应该是定义该方法的接口。您可以创建扩展活动的BaseActivity并实现侦听器,然后您的所有活动都将扩展该类。没关系,异步任务类无权访问您的活动,除非发送您的侦听器,即您的活动。这是。
public DataAsyncTask(Context context, MainActivityAsyncInterface mainActivityInterface) {
this.context = context;
this.mainActivityInterface = mainActivityInterface;
dialog = new ProgressDialog(context);
}