ListView in the first activity, listView in the second activity; nested Json- no images in second listView.

人走茶凉 提交于 2019-12-13 03:35:23

问题


I’m using Gson and Universal Image Loader. I used this project like a template (you need change version to run it, it shows in tutorial): tutorial: https://www.youtube.com/watch?v=X2mY3zfAMfM link to this project: https://github.com/hishamMuneer/JsonParsingDemo

I aded images in nested part of JSON and created listView in second activity to display it.

    {
  "movies": [
    {
      "movie": "Avengers",
      "cast": [
        {
          "name": "Robert Downey Jr.",
            "image": "www.mywebsite.com/img2.png"
        },
        {
          "name": "Chris Evans",
            "image": "www.mywebsite.com/img3.png"
        },
        {
          "name": "Mark Ruffalo",
            "image": "www.mywebsite.com/img4.png"
        }
      ],
      "image": "https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/images/avengers.jpg"
    },
    {
       "movie": "Interstellar",
      "cast": [
        {
          "name": "Robert Downey Jr.",
            "image": "www.mywebsite.com/img5.png"
        },
        {
          "name": "Chris Evans",
            "image": "www.mywebsite.com/img6.png"
        },
        {
          "name": "Mark Ruffalo",
            "image": "www.mywebsite.com/img7.png"
        }
      ],
      "image": "https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/images/interstellar.jpg"
    },...

  ]
}

First listView works correctly. In second I have errors. I tried three ways: 1. Using BaseAdapter: Withouth images it populates second listView with textView correctly, and displays each of image in detail activity. So three acitvities works fine (without images in second one). But when I try to populate ListView with images I have errors: a. Using default way: Problem with parse-while debuging I see in the logcat the correct image url, and its possition while debuging, but archive the error after that.

’FATAL EXCEPTION: main
java.lang.NumberFormatException: For input string: ”http://example.com/image14.png”
at java.lang.Integer.parseInt(Integer.java:608)
at java.lang.Integer.parseInt(Integer.java:643)
at ….ListAdapter.getView(ListActivity)

b. Using Universal Image Loader. ‚Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference’ ImageLoader configuration can not be initialized with null

  1. Using ArrayAdapter like in the first activity. Error: Attempt to read from field 'android.widget.TextView com.example…GridActivity$ViewHolder.gridTitle' on a null object reference

Could you help me, please?

    public class MovieModel {
    private String name;
    private String imgMovie;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getImgMenu() {
        return imgMovie;
    }
    public void setImgMenu(String imgMenu) {
        this.imgMovie = imgMenu;
    }


    @SerializedName("description")
    private List<Descriptions> descriptions;
    public List<Descriptions> getDescriptionsList() {
        return descriptions;
    }
    public void setDescriptionsList(List<Descriptions> descriptions) {
        this.descriptions = descriptions;
    }

    public static class Descriptions {
        private String title;
        private String image;

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getImage() {
            return image;
        }
        public void setImage(String image) {
            this.image = image;
        }
    }
}

   public class ListActivity extends AppCompatActivity {

    private ProgressBar progresBar;

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

        ListView listView = (ListView) findViewById(R.id.listView);

        // getting the model from MainActivity send via extras
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String json = bundle.getString("movieModel");
            MovieModel movieModel = new Gson().fromJson(json, MovieModel.class);
            final List<MovieModel.Descriptions> result = movieModel.getDescriptionsList();

            GridAdapter gridAdapter = new GridAdapter(getApplicationContext(), result);
            listView.setAdapter(gridAdapter);

            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    MovieModel.Descriptions descriptionsModel = result.get(position);

                    Intent intent = new Intent(ListActivity.this, DetailActivity.class);
                    intent.putExtra("descriptionsModel", new Gson().toJson(descriptionsModel));
                    startActivity(intent);
                }


            });
        }
    }

    public class GridAdapter extends BaseAdapter {

        private LayoutInflater inflater;
        private Context context;
        private int resource;
        private List<MovieModel.Descriptions> items; // You hate to use detailList

        public GridAdapter(Context context, List<MovieModel.Descriptions> items) {
            this.context = context;
            this.items = items;
            inflater = (LayoutInflater.from(context));
        }

        @Override
        public int getCount() {
            return items.size(); //returns total of items in the list
        }

        @Override
        public Object getItem(int position) {
            return items.get(position); //returns list item at the specified position
        }
        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

                convertView = inflater.inflate(R.layout.list, null);

//            Display text correctly when all below (with image) is comment
            TextView listTitle = (TextView) convertView.findViewById(R.id.text);
            listTitle.setText(items.get(position).getTitle());

            // 1a -Shows error because Parse when all bellow is comment
            ImageView listImg = (ImageView) convertView.findViewById(R.id.image);
           listImg.setImageResource(Integer.parseInt(items.get(position).getImage()));

            // 1b - ImageLoader configuration can not be initialized with null
            final ProgressBar progressBar = (ProgressBar) convertView.findViewById(R.id.progressBar);
            ImageLoader.getInstance().displayImage(items.get(position).getImage(), listImg , new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String imageUri, View view) {
                    progressBar.setVisibility(View.VISIBLE);
                }
                @Override
                public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                    progressBar.setVisibility(View.GONE);
                }
                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    progressBar.setVisibility(View.GONE);
                }
                @Override
                public void onLoadingCancelled(String imageUri, View view) {
                    progressBar.setVisibility(View.GONE);
                }
            });
            return convertView;
        }
    }

