我正在开发一个Android应用程序,我的问题是AsyncTask的实现,我必须做的是"简单":
这部分功能用于从数据库中获取信息,数据加载后,信息显示在表格中,我会实现一个功能,允许我在检索信息时显示进度条(读取服务器)
try {
String url_img = null;
String path = "MY FANTASTIC PATH";
/*READSERVER RETURN JSON STRING THAT CONTAIN SOME IMFORMATION*/
ReadServer read = new ReadServer();
String result = read.readserver("list_news","homepage");
TableLayout MainTable = (TableLayout)findViewById(R.id.main_table);
JSONArray Jobj = new JSONArray(result);
for (int i = 0; i < Jobj.length(); i++){
TableRow row = new TableRow(getApplicationContext());
row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
row.setPadding(0, 14, 2, 14);
JSONObject news_preview = Jobj.getJSONObject(i);
Integer news_id = news_preview.getInt("id_articolo");
String news_title = news_preview.getString("titolo");
String news_image = news_preview.getString("immagine");
//Check if image url is relative or absolute
Pattern p = Pattern.compile("^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]");
Matcher m = p.matcher(news_image);
if(m.matches() == false){
url_img = path+news_image;
}else if(m.matches() == true){
url_img = news_image;
}
//Call Html Parser to parse text
HtmlParser parsed_string = new HtmlParser();
Spanned title_nohtml = parsed_string.htmlparser(news_title);
//Thumb
ImageView img = new ImageView(getApplicationContext());
img.setAdjustViewBounds(true);
img.setMaxHeight(140); img.setMaxWidth(140);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(url_img).getContent());
img.setImageBitmap(bitmap);
LayoutParams params = new TableRow.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
//Clickable title
final TextView txt = new TextView(getApplicationContext());
txt.setGravity(Gravity.LEFT | Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL );
txt.setLayoutParams(params); txt.setTextSize(18); txt.setBackgroundColor(Color.WHITE);
txt.setTypeface(null, Typeface.BOLD); txt.setTextColor(Color.BLACK);
txt.setId(news_id); txt.setText(title_nohtml); txt.setClickable(true);
row.addView(img);
row.addView(txt);
MainTable.addView(row);
txt.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, OtherPages.class);
Bundle extras = new Bundle();
extras.putString("Boolean","1");
extras.putInt("id_news", txt.getId());
intent.putExtras(extras);
startActivity(intent);
}
});
}
}catch(Exception e){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Si è verificato un errore");
alertDialog.setMessage("Errore 001" +"\n"+"Non è stato possibile soddisfare la tua richiesta, riprova più tardi.");
alertDialog.show();
}
}else{
connectivityMessage("Nessuna connessione presente, assicurati di avere il traffico dati oppure il Wi-Fi attivato e riprova.");
}
我知道我必须使用这个代码,但我不知道如何实现,任何人都可以帮助我吗?
GetNews getNewsTask = new GetNews().execute();
private class GetNews extends AsyncTask<Void, Void, Void>{
private ProgressDialog progress = null;
@Override
protected Void doInBackground(Void... params) {
// do something
return null;
}
@Override
protected void onCancelled() {
super.onCancelled();
}
@Override
protected void onPreExecute() {
progress = ProgressDialog.show(
MainActivity.this, null, "Caricamento notizie...");
super.onPreExecute();
}
@Override
protected void onPostExecute(Void result) {
progress.dismiss();
super.onPostExecute(result);
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
最终解决方案:
private class GetNews extends AsyncTask<Void, Void, String>{
private ProgressDialog progress = null;
@Override
protected String doInBackground(Void... params) {
Looper.prepare(); //MUST BE ADDED
ReadServer read = new ReadServer();
String result = read.readserver("list_news","homepage");
System.out.println("DEBUG"+result);
return result;
}
@Override
protected void onCancelled() {
super.onCancelled();
}
@Override
protected void onPreExecute() {
progress = ProgressDialog.show(
MainActivity.this, null, "Caricamento notizie");
super.onPreExecute();
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String url_img = null;
String path = "http://www.MYFANTASTICPATH.it";
TableLayout MainTable = (TableLayout) findViewById(R.id.main_table);
JSONArray Jobj = new JSONArray(result);
for (int i = 0; i < Jobj.length(); i++) {
TableRow row = new TableRow(getApplicationContext());
row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
row.setPadding(0, 14, 2, 14);
JSONObject news_preview = Jobj.getJSONObject(i);
Integer news_id = news_preview.getInt("id_articolo");
String news_title = news_preview.getString("titolo");
String news_image = news_preview.getString("immagine");
// Check if image url is relative or absolute
Pattern p = Pattern.compile("^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]");
Matcher m = p.matcher(news_image);
if (m.matches() == false) {
url_img = path + news_image;
} else if (m.matches() == true) {
url_img = news_image;
}
// Call Html Parser to parse text
HtmlParser parsed_string = new HtmlParser();
Spanned title_nohtml = parsed_string.htmlparser(news_title);
// Thumb
ImageView img = new ImageView(getApplicationContext());
img.setAdjustViewBounds(true);
img.setMaxHeight(140);
img.setMaxWidth(140);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(url_img).getContent());
img.setImageBitmap(bitmap);
LayoutParams params = new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
// Clickable title
final TextView txt = new TextView(getApplicationContext());
txt.setGravity(Gravity.LEFT | Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
txt.setLayoutParams(params);
txt.setTextSize(18);
txt.setBackgroundColor(Color.WHITE);
txt.setTypeface(null, Typeface.BOLD);
txt.setTextColor(Color.BLACK);
txt.setId(news_id);
txt.setText(title_nohtml);
txt.setClickable(true);
row.addView(img);
row.addView(txt);
MainTable.addView(row);
txt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, OtherPages.class);
Bundle extras = new Bundle();
extras.putString("Boolean", "1");
extras.putInt("id_news", txt.getId());
intent.putExtras(extras);
startActivity(intent);
}
});
}
}catch (Exception e) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle("Si è verificato un errore");
alertDialog.setMessage("Errore 001" + "\n" + "Non è stato possibile soddisfare la tua richiesta, riprova più tardi.");
alertDialog.show();
}
progress.dismiss();
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
答案 0 :(得分:1)
ondoInbackground
你想在后台完成所有主要任务......
onPostexecute
显示doinbackground的所有结果
P.S:如果您想访问用户界面,请在onPostexecute
或onProgressupdate
答案 1 :(得分:0)
只需在任何想要使用它的地方书写。
GetNews getNewsTask = new GetNews().execute();
以下是Android开发者网站的文字。
在执行任务之前,在UI线程上调用onPreExecute()。此步骤通常用于设置任务,例如通过在用户界面中显示进度条。
在onPreExecute()完成执行后立即在后台线程上调用doInBackground(Params ...)。此步骤用于执行可能需要很长时间的后台计算。异步任务的参数将传递给此步骤。计算结果必须由此步骤返回,并将传递回最后一步。此步骤还可以使用publishProgress(Progress ...)发布一个或多个进度单元。这些值发布在UI线程的onProgressUpdate(Progress ...)步骤中。
调用publishProgress(Progress ...)后,在UI线程上调用onProgressUpdate(Progress ...)。执行的时间是不确定的。此方法用于在后台计算仍在执行时显示用户界面中的任何形式的进度。例如,它可用于为进度条设置动画或在文本字段中显示日志。
后台计算完成后,在UI线程上调用onPostExecute(Result)。后台计算的结果作为参数传递给此步骤。
参考:AsyncTask
答案 2 :(得分:0)
试试这个我编辑你的代码并准备一个如何使用asynctask的演示
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetNews getNews = new GetNews();
getNews.execute();
}
private class GetNews extends AsyncTask<Void, Void, String> {
private ProgressDialog progress = null;
@Override
protected String doInBackground(Void... params) {
ReadServer read = new ReadServer();
String result = read.readserver("list_news", "homepage");
return result;
}
@Override
protected void onCancelled() {
super.onCancelled();
}
@Override
protected void onPreExecute() {
progress = ProgressDialog.show(MainActivity.this, null, "Caricamento notizie...");
super.onPreExecute();
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String url_img = null;
String path = "MY FANTASTIC PATH";
/* READSERVER RETURN JSON STRING THAT CONTAIN SOME IMFORMATION */
ReadServer read = new ReadServer();
String result = read.readserver("list_news", "homepage");
TableLayout MainTable = (TableLayout) findViewById(R.id.main_table);
JSONArray Jobj = new JSONArray(result);
for (int i = 0; i < Jobj.length(); i++) {
TableRow row = new TableRow(getApplicationContext());
row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
row.setPadding(0, 14, 2, 14);
JSONObject news_preview = Jobj.getJSONObject(i);
Integer news_id = news_preview.getInt("id_articolo");
String news_title = news_preview.getString("titolo");
String news_image = news_preview.getString("immagine");
// Check if image url is relative or absolute
Pattern p = Pattern.compile("^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]");
Matcher m = p.matcher(news_image);
if (m.matches() == false) {
url_img = path + news_image;
} else if (m.matches() == true) {
url_img = news_image;
}
// Call Html Parser to parse text
HtmlParser parsed_string = new HtmlParser();
Spanned title_nohtml = parsed_string.htmlparser(news_title);
// Thumb
ImageView img = new ImageView(getApplicationContext());
img.setAdjustViewBounds(true);
img.setMaxHeight(140);
img.setMaxWidth(140);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(url_img).getContent());
img.setImageBitmap(bitmap);
LayoutParams params = new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
// Clickable title
final TextView txt = new TextView(getApplicationContext());
txt.setGravity(Gravity.LEFT | Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
txt.setLayoutParams(params);
txt.setTextSize(18);
txt.setBackgroundColor(Color.WHITE);
txt.setTypeface(null, Typeface.BOLD);
txt.setTextColor(Color.BLACK);
txt.setId(news_id);
txt.setText(title_nohtml);
txt.setClickable(true);
row.addView(img);
row.addView(txt);
MainTable.addView(row);
txt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, OtherPages.class);
Bundle extras = new Bundle();
extras.putString("Boolean", "1");
extras.putInt("id_news", txt.getId());
intent.putExtras(extras);
startActivity(intent);
}
});
}
} catch (Exception e) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle("Si è verificato un errore");
alertDialog.setMessage("Errore 001" + "\n" + "Non è stato possibile soddisfare la tua richiesta, riprova più tardi.");
alertDialog.show();
}
progress.dismiss();
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
答案 3 :(得分:0)
您应该在 doInBackground()中包含从数据库中提取数据的代码。此过程将在后台运行。由于您希望在信息回溯过程中显示进度条,因此您必须在 onProgressUpdate()中包含显示进度条的代码,该代码在 UI 主题上运行。您有从 doInBackground()手动调用 PublishProgres ,以通过 onProgressUpdate()发布一个或多个进度单元。在 onPreExecute()之后的后台线程上调用 doInBackground()。信息回溯后,您可以使用 onPostExecute() UI线程来显示数据。主要是异步任务用于执行与 UI 无关的后台线程的处理,而不是使用 UI
运行的主线程