Search code examples
androidlistviewandroid-arrayadapter

Not able to see ListView


i didn't see any data in listView i get all data from web-service but i didn't see it inside ListView. I get flow and i understand it never go inside getView() method Please explain me what's wrong going in that code and suggest me best-one.

public class WeatherReport extends Activity {

    ListView listView;
    GPS_Location gpsObj;
    BaseAdapter aAdapter;
    double Latitude, Longitude;
    Bitmap image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.weather_report);
        listView = (ListView) findViewById(R.id.listView);
        gpsObj = new GPS_Location(this);
        Latitude = gpsObj.getLatitude();
        Longitude = gpsObj.getLongitude();
        System.out.println("Inside onCreate() ");
        String Url = "http://api.openweathermap.org/data/2.5/forecast/daily?lat=" + Latitude + "&lon=" + Longitude + "&cnt=14&mode=json";
        new getJSON().execute(Url);
        //  listView.setAdapter(new BAdapter(this));
    }

    private class getJSON extends AsyncTask<String, String, String> {
        String cityName;
        String Latitude, Longitude;
        ArrayList<SingleRow> list;
        ArrayList<String> humidity;
        ArrayList<String> speed;
        ArrayList<String> weather;
        ArrayList<String> tempMin;
        ArrayList<String> tempMax;
        ArrayList<String> description;
        ArrayList<Bitmap> icon;

        @Override
        protected String doInBackground(String... params) {
            String Url = params[0];
            humidity = new ArrayList<String>();
            speed = new ArrayList<String>();
            weather = new ArrayList<String>();
            tempMin = new ArrayList<String>();
            tempMax = new ArrayList<String>();
            icon = new ArrayList<Bitmap>();
            description = new ArrayList<String>();
            String data;
            try {
                HttpClient hClient = new DefaultHttpClient();
                HttpGet hGet = new HttpGet(Url);
                ResponseHandler<String> rHandler = new BasicResponseHandler();
                data = hClient.execute(hGet, rHandler);
                System.out.println("Inside doInBackground  data " + data);
                JSONObject jObj = new JSONObject(data);
                System.out.println("Inside Background jObj " + jObj);
                JSONObject jsonObject = jObj.getJSONObject("city");
                cityName = jsonObject.getString("name");
                JSONObject jObjCoOrd = jsonObject.getJSONObject("coord");
                Latitude = jObjCoOrd.getString("lat");
                System.out.println("Inside Latitude " + Latitude);
                Longitude = jObjCoOrd.getString("lon");
                System.out.println("Inside Longitude " + Longitude);

                JSONArray jsonArray = jObj.getJSONArray("list");
                System.out.println("Inside jsonObjList " + jsonArray);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject object = jsonArray.getJSONObject(i);

                    String humidityString = object.getString("humidity");
                    humidity.add(humidityString);
                    String speedString = object.getString("speed");
                    System.out.println("Inside speedString " + speedString);
                    speed.add(speedString);

                    JSONArray weatherArray = object.getJSONArray("weather");
                    JSONObject weatherObj = weatherArray.getJSONObject(0);

                    String iconString = weatherObj.getString("icon");
                    final String iconURL = "http://openweathermap.org/img/w/" + iconString + ".png";
                    image = getImage(iconURL);
                    icon.add(image);
                    System.out.println("Inside icon " + icon);
                    String descriptionString = weatherObj.getString("description");
                    System.out.println("Inside descriptionString " + descriptionString);
                    description.add(descriptionString);

                    JSONObject tempObj = object.getJSONObject("temp");

                    String minTemp = tempObj.getString("min");
                    System.out.println("Inside minTemp " + minTemp);
                    tempMin.add(minTemp);

                    String maxTemp = tempObj.getString("max");
                    System.out.println("Inside maxTemp " + maxTemp);
                    tempMax.add(maxTemp);
                }

                aAdapter = new ListViewCustomAdapter(WeatherReport.this,
                        Latitude, Longitude, cityName, humidity, speed, icon, description, tempMin, tempMax);
                listView.setAdapter(aAdapter);

            } catch (Exception e) {
                Log.w("Error", e.getMessage());
            }
            return null;
        }

        private Bitmap getImage(String iconURL) {
            InputStream in = null;
            Bitmap bmp = null;
            int responseCode = -1;
            try {

                URL url = new URL(iconURL);//"http://192.xx.xx.xx/mypath/img1.jpg
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setDoInput(true);
                con.connect();
                responseCode = con.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    //download
                    in = con.getInputStream();
                    bmp = BitmapFactory.decodeStream(in);
                    in.close();
                }

            } catch (Exception ex) {
                Log.e("Exception", ex.toString());
            }


            return bmp;
        }

        private class ListViewCustomAdapter extends BaseAdapter {
            Context context;
            public LayoutInflater inflater;
            String Latitude, Longitude, cityName;
            String[] Humidity, Speed, Description1, minTemp, maxTemp ;
            ArrayList<Bitmap> bitmap;


            public ListViewCustomAdapter(Context context, String latitude, String longitude, String cityName, ArrayList<String> humidity, ArrayList<String> speed, ArrayList<Bitmap> image, ArrayList<String> description, ArrayList<String> tempMin, ArrayList<String> tempMax) {
                this.context = context;
                this.Latitude = latitude;
                this.Longitude = longitude;
                this.cityName = cityName;
                this.bitmap = icon;
                this.Humidity = humidity.toArray(new String[humidity.size()]);
                this.Speed = speed.toArray(new String[speed.size()]);
                this.Description1 = description.toArray(new String[description.size()]);
                this.minTemp = tempMin.toArray(new String[tempMin.size()]);
                this.maxTemp = tempMax.toArray(new String[tempMax.size()]);
                this.inflater = (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                System.out.println("Inside ListViewCustomAdapter ");
            }

            @Override
            public int getCount() {
                return 0;
            }

            @Override
            public Object getItem(int i) {
                return i;
            }

            @Override
            public long getItemId(int i) {
                return i;
            }

            private class Holder {
                TextView City, MinTemp, MaxTemp, Description, Speed, Latitude, Longitude, Humidity;
                ImageView cloud;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                Holder holder= null;
                View view = convertView;
                System.out.println("Inside getView");
                if(view== null){
                    System.out.println("Inside if getView");
                    holder = new Holder();
                    convertView = inflater.inflate(R.layout.weather_report_single_item, null);
                    holder.cloud = (ImageView) findViewById(R.id.cloud);
                    holder.City = (TextView) findViewById(R.id.cityName);
                    holder.MinTemp= (TextView) findViewById(R.id.minTemp);
                    holder.MaxTemp= (TextView) findViewById(R.id.maxTemp);
                    holder.Description=(TextView) findViewById(R.id.weather);
                    holder.Speed =(TextView) findViewById(R.id.speed);
                    holder.Latitude = (TextView) findViewById(R.id.latitude);
                    holder.Longitude= (TextView) findViewById(R.id.longitude);
                    holder.Humidity= (TextView) findViewById(R.id.humidity);

                    convertView.setTag(holder);
                }else{
                    System.out.println("Inside else getView");
                    holder = (Holder) convertView.getTag();
                    holder.City.setText(cityName);
                    holder.Latitude.setText(Latitude);
                    holder.Longitude.setText(Longitude);
                    holder.MaxTemp.setText(maxTemp[position]);
                    holder.MinTemp.setText(minTemp[position]);
                    holder.Speed.setText(Speed[position]);
                    holder.Description.setText(Description1[position]);
                    holder.cloud.setImageBitmap(bitmap.get(position));
                }

                return convertView;
            }
        }
    }
}