activity_list

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.xtech.baselistview.ListActivity">

    <GridView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:verticalSpacing="0dp"
        android:horizontalSpacing="0dp"
        android:stretchMode="columnWidth"
        android:numColumns="2"
        />
</RelativeLayout>

list.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="match_parent"
    android:orientation="vertical">


    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:scaleType="centerCrop" />

        <ProgressBar
            android:id="@+id/progressBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center" />

    </FrameLayout>
        <TextView
            android:id="@+id/text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:gravity="center" />

</LinearLayout>

Third way with ArrayAdapter

    public class ListActivity extends AppCompatActivity {

    private ProgressBar progresBar;
    private ListView listView;

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

        listView = (ListView) findViewById(R.id.listView);

        // getting the model from MainActivity send via extras
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String json = bundle.getString("movieModel");
            MovieModel movieModel = new Gson().fromJson(json, MovieModel.class);
            List<MovieModel.Descriptions> result = movieModel.getDescriptionsList();

            ListAdapter adapter = new ListAdapter(getApplicationContext(), R.layout.list, result);
            listView.setAdapter(adapter);
        }
    }

    public class ListAdapter extends ArrayAdapter {

        private LayoutInflater inflater;
        private Context context;
        private int resource;
        private List<MovieModel.Descriptions> items;

        public ListAdapter(Context context, int resource, List<MovieModel.Descriptions> items) {
            super(context, resource, items);
            this.context = context;
            this.resource = resource;
            this.items = items;
            inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return items.size(); //returns total of items in the list
        }

        @Override
        public Object getItem(int position) {
            return items.get(position); //returns list item at the specified position
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = inflater.inflate(resource, null);

                holder.listImg = (ImageView) convertView.findViewById(R.id.image);
                holder.listTitle = (TextView) convertView.findViewById(R.id.text);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            final ProgressBar progressBar = (ProgressBar)convertView.findViewById(R.id.progressBar);

            final ViewHolder finalHolder = holder;
            ImageLoader.getInstance().displayImage(items.get(position).getImage(), holder.listImg, new ImageLoadingListener() {

                @Override
                public void onLoadingStarted(String imageUri, View view) {
                    progresBar.setVisibility(View.VISIBLE);
                }
                @Override
                public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                    progresBar.setVisibility(View.GONE);
                }
                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    progresBar.setVisibility(View.GONE);
                }
                @Override
                public void onLoadingCancelled(String imageUri, View view) {
                   progresBar.setVisibility(View.GONE);
                }
            });
            holder.listTitle.setText(items.get(position).getTitle()); //

            return convertView;
        }
    }
    class ViewHolder {
        private ImageView listImg;
        private TextView listTitle;
    }
}

回答1:


I will suppose that you are passing correct url via intent so in your DetailActivity:

String flag;
flag = i.getStringExtra("flag");
flagImg = (ImageView)findViewById(R.id.detailImg);
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(flag, flagImg);


来源:https://stackoverflow.com/questions/46911971/listview-in-the-first-activity-listview-in-the-second-activity-nested-json-no

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!