繁体   English   中英

我该如何解决 ListView 问题? 错误:在空对象引用上

[英]how may i resolve ListView Problem ? ERROR: on a null object reference

大家好,我又回到了关于我的最终项目的问题。 我使用活动(无片段)制作了一个带有导航抽屉的 googlemap 应用程序。 我想你知道的。 然后,我没有使用标题和菜单,而是使用了标题应该在的布局,以便我可以在那里创建一个列表视图来显示事件,所有这些都很清楚。 截屏在此处输入图像描述 地图活动:

public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {

    private static final String TAG = "MapActivity";
    DrawerLayout drawerLayout;
    LinearLayout drawer_up;
    FloatingActionsMenu mainfloating;
    FloatingActionButton profile, evennement, historique,reglage,aidesupport;
    ImageButton zoomin,zoomout,showtail,zoom_auto,showgeofence,maplayer,drawermenugroit,drawermenugauche;
    ProgressDialog progressDialog;
    private Dialog mDialog;
    private GoogleMap map;
    private Timer timer;
    private int autoZoomedTimes = 0;// dėl bugo osmdroid library, zoom'inam du kartus ir paskui po refresh'o nebe, nes greičiausiai user'is bus pakeitęs zoom'ą
    RelativeLayout nodata_layout;
    private HashMap<Integer, Marker> deviceIdMarkers;
    private HashMap<String, Device> markerIdDevices;
    private HashMap<Integer, Polyline> deviceIdPolyline;
    private HashMap<Integer, LatLng> deviceIdLastLatLng;
    //    private HashMap<Integer, Marker> deviceIdSmallMarkerInfo;
    private long lastRefreshTime;
    boolean isAutoZoomEnabled = true;
    boolean isShowTitlesEnabled;
    boolean isShowTailsEnabled = true;
    boolean isShowGeofencesEnabled = true;
    private String stopTime;
    ImageButton map_layer_icon;
    private AsyncTask downloadingAsync;
    @Bind(R.id.listevent)
    ListView listevent;
    @Bind(R.id.clearAllEvents)
    Button clearAllEvents;
    @Bind(R.id.list) ListView list;
    @Bind(R.id.nodata_layout) RelativeLayout nodata_layout1;
    private boolean isRefreshLoced = false;

    ApiInterface.GetGeofencesResult geofencesResult;
    ArrayList<PolygonWithName> polygonsWithDetails = new ArrayList<>();
    float previousZoomLevel = 0;
    Boolean isAllFabsVisible;
    RelativeLayout content_layout;
    //fin de declaration a garder en tete

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        setContentView(R.layout.activity_map);
        //devices elements
        deviceIdMarkers = new HashMap<>();
        markerIdDevices = new HashMap<>();
        deviceIdPolyline = new HashMap<>();
        deviceIdLastLatLng = new HashMap<>();

        final String api_key = (String) DataSaver.getInstance(MapActivity.this).load("api_key");
        final EventsAdapter adapter = new EventsAdapter(this);
       listevent.setAdapter(adapter);
        //deviceIdSmallMarkerInfo = new HashMap<>();
        //delaration des boutons pour le compte de floatingButton, etc...;
        drawermenugroit = findViewById(R.id.drawermenudroit);
        drawer_up = findViewById(R.id.drawerup);
        drawermenugauche = findViewById(R.id.drawermenugauche);
        drawerLayout = findViewById(R.id.drawer);
       // profile = findViewById(R.id.profile);
        mainfloating = findViewById(R.id.mainFloatingBtn);
        evennement = findViewById(R.id.evennements);
        historique = findViewById(R.id.historiques);
        reglage = findViewById(R.id.reglages);
aidesupport = findViewById(R.id.aide_support);
        zoomin = findViewById(R.id.zoom_in);
        LinearLayout list_event = findViewById(R.id.list_event);
        zoomout = findViewById(R.id.zoom_out);
        showtail = findViewById(R.id.showtails);
        zoom_auto = findViewById(R.id.autozoom);
        listevent = (ListView) findViewById(R.id.listevent);
        list = (ListView) findViewById(R.id.list);
        showgeofence = findViewById(R.id.geofences);
        maplayer = findViewById(R.id.map_layer);
        map_layer_icon = (ImageButton) findViewById(R.id.map_layer);
        //loading_bar = (ProgressBar) findViewById(R.id.loading_progBar);
        content_layout = (RelativeLayout) findViewById(R.id.content_layout);
        nodata_layout = (RelativeLayout) findViewById(R.id.nodata_layout);
        //fin de declaration de boutons

          //chargement des données
        progressDialog = new ProgressDialog(this);
        progressDialog = new ProgressDialog(MapActivity.this);
        progressDialog.setMessage("En cours..."); // Setting Message
        progressDialog.setTitle("Chargement de la carte"); // Setting Title
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner
        progressDialog.show(); // Display Progress Dialog
        progressDialog.setCancelable(false);
        new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(10000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                progressDialog.dismiss();
            }
        }).start();
        // fni de chargement des données

        //open drawer and load list data in drawer layout button
        drawermenugauche.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                openDrawer(drawerLayout);
                API.getApiInterface(MapActivity.this).getEvents(api_key, getResources().getString(R.string.lang), 0, new Callback<ApiInterface.GetEventsResult>() {
                    @Override
                    public void success(ApiInterface.GetEventsResult result, Response response) {
                        adapter.setArray(result.items.data);
                        if(result.items.data.size() != 0)
                            listevent.setVisibility(View.VISIBLE);
                        else
                          nodata_layout1.setVisibility(View.VISIBLE);
                           listevent.setVisibility(View.GONE);
                    }
                    @Override
                    public void failure(RetrofitError retrofitError) {
                        Toast.makeText(MapActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
                    }
                });

            }
        });


