json 如何在Android应用程序中使用AsyncTask

wkftcu5l  于 2023-04-08  发布在  Android
关注(0)|答案(4)|浏览(121)

我正在开发一个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);
    }
   }
wbgh16ku

wbgh16ku1#

ondoInbackground你想在后台完成所有的主要任务。
onPostexecute你显示所有的结果从doinbackground
P.S:如果你想访问UI,在onPostexecuteonProgressupdate中进行

uklbhaso

uklbhaso2#

试试这个我编辑你的代码,并准备一个演示,如何使用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);
        }
    }

}
yyhrrdl8

yyhrrdl83#

你应该在doInBackground中包含从数据库中获取数据的代码().此过程将在后台运行,由于您希望在检索信息时显示进度条,因此必须在onProgressUpdate中包含显示进度条的代码()运行在UI线程上,需要在doInBackground手动调用PublishProgres**()通过onProgressUpdate发布一个或多个进度单元().doInBackground()onPreExecute之后在后台线程上调用().信息检索后,可以使用onPostExecute显示数据()UI线程**,主要是异步任务在与UI无关的后台线程上进行处理,而不是在主线程上运行*用户界面

yiytaume

yiytaume4#

只要写在任何你想使用它。

GetNews getNewsTask = new GetNews().execute();

以下是Android开发者网站的文字。

**onPreExecute()**在任务执行前在UI线程上调用,此步骤通常用于设置任务,例如在用户界面中显示进度条。
**doInBackground(Params...)**在onPreExecute之后立即在后台线程上调用()完成执行。此步骤用于执行可能需要很长时间的后台计算。异步任务的参数传递给此步骤。计算的结果必须由此步骤返回,并将传回到上一步骤。此步骤也可以使用publishProgress(Progress...)发布一个或多个进度单元。这些值在UI线程上的onProgressUpdate(Progress...)步骤中发布。
**onProgressUpdate(Progress...)**调用publishProgress(Progress...)后在UI线程上调用,执行时间未定义。此方法用于在后台计算仍在执行的情况下,在用户界面上显示任何形式的进度。例如,可用于动画进度条或在文本字段中显示日志。
**onPostExecute(Result)**后台计算完成后在UI线程上调用,后台计算的结果作为参数传入本步骤。

来源:AsyncTask

相关问题