class SingleRow {
    String minTemp, maxTemp, speed, humidity;
    Bitmap img;

    SingleRow(String minTemp, String maxTemp, String speed, String humidity, Bitmap img) {

        this.maxTemp = maxTemp;
        this.minTemp = minTemp;
        this.speed = speed;
        this.humidity = humidity;
        this.img = img;
    }

}

Solution

  • give length of the records which is going to be display .. give array/collection length in get count method

    Check the below code for adapter . Added comment also where u made mistakes and suggestions also

    Set the listview adapter and all in async task onPostExecute method.

    EDITED Check the suggestions i hve marked with with #### SUGGESTION

    enter image description here

    public class WeatherReport extends Activity {
    
        ListView listView;
        // GPS_Location gpsObj;
        // BaseAdapter aAdapter;
        double Latitude, Longitude;
        Bitmap image;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.listview_);
            listView = (ListView) findViewById(R.id.listdata);
            // gpsObj = new GPS_Location(this);
            /*
             * For testing i gve static lat long values as i dnt hve your
             * GPS_Location class
             */
            Latitude = 23;
            Longitude = 73;
            System.out.println("Inside onCreate() ");
            String Url = "http://api.openweathermap.org/data/2.5/forecast/daily?lat="
                    + Latitude + "&lon=" + Longitude + "&cnt=14&mode=json";
            new getJSON().execute(Url);
            // listView.setAdapter(new BAdapter(this));
        }
    
        private class getJSON extends AsyncTask<String, String, String> {
            String cityName;
            String Latitude, Longitude;
            ArrayList<SingleRow> list;
            ArrayList<String> humidity;
            ArrayList<String> speed;
            ArrayList<String> weather;
            ArrayList<String> tempMin;
            ArrayList<String> tempMax;
            ArrayList<String> description;
            ArrayList<String> icon;
    
            @Override
            protected void onPostExecute(String result) {
                // TODO Auto-generated method stub
                super.onPostExecute(result);
                listView.setAdapter(new ListViewCustomAdapter(WeatherReport.this,
                        Latitude, Longitude, cityName, humidity, speed, icon,
                        description, tempMin, tempMax));
            }
    
            @Override
            protected String doInBackground(String... params) {
                String Url = params[0];
                humidity = new ArrayList<String>();
                speed = new ArrayList<String>();
                weather = new ArrayList<String>();
                tempMin = new ArrayList<String>();
                tempMax = new ArrayList<String>();
                icon = new ArrayList<String>();
                description = new ArrayList<String>();
                String data;
                try {
                    HttpClient hClient = new DefaultHttpClient();
                    HttpGet hGet = new HttpGet(Url);
                    ResponseHandler<String> rHandler = new BasicResponseHandler();
                    data = hClient.execute(hGet, rHandler);
                    System.out.println("Inside doInBackground  data " + data);
                    JSONObject jObj = new JSONObject(data);
                    System.out.println("Inside Background jObj " + jObj);
                    JSONObject jsonObject = jObj.getJSONObject("city");
                    cityName = jsonObject.getString("name");
                    JSONObject jObjCoOrd = jsonObject.getJSONObject("coord");
                    Latitude = jObjCoOrd.getString("lat");
                    System.out.println("Inside Latitude " + Latitude);
                    Longitude = jObjCoOrd.getString("lon");
                    System.out.println("Inside Longitude " + Longitude);
    
                    JSONArray jsonArray = jObj.getJSONArray("list");
                    System.out.println("Inside jsonObjList " + jsonArray);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);
    
                        String humidityString = object.getString("humidity");
                        humidity.add(humidityString);
                        String speedString = object.getString("speed");
                        System.out.println("Inside speedString " + speedString);
                        speed.add(speedString);
    
                        JSONArray weatherArray = object.getJSONArray("weather");
                        JSONObject weatherObj = weatherArray.getJSONObject(0);
    
                        String iconString = weatherObj.getString("icon");
                        final String iconURL = "http://openweathermap.org/img/w/"
                                + iconString + ".png";
                        // #### SUGGESTION
    
                        // Do not Download images or files like this
                        // to display images use imageloader lazy loading library is
                        // available
    
                        // https://github.com/nostra13/Android-Universal-Image-Loader/tree/master/sample
    
                        // Comment image downloading related below line and once
                        // check
    
                        // image = getImage(iconURL);
                        // icon.add(image);
    
                        // here other change i hve made is converty bitmap array
                        // list to String which will hve images url not bitmap
                        icon.add(iconURL);
                        System.out.println("Inside icon " + icon);
                        String descriptionString = weatherObj
                                .getString("description");
                        System.out.println("Inside descriptionString "
                                + descriptionString);
                        description.add(descriptionString);
    
                        JSONObject tempObj = object.getJSONObject("temp");
    
                        String minTemp = tempObj.getString("min");
                        System.out.println("Inside minTemp " + minTemp);
                        tempMin.add(minTemp);
    
                        String maxTemp = tempObj.getString("max");
                        System.out.println("Inside maxTemp " + maxTemp);
                        tempMax.add(maxTemp);
                    }
    
                    // If u do any ui related changes here below exception will come
                    // so need to move ui changes in onPostExecute
    
                    // android.view.ViewRootImpl$CalledFromWrongThreadException:
                    // Only the original thread that created a view hierarchy can
                    // touch its views.
    
                    // listView.setAdapter(new ListViewCustomAdapter(
                    // WeatherReport.this, Latitude, Longitude, cityName,
                    // humidity, speed, icon, description, tempMin, tempMax));
    
                } catch (Exception e) {
                    Log.w("Error", e.getMessage());
                }
                return null;
            }
    
            private Bitmap getImage(String iconURL) {
                InputStream in = null;
                Bitmap bmp = null;
                int responseCode = -1;
                try {
    
                    URL url = new URL(iconURL);// "http://192.xx.xx.xx/mypath/img1.jpg
                    HttpURLConnection con = (HttpURLConnection) url
                            .openConnection();
                    con.setDoInput(true);
                    con.connect();
                    responseCode = con.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        // download
                        in = con.getInputStream();
                        bmp = BitmapFactory.decodeStream(in);
                        in.close();
                    }
    
                } catch (Exception ex) {
                    Log.e("Exception", ex.toString());
                }
    
                return bmp;
            }
    
            private class ListViewCustomAdapter extends BaseAdapter {
                Context context;
                public LayoutInflater inflater;
                String Latitude, Longitude, cityName;
                String[] Humidity, Speed, Description1, minTemp, maxTemp;
                ArrayList<String> bitmap;
                int totalDisplayDatasize = 0;
    
                public ListViewCustomAdapter(Context context, String latitude,
                        String longitude, String cityName,
                        ArrayList<String> humidity, ArrayList<String> speed,
                        ArrayList<String> image, ArrayList<String> description,
                        ArrayList<String> tempMin, ArrayList<String> tempMax) {
                    this.context = context;
                    this.Latitude = latitude;
                    this.Longitude = longitude;
                    this.cityName = cityName;
                    this.bitmap = icon;
                    this.Humidity = humidity.toArray(new String[humidity.size()]);
                    this.Speed = speed.toArray(new String[speed.size()]);
                    this.Description1 = description.toArray(new String[description
                            .size()]);
                    this.minTemp = tempMin.toArray(new String[tempMin.size()]);
                    this.maxTemp = tempMax.toArray(new String[tempMax.size()]);
                    // /suggestion : No need to create LayoutInflater instance in
                    // constructor
                    // this.inflater = (LayoutInflater) context
                    // .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    
                    /**
                     * set total data length for count
                     * */
                    if (this.Humidity != null)
                        totalDisplayDatasize = this.Humidity.length;
                    System.out.println("Inside ListViewCustomAdapter ");
                }
    
                @Override
                public int getCount() {
                    // this could be one of the reason for not showing listview.set
                    // total data length for count
                    return totalDisplayDatasize;
                }
    
                @Override
                public Object getItem(int i) {
                    return i;
                }
    
                @Override
                public long getItemId(int i) {
                    return i;
                }
    
                private class Holder {
                    TextView City, MinTemp, MaxTemp, Description, Speed, Latitude,
                            Longitude, Humidity;
                    ImageView cloud;
                }
    
                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    Holder holder = null;
                    View view = convertView;
                    System.out.println("Inside getView");
                    if (view == null) {
                        System.out.println("Inside if getView");
                        holder = new Holder();
                        // / No need to create LayoutInflater instance in
                        // constructor
    
                        convertView = LayoutInflater.from(this.context).inflate(
                                R.layout.list_row_data, null);
                        // Create instance from convertview.findviewbyid instead of
                        // directly using findViewById
                        // holder.cloud = (ImageView) convertView
                        // .findViewById(R.id.cloud);
                        // holder.City = (TextView) convertView
                        // .findViewById(R.id.cityName);
                        holder.MinTemp = (TextView) convertView
                                .findViewById(R.id.minTemp);
                        holder.MaxTemp = (TextView) convertView
                                .findViewById(R.id.maxTemp);
                        holder.Description = (TextView) convertView
                                .findViewById(R.id.weather);
                        holder.Speed = (TextView) convertView
                                .findViewById(R.id.speed);
                        holder.Latitude = (TextView) convertView
                                .findViewById(R.id.latitude);
                        holder.Longitude = (TextView) convertView
                                .findViewById(R.id.longitude);
    
                        convertView.setTag(holder);
                    } else {
                        System.out.println("Inside else getView");
                        holder = (Holder) convertView.getTag();
    
                    }// set values here for each row
    
                    // holder.City.setText(cityName);
                    holder.Latitude.setText("Lat : " + Latitude);
                    holder.Longitude.setText("Long : " + Longitude);
                    holder.MaxTemp.setText("maxTemp : " + maxTemp[position]);
                    holder.MinTemp.setText("minTemp : " + minTemp[position]);
                    holder.Speed.setText("Speed : " + Speed[position]);
                    holder.Description.setText("Description : "
                            + Description1[position]);
                    // #### SUGGESTION
    
                    // TO display image use ImageLoader which will download image in
                    // background and will display
                    // https://github.com/nostra13/Android-Universal-Image-Loader/tree/master/sample
    
                    // holder.cloud.setImageBitmap(bitmap.get(position));
                    return convertView;
                }
            }
        }
    }
    
    class SingleRow {
        String minTemp, maxTemp, speed, humidity;
        Bitmap img;
    
        SingleRow(String minTemp, String maxTemp, String speed, String humidity,
                Bitmap img) {
    
            this.maxTemp = maxTemp;
            this.minTemp = minTemp;
            this.speed = speed;
            this.humidity = humidity;
            this.img = img;
        }
    
    }
    

    list_row_data.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent" android:layout_margin="5dp"
        android:layout_height="wrap_content"
        android:background="#ffffff"
        android:orientation="vertical" >
    
        <TextView
            android:id="@+id/speed"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#ffff8800" />
    
        <TextView
            android:id="@+id/weather"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#ffff8800" />
    
        <TextView
            android:id="@+id/latitude"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#ffff8800" />
    
        <TextView
            android:id="@+id/longitude"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#ffff8800" />
    
        <TextView
            android:id="@+id/minTemp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#ffff8800" />
    
        <TextView
            android:id="@+id/maxTemp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#ffff8800" />
    
    </LinearLayout>
    

    listview_.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
    
        <ListView
            android:id="@+id/listdata"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />
    
    </LinearLayout>