drawer_up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeDrawer(drawerLayout);
            }
        });

        zoomin.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                map.animateCamera(CameraUpdateFactory.zoomIn());
            }
        });
        zoomout.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                map.animateCamera(CameraUpdateFactory.zoomOut());
            }
        });

        zoom_auto.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                isAutoZoomEnabled = !isAutoZoomEnabled;
                if (isAutoZoomEnabled)
                {
                    zoom_auto.setImageResource(R.drawable.icon2022);
                    Toast.makeText(MapActivity.this, "Zoom Auto Activé", Toast.LENGTH_SHORT).show();
                } else
                {
                    zoom_auto.setImageResource(R.drawable.disableicon2022);
                    Toast.makeText(MapActivity.this, "Zoom Auto Désactivé", Toast.LENGTH_SHORT).show();
                }
            }
        });
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

}
// ouverture et fermeture de drawer
    private static void openDrawer(DrawerLayout drawerLayout){
        drawerLayout.openDrawer(GravityCompat.START);

    }
    private static void closeDrawer(DrawerLayout drawerLayout){
        if(drawerLayout.isDrawerOpen(GravityCompat.START)){
            drawerLayout.closeDrawer(GravityCompat.START);

        }
    }
    //fin ouverture et fermeture drawer
......etc...

请参阅下面的 EventsAdapter 代码:

public class EventsAdapter extends AwesomeAdapter<Event> {
    public EventsAdapter(Context context) {
        super(context);
    }

    ArrayList<Event> original;
    @Override
    public void setArray(ArrayList<Event> array) {
        super.setArray(array);
        if(original == null)
            original = array;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView == null)
            convertView = getLayoutInflater().inflate(R.layout.adapter_events, null);

        Event item = getItem(position);
        TextView device_name = (TextView) convertView.findViewById(R.id.device_name);
        device_name.setText(item.device_name);
        TextView date = (TextView) convertView.findViewById(R.id.date);
        date.setText(item.time);
        TextView message = (TextView) convertView.findViewById(R.id.message);
        message.setText(item.message);
        TextView geofence_name = (TextView) convertView.findViewById(R.id.geofence_name);
        geofence_name.setText(item.geofence_name);

