简体   繁体   中英

Why i can't see ImageView on my device?

I tried to understand why my variable result is null ? I check it with Debug but I don't understand why.. I don't see my ImageView in my device And here is my code :

public class ClassicView extends Activity {

private Content content;
public  LinearLayout view;
ClassicView classicView;
JSONParser jParser;
Context context;
private Bitmap bitmap;

private ImageView downloadedImg;
 private ProgressDialog simpleWaitDialog;
//RelativeLayout mainLayout;

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( new ViewGroup.MarginLayoutParams(
        RelativeLayout.LayoutParams.WRAP_CONTENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT));

public ClassicView() {

}
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        JSONParser jParser = null;
        try {
            jParser = new JSONParser("Json.txt");
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        content = (Content)getIntent().getSerializableExtra("CONTENT");


            //this.setClassicLabel(jParser.getContentViewWithId(content.getElemView()).getJSONArray("Label"));
            //(jParser.getContentViewWithId(content.getElemView()).getJSONArray("Img"));

        try {
            this.setClassicImg();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    public void setClassicLabel(JSONArray listLabel) throws JSONException {
        RelativeLayout rl = new RelativeLayout(this);
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        setContentView(rl);

        for (int i = 0; i < listLabel.length(); i++) {  
            TextView tv = new TextView(this);
            tv.setText(listLabel.getJSONObject(i).getString("text"));
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((int) (metrics.widthPixels * listLabel.getJSONObject(i).getDouble("size_x")), (int) (metrics.heightPixels * listLabel.getJSONObject(i).getDouble("size_y")));
            params.leftMargin = (int) (metrics.widthPixels * listLabel.getJSONObject(i).getDouble("position_x"));
            params.topMargin = (int) (metrics.heightPixels * listLabel.getJSONObject(i).getDouble("position_y"));
            rl.addView(tv, params);

        }
    }

    public void setClassicImg() throws JSONException, IOException, MalformedURLException {
        RelativeLayout rl2 = new RelativeLayout(this);
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        setContentView(rl2);
        ImageView downloadedImg = new ImageView(this);
        new DownloadImageTask(downloadedImg).execute("http://felicita-pizzeria.fr/images/logo.png");
        }





/* To Load Image */


    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView myimage;

        public DownloadImageTask(ImageView bmImage) {
            this.myimage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {
            myimage.setImageBitmap(result);
        }
    }`

Somebody can help me please ? thank you

It's null because downloadedImg you pass to task constructor is null. Your code shows no code how you find that ImageView, but most likely you either look for imageView that does not exist in that layout or you forgot to do that completely.

Its giving nullpointer exception because you might have forget to initialize the ImageView which you are passing as parameter in your new DownloadImageTask(downloadedImg).execute(..);

Make sure you have initialized your ImageView in your class.

 ImageView downloadedImg =new ImageView(this);

Use the below code to download the image from url:

private Bitmap downloadBitmap(String url) {
     // initilize the default HTTP client object
     final DefaultHttpClient client = new DefaultHttpClient();

     //forming a HttoGet request 
     final HttpGet getRequest = new HttpGet(url);
     try {

         HttpResponse response = client.execute(getRequest);
             //check 200 OK for success
         final int statusCode = response.getStatusLine().getStatusCode();

         if (statusCode != HttpStatus.SC_OK) {
             Log.w("ImageDownloader", "Error " + statusCode + 
                     " while retrieving bitmap from " + url);
             return null;

         }

         final HttpEntity entity = response.getEntity();
         if (entity != null) {
             InputStream inputStream = null;
             try {
                 // getting contents from the stream 
                 inputStream = entity.getContent();

                 // decoding stream data back into image Bitmap that android understands
                 image = BitmapFactory.decodeStream(inputStream);


             } finally {
                 if (inputStream != null) {
                     inputStream.close();
                 }
                 entity.consumeContent();
             }
         }
     } catch (Exception e) {

         Log.e("ImageDownloader", "Something went wrong while" +
                 " retrieving bitmap from " + url + e.toString());
     } 

     return image;
 }

Change your code as below:

  private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView myimage;

    public DownloadImageTask(ImageView bmImage) {
        this.myimage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
                   mIcon11 = downloadBitmap(urldisplay);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        myimage.setImageBitmap(result);
    }
}

EDITED:

Here is my code which i have tried and which works like charm.

public class MainActivity extends Activity {

    Bitmap image;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImageView mm=new ImageView(getApplicationContext());

        new DownloadImageTask(mm).execute("http://felicita-pizzeria.fr/images/logo.png");
        setContentView(mm);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private Bitmap downloadBitmap(String url) {
         // initilize the default HTTP client object
         final DefaultHttpClient client = new DefaultHttpClient();

         //forming a HttoGet request 
         final HttpGet getRequest = new HttpGet(url);
         try {

             HttpResponse response = client.execute(getRequest);
                 //check 200 OK for success
             final int statusCode = response.getStatusLine().getStatusCode();

             if (statusCode != HttpStatus.SC_OK) {
                 Log.w("ImageDownloader", "Error " + statusCode + 
                         " while retrieving bitmap from " + url);
                 return null;

             }

             final HttpEntity entity = response.getEntity();
             if (entity != null) {
                 InputStream inputStream = null;
                 try {
                     // getting contents from the stream 
                     inputStream = entity.getContent();

                     // decoding stream data back into image Bitmap that android understands
                     image = BitmapFactory.decodeStream(inputStream);


                 } finally {
                     if (inputStream != null) {
                         inputStream.close();
                     }
                     entity.consumeContent();
                 }
             }
         } catch (Exception e) {

             Log.e("ImageDownloader", "Something went wrong while" +
                     " retrieving bitmap from " + url + e.toString());
         } 

         return image;
     }

     private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
            ImageView myimage;

            public DownloadImageTask(ImageView bmImage) {
                this.myimage = bmImage;
            }

            protected Bitmap doInBackground(String... urls) {


        String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                       mIcon11 = downloadBitmap(urldisplay);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {
            myimage.setImageBitmap(result);
        }
    }

}

Output:

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM