简体   繁体   中英

Custom Listview Adapter in Android implementation Problems

I want to display some objects that I have filled with data from a JSON file on a ListView. In my code, I create the Listview and then instanciate a custom list adapter, but it crashes as soon as my app opens the listview. Here is the code from the activity InsectsCatchable:

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class InsectsCatchable extends AppCompatActivity {
    private static final String TAG = "InsectsCatchable";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        String insects_total = "";
        JSONArray insects_array = null;
        super.onCreate(savedInstanceState);
        Log.d(TAG,"onCreate: Started.");
        setContentView(R.layout.activity_insects_catchable);
        ListView mListView = (ListView) findViewById(R.id.listInsects);

        InputStream insects_stream = getResources().openRawResource(R.raw.insects);
        BufferedReader reader = new BufferedReader(new InputStreamReader(insects_stream));
        try {
            //load JSON
            String insects_string = reader.readLine();
            while (insects_string != null) {
                insects_total = insects_total+insects_string;
                insects_string = reader.readLine();
            }
            insects_array = new JSONArray(insects_total);

            // create insectsArray
            ArrayList<Insect> insectsList = new ArrayList<>();
            for (int i = 0; i< insects_array.length();i++){

                //iterate over JSON object
                JSONObject currentins = insects_array.getJSONObject(i);

                //every insect gets instanciated and put into the insectslist

                Insect e = new Insect(currentins);
                insectsList.add(e);
            }

            //create Listadapter
            InsectListAdapter adapter = new InsectListAdapter (this, R.layout.adapter_view_layout, insectsList);
            mListView.setAdapter(adapter);

        } catch (Exception e) {
            e.printStackTrace();
        }



    }
}

And this is my Custom Adapter InsectListAdapter.java


import android.content.Context;
import android.text.Layout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

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

public class InsectListAdapter extends ArrayAdapter<Insect> {
    private static final String TAG = "InsectListAdapter";
    private Context mContext;
    int mResource;

    public InsectListAdapter(@NonNull Context context, int resource, @NonNull ArrayList<Insect> objects) {
        super(context, resource, objects);
        this.mContext = mContext;
        Log.d(TAG,"InsectListAdapter started");
        mResource = resource;
    }


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

        //Insect insect = new Insect();
        //LayoutInflater inflater = LayoutInflater.from(mContext);
        //convertView = inflater.inflate(mResource,parent,false);

        /*TextView tvPrice = (TextView) convertView.findViewById(R.id.priceview);
        TextView tvLocation = (TextView) convertView.findViewById(R.id.locationview);
        TextView tvName = (TextView) convertView.findViewById(R.id.nameview);*/

        return convertView;
    }
}

And these are the .xml files for InsectsCatchable:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:background="@drawable/nook"
    tools:context=".InsectsCatchable">

    <ListView
        android:id="@+id/listInsects"
        android:layout_marginTop="100dp"
        android:layout_width="409dp"
        android:layout_height="550dp"/>


</LinearLayout> 

and "adapter_view_layout"

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="100">


    <TextView
        android:gravity="center"
        android:textAlignment="center"
        android:text="Name"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:id="@+id/nameview"
        android:layout_weight="66.6"/>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="33.3">

        <TextView
            android:gravity="center"
            android:text="Price"
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:id="@+id/locationview"/>

        <TextView
            android:gravity="center"
            android:text="Location"
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:id="@+id/textView3"
            android:layout_below="@+id/priceview"/>
    </LinearLayout>

</LinearLayout>

Does anyone have an Idea why I cannot show the insects's prices and names (for proof of concept) in my Listview in the InsectsCatchable?

EDIT: Logcat:

2020-03-28 15:41:46.586 16312-16312/com.example.acfaunapedia D/InsectListAdapter: InsectListAdapter started
2020-03-28 15:41:46.613 16312-16312/com.example.acfaunapedia I/Choreographer: Skipped 68 frames!  The application may be doing too much work on its main thread.
2020-03-28 15:41:46.684 16312-16312/com.example.acfaunapedia D/AndroidRuntime: Shutting down VM


    --------- beginning of crash