        return convertView;
    }

    ItemFilter mFilter = new ItemFilter();
    public Filter getFilter() {
        return mFilter;
    }

    private class ItemFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint)
        {
            String filterString = constraint.toString().toLowerCase();
            FilterResults results = new FilterResults();
            final ArrayList<Event> nlist = new ArrayList<>();

            for(Event item : original)
            {
                if(item.fitForFilter(filterString))
                    nlist.add(item);
            }
            results.values = nlist;
            results.count = nlist.size();
            return results;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            setArray((ArrayList<Event>) results.values);
            notifyDataSetChanged();
        }

    }
}

然后在我的 adapter_event 布局中

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:background="@color/whitesplash"
    android:layout_marginBottom="10dp"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/instance"
        android:layout_width="16dp"
        android:layout_height="22dp"
        android:src="@drawable/custom_floating_button" />

    <TextView
        android:id="@+id/device_nam"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@+id/instance"
        android:fontFamily="@font/fjallaoneregular"
        android:text="Info Balise"
        android:textColor="@color/black"
        android:textSize="8dp"
        android:textStyle="normal" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_below="@+id/device_nam"
        android:outlineAmbientShadowColor="@color/blue" />
    <TextView
        android:id="@+id/device_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/device_nam"
        android:layout_marginStart="16dp"
        android:fontFamily="@font/fjallaoneregular"
        android:text="device name"
        android:textColor="@color/blue"
        android:textSize="8dp"
        android:textStyle="italic" />

    <TextView
        android:id="@+id/textspeed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="3dp"
        android:layout_toEndOf="@+id/device_nam"
        android:fontFamily="@font/fjallaoneregular"
        android:text="Vitesse"
        android:textColor="@color/black"
        android:textSize="8dp"
        android:textStyle="italic" />

    <TextView
        android:id="@+id/speed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textspeed"
        android:layout_marginStart="3dp"
        android:layout_toEndOf="@+id/device_name"
        android:fontFamily="@font/fjallaoneregular"
        android:text="speed"
        android:textColor="@color/blue"
        android:textSize="8dp"
        android:textStyle="italic" />

    <TextView
        android:id="@+id/message1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="3dp"
        android:layout_toRightOf="@+id/textspeed"
        android:fontFamily="@font/fjallaoneregular"
        android:text="message"
        android:textColor="@color/black"
        android:textSize="8dp"
        android:textStyle="normal" />

    <TextView
        android:id="@+id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textspeed"
        android:layout_marginStart="3dp"
        android:layout_toEndOf="@+id/speed"
        android:fontFamily="@font/fjallaoneregular"
        android:text="massage"
        android:textColor="@color/blue"
        android:textSize="8sp"
        android:textStyle="italic" />

    <View
        android:id="@+id/view2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/device_name" />
    <TextView
        android:id="@+id/datetext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/device_name"
        android:layout_toEndOf="@+id/instance"
        android:fontFamily="@font/fjallaoneregular"
        android:text="date:"
        android:textColor="@color/black"
        android:textSize="8dp"
        android:textStyle="normal" />

    <TextView
        android:id="@+id/date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/device_name"
        android:layout_marginStart="3dp"
        android:layout_toEndOf="@+id/datetext"
        android:fontFamily="@font/fjallaoneregular"
        android:text="date"
        android:textColor="@color/blue"
        android:textSize="8sp"
        android:textStyle="italic" />

    <TextView
        android:id="@+id/geofence_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="geofence_name"
        android:fontFamily="@font/lobsterregular"
        android:layout_below="@+id/date"
        android:layout_marginStart="3dp"
        android:layout_toRightOf="@+id/instance"
        android:textSize="8dp"
        android:textColor="@color/blue"/>

