Hi guys,

I'm having a weird problem regarding the simple ListView.
On my emulator everything is allright and the data is loaded correctly from JSON API, the data also loads on my device.
The problem is that on my emulator, the listview is populated but on my real device, not, why ?

1.jpg2.jpg

Dani AI

Generated

A couple of things in your snippet can make a ListView look fine on the emulator but appear empty on a device:

  • Adapter lifecycle: you create the adapter and then clear it immediately, and later you mutate the backing list in onPostExecute without notifying the adapter. On many devices the ListView will not refresh unless you keep a reference to the adapter and call notifyDataSetChanged() after you add items. See BaseAdapter.notifyDataSetChanged() in the Android docs ([link](https://developer.android.com/reference/android/widget/BaseAdapter#notifyDataSetChanged())). Also consider removing the early clear().

  • Layout constraints: your switch to LinearLayout likely changed measurement. In a vertical layout, give the ListView non-zero space (e.g., match_parent height or 0dp with layout_weight) so it can render. Attributes like layout_below are ignored in LinearLayout; rely on order and weights instead (LinearLayout guide). If a ProgressBar sits on top, hide it when data is loaded (GONE). Using setEmptyView(...) on the ListView is a great way to confirm when the adapter is empty (AdapterView.setEmptyView).

  • Network/security differences: if your API or image URLs are HTTP, Android 9+ blocks cleartext by default. The emulator may be more permissive, while a real device may drop the requests. Prefer HTTPS or add a Network Security Config if you must allow HTTP (Network security configuration).

Recommended Answers

All 5 Replies

Without seeing actual code hard to say...

Sorry, here it is :)

My Model:

public class ImagesModel {
    private int sapCode;
    private String imagePath;
    private int icon;

    public ImagesModel(int sapCode, String imagePath, int icon) {
        this.sapCode = sapCode;
        this.imagePath = imagePath;
        this.icon = icon;
    }

    public int getSapCode() {
        return sapCode;
    }

    public String getImagePath() {
        return imagePath;
    }

    public int getIcon() {
        return icon;
    }
}

And My Activity

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import ro.sz.dezmembrari.sza.Config;
import ro.sz.dezmembrari.sza.JSONParser;
import ro.sz.dezmembrari.sza.R;
import ro.sz.dezmembrari.sza.model.ImagesModel;

/**
 * Created by Szabi.Zsoldos on 28/04/2015.
 */
public class ImagesListView extends Activity {

    private List<ImagesModel> myImages = new ArrayList<ImagesModel>();
    long totalSize = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.uploaded_layout);

        populateImageList();
        populateListView();
    }

    private void populateImageList() {
        new GetReportFromAPI().execute();
    }

    private void populateListView() {
        ArrayAdapter<ImagesModel> adapter = new MyListAdapter();
        ListView list = (ListView) findViewById(R.id.imagesListView);
        list.setAdapter(adapter);
        adapter.clear();
    }

    private class MyListAdapter extends ArrayAdapter<ImagesModel> {

        public MyListAdapter() {
            super(ImagesListView.this, R.layout.item_view, myImages);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // Make sure we have a view to work with
            View itemView = convertView;
            if(itemView == null) {
                itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false);
            }

            // find the image to work with
            ImagesModel currentImage = myImages.get(position);

            // fill the view

            ImageView imageView = (ImageView) itemView.findViewById(R.id.item_icon);
            try {
                Picasso.with(ImagesListView.this).load(currentImage.getImagePath()).into(imageView);
            } catch(Exception e) {
                imageView.setImageResource(currentImage.getIcon());
            }

            TextView sapCode = (TextView) itemView.findViewById(R.id.item_txtSAPCode);
            sapCode.setText("" + currentImage.getSapCode());

            TextView imagePath = (TextView) itemView.findViewById(R.id.item_imagePath);
            imagePath.setText(currentImage.getImagePath());


            return itemView;
        }
    }

    private class GetReportFromAPI extends AsyncTask<String, String, JSONObject> {



        @Override
        protected JSONObject doInBackground(String... params) {
            JSONParser jParser = new JSONParser();

            // Getting JSON from URL
            JSONObject json = jParser.getJSONFromUrl(Config.REPORT_URL);
            return json;
        }

        @Override
        protected void onPostExecute(JSONObject json) {
            // showing the server response in an alert dialog
            addItemsToListView(json);
        }

    }

    private void addItemsToListView(JSONObject message) {
        try {
            JSONArray jsonArray = message.getJSONArray("android");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject c = jsonArray.getJSONObject(i);
                String imagePath = c.getString("path");

                try {
                    myImages.add(new ImagesModel(i, imagePath, R.drawable.mtr));
                } catch(Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

Got the problem, I've changed the layout from RelativeLayout to LinearLayout and it is all working fine.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/view_background"
    android:orientation="vertical"
    android:padding="10dp"
    android:weightSum="1">

    <ProgressBar
        android:id="@+id/progressBar1"
        style="@style/Base.Widget.AppCompat.ProgressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:progress="@integer/abc_config_activityShortDur"
        android:layout_centerInParent="true"
        android:maxHeight="100dp"
        android:maxWidth="100dp"
        android:minHeight="200dp"
        android:minWidth="200dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/btnUploadedActivity"
        android:id="@+id/imagesListViewTitle"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imagesListView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignLeft="@+id/imagesListViewTitle"
        android:layout_below="@+id/imagesListViewTitle"
        android:smoothScrollbar="true" />
</LinearLayout>

Well done

maybe it cause link of API using http not https, android consider it insecure

commented: Remember that 5 years ago, that wasn't being forced. Today? You're right. Watch those discussion dates! +15
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.