我想在android上做异步任务,我在不同的类而不是活动内部做了。我的问题是,当我想将ProgressBar可见性从INVISIBLE设置为GONE时,它返回NullPointerException。我不明白为什么,这是我的代码到目前为止。
package com.ursabyte.boxi;
import android.os.AsyncTask;
import android.widget.ProgressBar;
public class SyncPercobaan extends AsyncTask<Object, Boolean, String> {
AktifitasUtama ut;
ManajemenFile mf;
ProgressBar loading;
@Override
protected void onPreExecute() {
super.onPreExecute();
ProgressBar loading = (ProgressBar) ut.findViewById(R.id.loading);
loading.setVisibility(ProgressBar.VISIBLE);
}
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
ProgressBar loading = (ProgressBar) ut.findViewById(R.id.loading);
loading.setVisibility(ProgressBar.GONE);
ut.browseToRoot();
}
@Override
protected String doInBackground(Object... params) {
String dir_name = (String) params[0];
ut = (AktifitasUtama) params[1];
ManajemenFile mf = new ManajemenFile(ut);
mf.retrieve_user_dir();
return dir_name;
}
}
AktifitasUtama是我的主要活动。
答案 0 :(得分:0)
这里
public class SyncPercobaan extends AsyncTask<Object, Boolean, String> {
AktifitasUtama ut; //<<--here
这种不正确的方法可以在AsyncTask
用于从非Activity类访问UI元素,创建非Activity的构造函数:
public class SyncPercobaan extends AsyncTask<Object, Boolean, String> {
Context context;
SyncPercobaan(Context context){
this.context=context;
}
//your code here
现在使用context
来访问AktifitasUtama
答案 1 :(得分:0)
答案是context.runOnUiThread。在我的情况下ut.runOnUiThread。这是代码:
public class SyncPercobaan extends AsyncTask<Object, Boolean, String> {
AktifitasUtama ut;
ManajemenFile mf;
ManajemenKoneksi mk;
SessionManager session;
DatabaseHandler dh;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String response) {
final String res = response;
super.onPostExecute(response);
session = new SessionManager(ut);
ut.runOnUiThread(new Runnable() {
@Override
public void run() {
ut.toogle_indicator(false);
ut.display_toast(res);
}
});
ut.browseToRoot();
}
@Override
protected String doInBackground(Object... params) {
String dir_name = (String) params[0];
ut = (AktifitasUtama) params[1];
session = new SessionManager(ut);
mk = new ManajemenKoneksi(ut);
if(mk.is_connected()){
ut.runOnUiThread(new Runnable() {
@Override
public void run() {
ut.display_toast("Starting syncing...");
ut.toogle_indicator(true);
}
});
ManajemenFile mf = new ManajemenFile(ut);
String result = mf.retrieve_user_dir(dir_name);
if(result.equals("true")){
return "Syncing completed...";
} else {
return result;
}
} else {
return "Internet connection unavailable";
}
}
}
class Task extends TimerTask {
AktifitasUtama au;
String dir_name;
Task(AktifitasUtama ut, String dir_name){
au=ut;
this.dir_name=dir_name;
}
public void run() {
ManajemenFile mf = new ManajemenFile(au);
mf.retrieve_user_dir(dir_name);
}
}