0

In my android app I am trying to create a list and I need to display an image in each item list. I use Drawable to display the image from an URL. And I do this inside my ArrayAdapter. The app crashes and displays erros.

Below is my ArrayAdapter and the logcat. What is wrong with y code? Please help me. Thank you in advance!

package com.makemyandroidapp.example.stacksites;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.app.Activity;
import android.view.View.OnClickListener;
import android.content.Intent;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;

import android.view.View.OnClickListener;

/*
 * Custom Adapter class that is responsible for holding the list of sites after they
 * get parsed out of XML and building row views to display them on the screen.
 */
public class CategoryAdapter extends ArrayAdapter<StackSite> {

    //ImageLoader imageLoader;
    //DisplayImageOptions options;
    Context c;
    String url1;
    String url2;
Drawable backgr;
    public CategoryAdapter(Context ctx, int textViewResourceId, List<StackSite> sites) {
        super(ctx, textViewResourceId, sites);
        c=ctx;
        //Setup the ImageLoader, we'll use this to display our images
       // ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx).build();

       // imageLoader = ImageLoader.getInstance();
       // imageLoader.init(config);

        //Setup options for ImageLoader so it will handle caching for us.
       // options = new DisplayImageOptions.Builder()
        //.cacheInMemory()
        //.cacheOnDisc()
        //.build();


    }


    /*
     * (non-Javadoc)
     * @see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup)
     * 
     * This method is responsible for creating row views out of a StackSite object that can be put
     * into our ListView
     */
    @Override
    public View getView(int pos, View convertView, ViewGroup parent){
        RelativeLayout row = (RelativeLayout)convertView;
        Log.i("StackSites", "getView pos = " + pos);
        if(null == row){
            //No recycled View, we have to inflate one.
            LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = (RelativeLayout)inflater.inflate(R.layout.row_site, null);
        }

        //Get our View References
        final ImageView iconImg = (ImageView)row.findViewById(R.id.iconImg);
        final TextView kompaniaTxt = (TextView)row.findViewById(R.id.nameTxt);
        TextView pozicioniTxt = (TextView)row.findViewById(R.id.aboutTxt);
        final TextView kategoriaTxt = (TextView)row.findViewById(R.id.kategoriaTxt);
        TextView qytetiTxt = (TextView)row.findViewById(R.id.qytetiTxt);
        final ProgressBar indicator = (ProgressBar)row.findViewById(R.id.progress);


        kompaniaTxt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
//String emri_komp=kompaniaTxt.getText().toString().replaceAll("\\s+","%20");
String emri_komp=kompaniaTxt.getText().toString();

            Intent intent=new Intent(c,CompanyDesc.class);
             intent.putExtra("emri_komp", emri_komp);
             intent.putExtra("url1", url1); 
            c.startActivity(intent);


            }
        });
        kategoriaTxt.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
//String emri_komp=kompaniaTxt.getText().toString().replaceAll("\\s+","%20");
String idKateg=kategoriaTxt.getText().toString();

            Intent intent=new Intent(c,CategoryList.class);
             intent.putExtra("idKateg", idKateg);
             intent.putExtra("url2", url2); 
            c.startActivity(intent);


            }
        });
        //Initially we want the progress indicator visible, and the image invisible
        //indicator.setVisibility(View.VISIBLE);
        //iconImg.setVisibility(View.INVISIBLE);

        //Setup a listener we can use to swtich from the loading indicator to the Image once it's ready
//      ImageLoadingListener listener = new ImageLoadingListener(){
//
//
//
//          @Override
//          public void onLoadingStarted(String arg0, View arg1) {
//              // TODO Auto-generated method stub
//              
//          }
//
//          @Override
//          public void onLoadingCancelled(String arg0, View arg1) {
//              // TODO Auto-generated method stub
//              
//          }
//
//          @Override
//          public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
//              indicator.setVisibility(View.INVISIBLE);
//              iconImg.setVisibility(View.VISIBLE);
//          }
//
//          @Override
//          public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
//              // TODO Auto-generated method stub
//              
//          }
//          
//      };
//      
        //Load the image and use our options so caching is handled.
        //imageLoader.displayImage(getItem(pos).getImgUrl(), iconImg,options, listener);

        //Set the relavent text in our TextViews
        kompaniaTxt.setText(getItem(pos).getKompania());
        pozicioniTxt.setText(getItem(pos).getPozicioni());
        kategoriaTxt.setText(getItem(pos).getKategoria());
        qytetiTxt.setText(getItem(pos).getQyteti());
url1=getItem(pos).getImgUrl();
//url1=getItem(pos).getIdKategoria();
try {
    backgr=drawable_from_url(getItem(pos).getImgUrl(),"kot");

} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
iconImg.setBackground(backgr);


return row;


    }


    Drawable drawable_from_url(String url, String src_name) throws 
       java.net.MalformedURLException, java.io.IOException 
    {System.out.println("uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu");
       return Drawable.createFromStream(((java.io.InputStream)
          new java.net.URL(url.trim()).getContent()), src_name);

    }

}

Logcat:

05-12 01:13:07.011: E/AndroidRuntime(1665): FATAL EXCEPTION: main
05-12 01:13:07.011: E/AndroidRuntime(1665): Process: com.makemyandroidapp.example.stacksites, PID: 1665
05-12 01:13:07.011: E/AndroidRuntime(1665): android.os.NetworkOnMainThreadException
05-12 01:13:07.011: E/AndroidRuntime(1665):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
05-12 01:13:07.011: E/AndroidRuntime(1665):     at com.makemyandroidapp.example.stacksites.CategoryAdapter.drawable_from_url(CategoryAdapter.java:187)
05-12 01:13:07.011: E/AndroidRuntime(1665):     at com.makemyandroidapp.example.stacksites.CategoryAdapter.getView(CategoryAdapter.java:165)

Line number 187 is :

  new java.net.URL(url.trim()).getContent()), src_name);

Line number 165 is:

backgr=drawable_from_url(getItem(pos).getImgUrl(),"kot");
user3331949
  • 23
  • 1
  • 8

3 Answers3

0

Since you are already using the Android Universal Image Loader. Loading images from a url should be pretty easy. This will also work inside an adapter.

imageLoader.displayImage(imageUri, imageView);

In your case :

ImageLoader imageloader = ImageLoader.getInstance();
imageLoader.displayImage(url1, iconImg);
Shivam Verma
  • 7,973
  • 3
  • 26
  • 34
0

android.os.NetworkOnMainThreadException

You are performing network operation of fetching the image from the url on the main thread which is not allowed on android versions of Honeycomb and above. Use AsyncTask instead which will run your code in a separate thread in the background.

Vikram Gupta
  • 6,496
  • 5
  • 34
  • 47
0

This exception comes when u r trying to perform netwok operations in main thread which is recommended to do using AsyncTask.

But if our code is much and it looks tidy to manage code again.

Then add

StrictMode.ThreadPolicy policy = new   
                             StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy); 

inside onCreate() method.

It will your issue.

Please try and let me know

Neha Shukla
  • 3,572
  • 5
  • 38
  • 69