Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/204.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Android应用程序中使用AsyncTask_Android_Json_Database_Android Asynctask - Fatal编程技术网

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

如何在Android应用程序中使用AsyncTask,android,json,database,android-asynctask,Android,Json,Database,Android Asynctask,我正在为android开发一个应用程序,我的问题是AsyncTask的实现,我必须做的是“简单”: 这部分函数用于从数据库获取信息,数据加载后,信息显示在表中,我将实现一个函数,允许我在检索信息时显示进度条(读取服务器) 试试看{ 字符串url\u img=null; String path=“我的奇妙之路”; /*READSERVER返回包含某些信息的JSON字符串*/ ReadServer read=new ReadServer(); 字符串结果=read.readserver(“列表新闻”

我正在为android开发一个应用程序,我的问题是AsyncTask的实现,我必须做的是“简单”:

这部分函数用于从数据库获取信息,数据加载后,信息显示在表中,我将实现一个函数,允许我在检索信息时显示进度条(读取服务器)

试试看{
字符串url\u img=null;
String path=“我的奇妙之路”;
/*READSERVER返回包含某些信息的JSON字符串*/
ReadServer read=new ReadServer();
字符串结果=read.readserver(“列表新闻”、“主页”);
TableLayout MainTable=(TableLayout)findViewById(R.id.main_table);
JSONArray Jobj=新JSONArray(结果);
对于(int i=0;i
我知道我必须使用这个代码,但我不知道如何实现,有人能帮我吗

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);
       }
      }
GetNews getNewsTask=new GetNews().execute();
私有类GetNews扩展异步任务{
private ProgressDialog progress=null;
@凌驾
受保护的Void doInBackground(Void…参数){
//做点什么
返回null;
}
@凌驾
受保护的void onCancelled(){
super.onCancelled();
}
@凌驾
受保护的void onPreExecute(){
progress=ProgressDialog.show(
MainActivity.this,null,“Caricamento notizie…”);
super.onPreExecute();
}
@凌驾
受保护的void onPostExecute(void结果){
进步。解散();
super.onPostExecute(结果);
}
@凌驾
受保护的void onProgressUpdate(void…值){
super.onProgressUpdate(值);
}
}
最终解决方案:

 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);
    }
   }
私有类GetNews扩展异步任务{
private ProgressDialog progress=null;
@凌驾
受保护字符串doInBackground(无效…参数){
Looper.prepare();//必须添加
ReadServer read=new ReadServer();
字符串结果=read.readserver(“列表新闻”、“主页”);
System.out.println(“调试”+结果);
返回结果;
}
@凌驾
受保护的void onCancelled(){
super.onCancelled();
}
@凌驾
受保护的void onPreExecute(){
progress=ProgressDialog.show(
MainActivity.this,null,“Caricamento notizie”);
super.onPreExecute();
}
@凌驾
受保护的void onPostExecute(字符串结果){
super.onPostExecute(结果);
试一试{
字符串url\u img=null;
字符串路径=”http://www.MYFANTASTICPATH.it";
TableLayout MainTable=(TableLayout)findViewById(R.id.main_table);
JSONArray Jobj=新JSONArray(结果);
对于(int i=0;i 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);
    }
   }
GetNews getNewsTask = new GetNews().execute();
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);
        }
    }

}