</RelativeLayout>

在这个 adpater_events 我没有发现错误。 并且在我之前说过的drawer_tracesas中(我没有在navigationDrawer中使用菜单和标题,我想使用我称为drawer_traces的布局),如下所示

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
       android:id="@+id/drawerup"
        android:orientation="horizontal"
        android:background="@color/blue">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@string/objects"
            android:src="@drawable/ic_menu_24"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textSize="16sp"
            android:text="@string/objects" />
    </LinearLayout>

    <TextView
        android:id="@+id/Liste_Balises"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/drawerup"
        android:fontFamily="@font/fjallaoneregular"
        android:gravity="center"
        android:text="@string/liste_balises"
        android:textColor="@color/blue" />

    <LinearLayout
        android:id="@+id/list_balises"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:orientation="vertical"
        android:layout_below="@+id/Liste_Balises"
        android:layout_marginTop="10dp"
        android:minHeight="?android:attr/listPreferredItemHeight">

        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:orientation="vertical" />
    </LinearLayout>

    <TextView
        android:id="@+id/list_events"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/list_balises"
        android:layout_marginTop="10dp"
        android:fontFamily="@font/fjallaoneregular"
        android:gravity="center"
        android:text="@string/liste_evennemT"
        android:textColor="@color/blue" />

    <LinearLayout
        android:id="@+id/list_event"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="300dp"

        android:layout_below="@+id/list_events"
        android:layout_marginTop="10dp"
        android:minHeight="?android:attr/listPreferredItemHeight">

        <ListView
            android:id="@+id/listevent"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"
            android:layout_marginRight="10dp"
            android:orientation="vertical" />
    </LinearLayout>
    <RelativeLayout
        android:id="@+id/nodata_layout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/list_event"
        android:layout_above="@+id/clearAllEvents"
        android:background="#ffffff"
        android:visibility="gone"
        android:gravity="center">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@string/noEventsData"/>
    </RelativeLayout>
    <Button
        android:id="@+id/clearAllEvents"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/list_event"
        android:fontFamily="@font/fjallaoneregular"
        android:text="Effacer Evennements"/>
</RelativeLayout>

此布局 (drawer_trace) 将作为导航抽屉显示在 mapActivity 中。 我们可以。 然后我有我的事件模型:

public class Event
{
    public int id, user_id, device_id, position_id, alert_id;
    // geofence_id
    public String message;
    public String address;
    public float altitude;
    // course
    public float latitude, longitude;
    // power
    public float speed;
    public String time;
    // deleted

    public String device_name, geofence_name;

    public boolean fitForFilter(String filterString) {
        if(message.toLowerCase().contains(filterString.toLowerCase()))
            return true;
        if(address.toLowerCase().contains(filterString.toLowerCase()))
            return true;
        if(time.toLowerCase().contains(filterString.toLowerCase()))
            return true;
        if(device_name.toLowerCase().contains(filterString.toLowerCase()))
            return true;
        if(geofence_name.toLowerCase().contains(filterString.toLowerCase()))
            return true;
        return false;
    }

我在后端和改造中使用 REST API。 一切都很好,直到我尝试启动应用程序。 它说错误消息:

Process: com.gabontech.gprstest, PID: 14460
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gabontech.gprstest/com.gabontech.gprstest.activities.MapActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3433)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3572)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:96)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2097)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:264)
        at android.app.ActivityThread.main(ActivityThread.java:7663)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
        at com.gabontech.gprstest.activities.MapActivity.onCreate(MapActivity.java:139)
        at android.app.Activity.performCreate(Activity.java:7805)
        at android.app.Activity.performCreate(Activity.java:7794)

我想到了 EventsAdapter.class 行 ref::::: 中的适配器

convertView = getLayoutInflater().inflate(R.layout.adapter_events, null); 我在那里呆了两天。 请如果你能帮助它会帮我考试。 非常感谢你们

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM