java - 从php mysql循环加载图像时对话框不断出现

标签 java android mysql

这是我的 java 代码,用于在循环中通过 Php 从 Mysql 加载标题、描述、日期和图像。除图像外,一切都完美加载。当我加载图像时,加载对话框显示,我只能在背景中看到一张图像,但加载对话框仍在出现。我是 android 新手,所以我需要像您这样的专家帮助。

Java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class News_events extends Fragment {
    private String jsonResult;
     private String url = "http://192.168.2.7/crescentnews/select.php";
     HttpPost httppost;
     StringBuffer buffer;
     HttpResponse response;
     HttpClient httpclient;
     List<NameValuePair> nameValuePairs;
     ProgressDialog dialog = null;
     ImageView img;
      Bitmap bitmap;
      ProgressDialog pDialog;


     InputStream is=null;
     String result=null;
        String line=null;
        int code;

    public News_events(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_news_events, container, false);
        accessWebService();


        return rootView;
    }

    // Async Task to access the web
     private class JsonReadTask extends AsyncTask<String, Void, String> {
      @Override
      protected String doInBackground(String... params) { 
          List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);


       HttpClient httpclient = new DefaultHttpClient();
       HttpPost httppost = new HttpPost(params[0]);
       try {

           httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
        HttpResponse response = httpclient.execute(httppost); 
        jsonResult = inputStreamToString(
          response.getEntity().getContent()).toString();
        }

       catch (ClientProtocolException e) {
        e.printStackTrace();
       } catch (IOException e) {
        e.printStackTrace();
       }
       return null;
      }

      private StringBuilder inputStreamToString(InputStream is) {
       String rLine = "";
       StringBuilder answer = new StringBuilder();
       BufferedReader rd = new BufferedReader(new InputStreamReader(is));

       try {
        while ((rLine = rd.readLine()) != null) {
         answer.append(rLine);
        }
       }
        catch (IOException e) {
        // e.printStackTrace();
        Toast.makeText(getActivity().getApplicationContext(),
          "Error..." + e.toString(), Toast.LENGTH_LONG).show();
       }
       return answer;
      }

      @Override
      protected void onPostExecute(String result) {
       display();
      }
     }// end async task

     public void accessWebService() {
      JsonReadTask task = new JsonReadTask();
      // passes values for the urls string array
      task.execute(new String[] { url });
     }

     // build hash set for list view
     public void display() {


      try {
       JSONObject jsonResponse = new JSONObject(jsonResult);
       JSONArray jsonMainNode = jsonResponse.optJSONArray("news_details");
       LinearLayout MainLL= (LinearLayout)getActivity().findViewById(R.id.newslayout); 
       //LinearLayout headLN=(LinearLayout)findViewById(R.id.headsection);

       for (int i = 0; i < jsonMainNode.length(); i++) {
           JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
            final String head = jsonChildNode.optString("title");
            final String details = jsonChildNode.optString("text");
            final String date = jsonChildNode.optString("date");
            final String image = jsonChildNode.optString("img");
            //final String time = jsonChildNode.optString("time");
            //img = new ImageView(this.getActivity());
            //new LoadImage().execute("http://192.168.2.7/crescentnews/images/"+image);

            img = new ImageView(this.getActivity());
            LoadImage ldimg=new LoadImage();
            ldimg.setImage(img);
            ldimg.execute("http://192.168.2.7/crescentnews/images/"+image);


            TextView headln = new TextView(this.getActivity());
            headln.setText(head); // News Headlines
            headln.setTextSize(20);
            headln.setTextColor(Color.BLACK);
            headln.setGravity(Gravity.CENTER);
            headln.setBackgroundResource(R.drawable.menubg);
            headln.setPadding(10, 20, 10, 0);
            headln.setWidth(100);
            headln.setClickable(true);
            headln.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    //Toast.makeText(getBaseContext(), head, Toast.LENGTH_SHORT).show();
                   Intent intent = new Intent(getActivity().getApplicationContext(),MainActivity.class);
                   intent.putExtra("head",head.toString());
                   intent.putExtra("details",details.toString());
                   intent.putExtra("date",date.toString());
                  // intent.putExtra("time",time.toString());
                   startActivity(intent);       
                }
            });

            ImageView photo=new ImageView(this.getActivity());
            //dateln.setBackgroundColor(Color.parseColor("#f20056"));
            photo.setBackgroundColor(Color.parseColor("#000000"));
            photo.setPadding(0, 0, 10, 10);
            photo.setClickable(true);



           // Drawable drawable = LoadImageFromWebOperations("http://192.168.2.7/crescentnews/images/"+pic);
           // userpic.setImageDrawable(drawable);




            TextView dateln = new TextView(this.getActivity());
            dateln.setText(date); // News Headlines
            dateln.setTextSize(12);
            dateln.setTextColor(Color.BLACK);
            dateln.setGravity(Gravity.RIGHT);
            //dateln.setBackgroundColor(Color.parseColor("#f20056"));
            dateln.setBackgroundColor(0x00000000);
            dateln.setPadding(0, 0, 10, 10);
            dateln.setWidth(100);
            dateln.setClickable(true);
            dateln.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                   // TODO Auto-generated method stub
                     Intent intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
                       intent.putExtra("head",head.toString());
                       intent.putExtra("details",details.toString());
                       intent.putExtra("date",date.toString());
                      // intent.putExtra("time",time.toString());
                       startActivity(intent);         
                }
            });

            View sep=new View(this.getActivity());
            sep.setBackgroundColor(Color.parseColor("#252525"));
            sep.setMinimumHeight(10);

            TextView detailsln = new TextView(this.getActivity());
            detailsln.setText(details); // News Details
            detailsln.setTextSize(12);
            detailsln.setTextColor(Color.BLACK);
            detailsln.setGravity(Gravity.LEFT);
            detailsln.setPadding(10, 10, 10, 10);
            MainLL.addView(headln);
            MainLL.addView(dateln);
            MainLL.addView(photo);
            MainLL.addView(img);
            MainLL.addView(detailsln);
            MainLL.addView(sep);


            detailsln.setClickable(true);
            detailsln.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                    // TODO Auto-generated method stub

            Intent intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
            intent.putExtra("head",head.toString());
            intent.putExtra("details",details.toString());
            intent.putExtra("date",date.toString());
            // intent.putExtra("time",time.toString());
            startActivity(intent);      
                }
            });

       }
      } catch (JSONException e) {
       Toast.makeText(getActivity().getApplicationContext(), "Error" + e.toString(),
         Toast.LENGTH_SHORT).show();
      }
       }

     private class LoadImage extends AsyncTask<String, String, Bitmap> {
         ImageView img;
                     @Override
                         protected void onPreExecute() {
                             super.onPreExecute();
                             pDialog = new ProgressDialog(getActivity());
                             pDialog.setMessage("Loading Image ....");
                             pDialog.show();


                     }
         public void setImage(ImageView img ){
         this.img=img;
         }

         protected Bitmap doInBackground(String... args) {
             try {
                 bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).openStream());
                 } 
             catch (Exception e) { e.printStackTrace(); }
             return bitmap;
         }

         protected void onPostExecute(Bitmap image) {
              if(image != null){
                  img.setImageBitmap(image);
                  pDialog = new ProgressDialog(getActivity());
                  pDialog.dismiss(); 
              }
              pDialog.dismiss(); 
         } 

     }

