编辑:已解决.对不起,伙计们,我发现虽然我的数据加载发生在后台线程中,但解析数据的回调却没有.解析数据花了很长时间,这就是锁定我的线程的原因.
编辑:我注意到我的首要问题(ProgressDialog不再旋转)可能是由于我使用ProgressDialog而不是阻止UI线程的问题引起的.如果是这种情况,我该如何解决?
编辑:澄清一下,这并不会永远锁定整个程序.加载完所有内容后,将取消进度对话框,并启动新活动.我的问题是,当它加载时,整个UI锁定(即progressdialog停止旋转)
TL; DR:doInBackground()中的Thread.sleep()锁定UI线程
我有一个应用程序,当特定活动打开时,开始从后端加载后台的大量数据,例如,与计划相关的大量数据.此信息不会立即使用,但如果用户尝试访问它(即通过单击计划按钮,并启动计划活动),则可以使用此信息.
如果用户在单击计划按钮之前等待一点,则会加载所有数据,计划活动将打开,并显示所有内容.我的问题是,如果他们在数据加载前单击按钮.
我的解决方案是创建一个显示ProgressDialog的ASyncTask,同时定期检查数据是否已完成加载,否则将睡眠.它知道数据是通过一些应用程序范围的布尔变量完成加载的.我的问题是,即使Thread.sleep()在doinbackground()中运行,它仍然锁定UI线程.
我使用的是自定义ASyncTask,定义如下:
public class LoadWithProgressDialog extends AsyncTask<Void, Void, Boolean>{
private ProgressDialog pd; //the progress dialog
private String title; //the title of the progress dialog
private String message; //the body of the progress dialog
private Runnable task; //contains the code we want to run in the background
private Runnable postTask; //execute when the task ends
private Context c;
public LoadWithProgressDialog(Context context,String t, String m,Runnable r, Runnable postR){
super();
c = context;
task = r; …Run Code Online (Sandbox Code Playgroud) 我使用an AsyncTask来获取数据,然后将其加载到ListView.我的代码是:
AsyncTaskTwitterFeeds asyncTaskTwitterFeeds = new AsyncTaskTwitterFeeds(TwitterFeedsActivity.this);
asyncTaskTwitterFeeds.execute("");
loadList();
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,一旦AsyncTask执行,流程就会到达loadlist()方法并且程序崩溃.我发现的原因Adapter是仍在使用的数组仍在填充.我想知道我如何能够AsyncTask执行一次并且只有当它完成然后流程应该转到loadlist()方法时.这是LogCat错误:
02-25 18:50:25.879: E/AndroidRuntime(19851): FATAL EXCEPTION: main
02-25 18:50:25.879: E/AndroidRuntime(19851): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cubix.twitterfeed/com.cubix.twitterfeed.TwitterFeedsActivity}: java.lang.NullPointerException
02-25 18:50:25.879: E/AndroidRuntime(19851): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1816)
02-25 18:50:25.879: E/AndroidRuntime(19851): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1837)
02-25 18:50:25.879: E/AndroidRuntime(19851): at android.app.ActivityThread.access$1500(ActivityThread.java:132)
02-25 18:50:25.879: E/AndroidRuntime(19851): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1033)
02-25 18:50:25.879: E/AndroidRuntime(19851): at android.os.Handler.dispatchMessage(Handler.java:99)
02-25 18:50:25.879: E/AndroidRuntime(19851): at android.os.Looper.loop(Looper.java:143)
02-25 18:50:25.879: E/AndroidRuntime(19851): at android.app.ActivityThread.main(ActivityThread.java:4196)
02-25 18:50:25.879: E/AndroidRuntime(19851): at …Run Code Online (Sandbox Code Playgroud) public class async extends AsyncTask<String, Integer, String>{
ProgressDialog prog;
@Override
protected void onPreExecute() {
super.onPreExecute();
prog=new ProgressDialog(async.this);//This is chowing error
prog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
prog.setMax(100);
prog.show();
}
@Override
protected String doInBackground(String... params) {
for (int i = 0; i < 10; i++) {
publishProgress(5);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
prog.dismiss();
}
@Override
protected void onProgressUpdate(Integer... values) {
prog.setProgress(values[0]);
super.onProgressUpdate(values);
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码产生错误: …
无论如何使用AsyncTask而不传入任何参数?我目前正在传递一个空字符串,但我没有做任何事情:
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "" });
class DownloadWebPageTask extends AsyncTask<String, Void, String> {
private final ProgressDialog dialog = new ProgressDialog(MainScreen.this);
@Override
protected void onPreExecute() {
dialog.setMessage("Gathering data for\n"+selectedSportName+".\nPlease wait...");
dialog.show();
}
@Override
protected String doInBackground(String... urls) {
//go do something
return "";
}
@Override
protected void onPostExecute(String result) {
dialog.dismiss();
startTabbedViewActivity();
}
}
private void startTabbedViewActivity(){
Intent intent = new Intent(MainScreen.this, TabbedView.class);
intent.putExtra(SPORT_NAME_EXTRA, selectedSportName);
intent.putExtra(HEADLINES_FOR_SPORT_EXTRA, existingSportHeadlines.get(selectedSportName));
intent.putExtra(SCORES_FOR_SPORT_EXTRA, existingSportScores.get(selectedSportName));
intent.putExtra(SCHEDULE_FOR_SPORT_EXTRA, existingSportSchedule.get(selectedSportName));
startActivity(intent);
}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,当我运行如图所示的代码时,doInBackground()中没有任何事情发生,对话框消失,TabbedView活动启动.
但是,当我使用doInBackground()运行某些代码时,对话框会消失,但TabbedView活动将无法启动.所以我想知道我是否可以做任何不同的事情?
在我的应用程序中,我需要根据来自网络的数据更新UI中的文本.因为我AsyncTask在Android中使用后台工作.我的代码如下.
public class DefaultActivity extends Activity{
TextView textView;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView=(TextView)findViewById(R.id.textId);
new networkFileAccess().execute("background","Progress","result");
}
private class networkFileAccess extends AsyncTask<String,String,String>{
protected String doInBackground(String... background){
return changeText();
}
private String changeText(){
//Code to Access data from the Network.
//Parsing the data.
//Retrieving the boolean Value.
if(booleanistrue){
//Displaying some text on the UI.
publishProgress("someTextOnUI");
//Send request till we get get boolean value as false.
changeText();
}else{
return "success";
}
return "";
}
protected void onProgressUpdate(String... progress){
textView.setText("Wait …Run Code Online (Sandbox Code Playgroud) 我有下面的代码的问题,onProgressUpdate没有运行...但是onPreExecute,doInBackground和onPostExecute相应地执行.还是我需要在doInBackground中返回?请告诉我错过了什么.我曾经删除过
notification.contentView.setProgressBar(R.id.pbStatus, 100, progress, false);
notificationManager = (NotificationManager) getApplicationContext().getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
notificationManager.notify(42, notification);
Run Code Online (Sandbox Code Playgroud)
在onCreate中,通知根本没有出现.以下是完整代码:
package com.android.MaxApps;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.RemoteViews;
import android.widget.Toast;
public class StaffChoice extends Activity {
ProgressBar progressBar;
private int progress;
Intent MyI;
PendingIntent MyPI;
NotificationManager MyNM;
Notification notification;
NotificationManager notificationManager;
@Override …Run Code Online (Sandbox Code Playgroud) 我得到了一个名为A的类,我的async类被编写为A的内部类.我得到了另一个名为B(Activity)的类.现在我在B班.我想要的是调用A的asyncTask.
我对这个问题很困惑,如果有人能给我一个正确的答案,他将成为一个救命的人.希望你们帮助我.谢谢.
我是android的新手,我正在尝试与Json做一些异步任务,我想从tke Json文件到达数据.我的代码是:
package com.example.httpsample;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.httpsample.HttpExample.Read;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView httpsetup;
HttpClient client;
JSONObject json;
//url tan?mlama:
final static String URL = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.httpex);
httpsetup = (TextView) findViewById(R.id.tvHttp);
//client aç?yoruz.
client …Run Code Online (Sandbox Code Playgroud) 我的Android应用程序中有一个名为Main.java的类,用于根据我服务器中的数据验证用户登录名(用户名+密码).起初,我成功了; 我使用AsyncTask线程加上一个处理Http连接的库,调用HttpPostAux.java(实际上,我在这个论坛中找到了库的代码).在AsyncTask的onPostExecute方法中,我创建并启动了一个新活动,而不是修改当前的活动并且它有效.
但现在我想做的事情与众不同.我想将验证的数据(用户名+密码)保存到AsyncTask线程中的SQLite表中,然后在UI线程中,恢复该数据并使用它来打开上述活动.插入发生但当我尝试从UI线程访问数据库时:它表示该表为空.所以我查看了logcat,发现UI线程在AsyncTask线程之前执行.
所以我的问题是如何在AsyncTask线程中插入数据然后在UI线程内恢复?有人可以帮忙吗?我有点迷路了!
我将欣赏一个代码示例!提前致谢!来自委内瑞拉的问候!
我想在我的Listview中显示一个Button,以防我没有数据通过自定义数组适配器填充列表.如果我有数据并且我的listview填充了数据项,但是如果我没有数据项,那么一切正常显示listview应该显示ID为"@android:id/empty"的LinearLayout但是它从未显示出来并且我的应用程序在此阶段崩溃.在我的FavoriteStudents.java类文件中我定义了AsyncTask.In doInBackground方法我检查如果我的手机内存中有喜欢的文件为listview创建适配器,如果没有则停止AsyncTask并显示只有一个按钮的列表视图.从doInBackground方法返回后它崩溃并显示我的错误:
10-16 16:06:37.568: E/WindowManager(274): Activity com.example.hellogridview.FavoriteStudets has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@44bfea80 that was originally added here
10-16 16:06:37.568: E/WindowManager(274): android.view.WindowLeaked: Activity com.example.hellogridview.FavoriteStudents has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@44bfea80 that was originally added here
10-16 16:06:37.568: E/WindowManager(274): at android.view.ViewRoot.<init>(ViewRoot.java:227)
10-16 16:06:37.568: E/WindowManager(274): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
10-16 16:06:37.568: E/WindowManager(274): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
10-16 16:06:37.568: E/WindowManager(274): at android.view.Window$LocalWindowManager.addView(Window.java:424)
10-16 16:06:37.568: E/WindowManager(274): at android.app.Dialog.show(Dialog.java:239)
10-16 16:06:37.568: E/WindowManager(274): at com.example.hellogridview.FavoriteStudents$readingFavFileTask.onPreExecute(FavoriteStudents.java:50)
10-16 16:06:37.568: E/WindowManager(274): at android.os.AsyncTask.execute(AsyncTask.java:391)
10-16 16:06:37.568: E/WindowManager(274): at com.example.hellogridview.FavoriteStudents.onCreate(FavoriteStudents.java:34)
10-16 16:06:37.568: E/WindowManager(274): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
10-16 …Run Code Online (Sandbox Code Playgroud)