2020-03-28 15:41:46.685 16312-16312/com.example.acfaunapedia E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.acfaunapedia, PID: 16312
    java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference
        at android.widget.AbsListView.obtainView(AbsListView.java:2379)
        at android.widget.ListView.makeAndAddView(ListView.java:1970)
        at android.widget.ListView.fillDown(ListView.java:704)
        at android.widget.ListView.fillFromTop(ListView.java:765)
        at android.widget.ListView.layoutChildren(ListView.java:1744)
        at android.widget.AbsListView.onLayout(AbsListView.java:2161)
        at android.view.View.layout(View.java:17523)
        at android.view.ViewGroup.layout(ViewGroup.java:5612)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
        at android.widget.LinearLayout.layoutHorizontal(LinearLayout.java:1730)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1496)
        at android.view.View.layout(View.java:17523)
        at android.view.ViewGroup.layout(ViewGroup.java:5612)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:17523)
        at android.view.ViewGroup.layout(ViewGroup.java:5612)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
        at android.view.View.layout(View.java:17523)
        at android.view.ViewGroup.layout(ViewGroup.java:5612)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:17523)
        at android.view.ViewGroup.layout(ViewGroup.java:5612)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
        at android.view.View.layout(View.java:17523)
        at android.view.ViewGroup.layout(ViewGroup.java:5612)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at com.android.internal.policy.DecorView.onLayout(DecorView.java:724)
        at android.view.View.layout(View.java:17523)
        at android.view.ViewGroup.layout(ViewGroup.java:5612)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2342)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2069)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1246)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6301)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
        at android.view.Choreographer.doCallbacks(Choreographer.java:683)
        at android.view.Choreographer.doFrame(Choreographer.java:619)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) ```

Here is a sample Listview

ListViewAdapter class

public class ListViewAdapter extends BaseAdapter {
Context mContext;
LayoutInflater inflater;

public ListViewAdapter(Context context, List<ModelData> modelList) {
    this.mContext = context;
    this.modelList = modelList;
    inflater = LayoutInflater.from(mContext);
    this.arrayList = new ArrayList<ModelData>();
    this.arrayList.addAll(modelList);

}
public class ViewHolder
{
    TextView mPackDate,mPackDes;
    Button mPackDelete;
}

@Override
public int getCount() {
    return modelList.size();
}

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

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

@Override
public View getView(final int i, View view, ViewGroup viewGroup) {

    final ListViewAdapter.ViewHolder  holder;
    if (view == null) {
        holder = new ListViewAdapter.ViewHolder();

        view = inflater.inflate(R.layout.sticker_main, null);

        holder.mPackDate = view.findViewById(R.id.sticker_date);
        holder.mPackDes = view.findViewById(R.id.sticker_des);
        holder.mPackDelete = view.findViewById(R.id.sticker_btn);
        view.setTag(holder);

    } else {
        holder = (ListViewAdapter.ViewHolder) view.getTag();
    }
    holder.mPackDate.setText( modelList.get(i).getDate() );
    holder.mPackDes.setText( modelList.get(i).getDes() );

  Picasso.get().load(modelList.get(i).getUrl()).into(holder.mPackImg);

    return view;
}

}

MainAcitivity

public class MainPage extends AppCompatActivity {


ListView listView;
ArrayList<ModelData> arrayList = new ArrayList<ModelData>();
ListViewAdapter adapter;
ModelData modelData;
String sUrl, sDes, sDate, skey;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.main_page_activity );
    Toolbar toolbar = findViewById( R.id.toolbar );
    setSupportActionBar( toolbar );

    listView = findViewById( R.id.myList );
    modelData = new ModelData( sUrl, sDate, sDes, skey );
    arrayList.add( modelData );
    adapter = new ListViewAdapter( getApplicationContext(), arrayList); 
    listView.setAdapter( adapter );
}

我解决了我的 InsectListAdapter 构造函数中的问题,将 this.mContext 设置为 mContext 而不是 context

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