最佳答案

您的代码似乎没问题。

还要检查一些选项,例如 volley

尝试以下内容

private class LoadImage extends AsyncTask<String, String, Bitmap> {
ImageView img;
            @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    pDialog = new ProgressDialog(getActivity());
                    pDialog.setMessage("Loading Image ....");
                    pDialog.show();
            }
public void setImage(ImageView img ){
this.img=img;
}
               protected Bitmap doInBackground(String... args) {
              try {
                   bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).openStream());
            } catch (Exception e) {
                  e.printStackTrace();
            }
              return bitmap;
               }
               protected void onPostExecute(Bitmap image) {
                if(image != null){
                   img.setImageBitmap(image);

                   }
 pDialog.dismiss(); 
               }
}

调用这个

img = new ImageView(this.getActivity());
LoadImage ldimg=new LoadImage();
ldimg.setImage(img);
 ldimg.execute("http://192.168.2.7/crescentnews/images/"+image);

解雇dialog显示 dialogfor loop 之前只有一次并在 for loop 之后关闭它

希望对你有帮助:)

关于java - 从php mysql循环加载图像时对话框不断出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27653480/

相关文章:

java - 面板不会显示文本

java - 将 5 位整数转换为列

java - 当我使用 Genymotion 模拟器运行我的第一个 Android 应用程序时,不幸的是,它给出的错误 "app name"已经停止。请帮我

Android多列ListView

java - 如何使用 mysql 日期时间列处理 java 日期

mysql - 我将如何加入这些表格?

java - 无法在 Jboss EAP 7.0 服务器中创建 oracle 数据源

java - 为什么 Eclipse 看不到库的 .jar 文件?

java - 我的应用程序在我的设备上占用了 250mb 内存。当我进行堆转储并对其进行分析时。它说堆大小约为 7mb

php - Yii CDbCriteria 添加不需要的别名