在这里,首先,当数据同步到本地数据库时,我的应用程序从服务器同步数据后台线程是布尔类型,因此我无法调用功能来从那里获取图像。如果我从 postexecute 调用方法然后我得到 NetworkOnMainthread 异常我被困在我需要使用安全线程的情况下面是代码
protected void onPreExecute() {
mDialog = ProgressDialog.show(viewContext, "", "Synchronizing Data",
true);
};
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#doInBackground(Params[])
*/
@Override
protected Boolean doInBackground(Void... arg0) {
if (type.contains("ferry")) {
return SynchronizeRepositoryFerry(false);
} else {
return SynchronizeRepositories(false, initialSync);
}
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute(Boolean result) {
this.syncComplete = result;
mDialog.dismiss();
if (type.contains("Dash")) {
new BackgroundTask().execute();
}
else{
Intent intent = new Intent();
intent.setClass(viewContext, classType);
viewContext.startActivity(intent);
}
}
class BackgroundTask extends AsyncTask<Void, Void, Void> {
ProgressDialog mDialog;
protected void onPreExecute() {
mDialog = ProgressDialog.show(viewContext, "", "Loading Images",
true);
};
@Override
protected Void doInBackground(Void... params) {
try {
int id = 0;
String url = "http://i.zdnet.com/blogs/3-29-androids.jpg";
com.jumbybay.businessobjects.User user = new com.jumbybay.businessobjects.User();
DatabaseHelper dbHelper = new DatabaseHelper(viewContext);
IUserRepository repository = dbHelper.getUserRepository();
List<com.jumbybay.businessobjects.User> imageList;
try {
imageList = repository.Retrieve();
for (int i = 0; i < imageList.size(); i++) {
user = imageList.get(i);
// url = user.getPicture();
id = user.getId();
savesd(id, url);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (final Exception e) {
}
return null;
}
public void savesd(int id, String uri) throws IOException {
URL url;
if (uri == null) {
url = new URL("http://i.zdnet.com/blogs/3-29-androids.jpg");
} else {
url = new URL(uri);
}
InputStream input = url.openStream();
try {
File storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream(new File(
storagePath, +id + ".jpg"));
try {
byte[] buffer = new byte[20000];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
input.close();
}
}
protected void onPostExecute(Void result) {
mDialog.dismiss();
Intent intent = new Intent();
/*
* intent.setClass(viewContext, classType);
* viewContext.startActivity(intent);
*/
intent.setClass(viewContext, classType);
viewContext.startActivity(intent);
};
}