ListView fehler: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference

wer112

Top Contributor
Ich habe damals in mein App Store eine Listview gemacht(mehrere) die alle bisher funktioniert hat.
Ich habe das exakt nachgemacht, wie früher, leider bekomme ich diese Fehlermeldung:

Java:
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
                                                                                                        at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:389)
                                                                                                        at android.widget.ListView.setAdapter(ListView.java:612)
                                                                                                        at com.andrealfredklug.klugstore.Konsole.App_spenden$1.onResponse(App_spenden.java:184)
                                                                                                        at com.andrealfredklug.klugstore.Konsole.App_spenden$1.onResponse(App_spenden.java:84)
                                                                                                        at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:100)
                                                                                                        at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
                                                                                                        at android.os.Handler.handleCallback(Handler.java:938)
                                                                                                        at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                                        at android.os.Looper.loopOnce(Looper.java:226)
                                                                                                        at android.os.Looper.loop(Looper.java:313)
                                                                                                        at android.app.ActivityThread.main(ActivityThread.java:8751)
                                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
                                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)

Die TEST Json und die ArrayList klappen laut Log.e():

Java:
{"status":"es gibt Apps","AppAnzahl":2,"Apps":"{\"app_name\":[\"CoundownWlanApp\",\"Navigator\"],\"package\":[\"com.andrealfredklug.countdownwlanapp\",\"com.navigator\"],\"utc\":[\"02.10.2024\",\"01.10.2024\"]}"}
2024-10-04 17:40:34.990 14738-14738 App spenden             com.andrealfredklug.klugstore        E  [CoundownWlanApp, Navigator]
2024-10-04 17:40:34.990 14738-14738 App spenden             com.andrealfredklug.klugstore        E  [com.andrealfredklug.countdownwlanapp, com.navigator]
2024-10-04 17:40:34.990 14738-14738 App spenden             com.andrealfredklug.klugstore        E  [02.10.2024, 01.10.2024]

Sobald ich den listview.setadapter mache crascht die Listview.

Meine Klasse:

Java:
package com.andrealfredklug.klugstore.Konsole;

import android.app.Fragment;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.andrealfredklug.klugstore.ALoadingDialog;
import com.andrealfredklug.klugstore.Adapter.App_spenden_Adapter;
import com.andrealfredklug.klugstore.R;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

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

import java.util.ArrayList;

public class App_spenden extends Fragment {

    TextView keineApps;

    public ALoadingDialog aLoadingDialog;

    final String TAG = "App spenden";

    App_spenden_Adapter adapter;
    ListView listView;

    ArrayList appName, appPackage, appUtc;

    String abruf_url = "https://www.klug-aug.de/projekte/klugstore/php/android-scripte/entwicklerPHP/console/app_spenden_information.php";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View app_spenden = inflater.inflate(R.layout.activity_app_spenden, null);
        return app_spenden;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

        adapter = new App_spenden_Adapter(getActivity(), appName, appPackage, appUtc);
        listView = (ListView)view.findViewById(R.id.as_listview);

        aLoadingDialog = new ALoadingDialog(getActivity());
        keineApps = (TextView)view.findViewById(R.id.as_keine_apps_textView);
        keineApps.setVisibility(View.GONE);

        appName = new ArrayList<String>();
        appPackage = new ArrayList<String>();
        appUtc = new ArrayList<String>();


        AppsImport();
    }

    private void AppsImport() {
    aLoadingDialog.show();

        RequestQueue queue = Volley.newRequestQueue(getActivity());

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, abruf_url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
            Log.e(TAG, "" + response.toString());

            String json = response.toString();
            try {
                JSONObject jsonObject = new JSONObject(json);

                if (jsonObject.getString("status").equals("Session fehler")){
                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AlertDialogTheme);
                    View view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_error_dialog, getView().findViewById(R.id.layoutDialogContainer));


                    builder.setView(view);
                    ((TextView) view.findViewById(R.id.textTitle)).setText("Session");
                    ((TextView) view.findViewById(R.id.textView_error)).setText("Bitte melden Sie sich erneut an oder wenden Sie sich an den Support: support@klug-aug.de\n\n");
                    ((Button) view.findViewById(R.id.buttonAction)).setText(getString(R.string.okay));
                    ((ImageView) view.findViewById(R.id.image_error)).setImageResource(R.drawable.ic_error);

                    final AlertDialog alertDialog = builder.create();

                    view.findViewById(R.id.buttonAction).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            alertDialog.dismiss();
                            aLoadingDialog.dismiss();
                        }
                    });

                    if (alertDialog.getWindow() != null) {
                        alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
                    }


                    alertDialog.show();

                }else if(jsonObject.getString("status").equals("Du bist nicht angemeldet.")){
                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AlertDialogTheme);
                    View view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_error_dialog, getView().findViewById(R.id.layoutDialogContainer));


                    builder.setView(view);
                    ((TextView) view.findViewById(R.id.textTitle)).setText("Abgemeldet");
                    ((TextView) view.findViewById(R.id.textView_error)).setText("Du bist abgemeldet. Bitte melde dich erneut an.\n");
                    ((Button) view.findViewById(R.id.buttonAction)).setText(getString(R.string.okay));
                    ((ImageView) view.findViewById(R.id.image_error)).setImageResource(R.drawable.ic_error);

                    final AlertDialog alertDialog = builder.create();

                    view.findViewById(R.id.buttonAction).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            alertDialog.dismiss();
                            aLoadingDialog.dismiss();
                        }
                    });

                    if (alertDialog.getWindow() != null) {
                        alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
                    }


                    alertDialog.show();
                } else if (jsonObject.getString("status").equals("keine Apps")) {
                    keineApps.setVisibility(View.VISIBLE);
                    aLoadingDialog.dismiss();

                } else if (jsonObject.getString("status").equals("es gibt Apps")) {
                    aLoadingDialog.dismiss();

                    JSONObject jsonApps = new JSONObject(jsonObject.getString("Apps"));

                    String anzahl = response.getString("AppAnzahl").trim();
                    Integer anzahlInt = Integer.parseInt(anzahl);

                    if (anzahlInt == 1){
                        String appN, appP, appU;
                        appN = jsonApps.getString("app_name");
                        appP = jsonApps.getString("package");
                        appU = jsonApps.getString("utc");

                        appName.add(appN);
                        appPackage.add(appP);
                        appUtc.add(appU);

                        listView.setVisibility(View.VISIBLE);
                        listView.setAdapter(adapter);

                    } else if (anzahlInt > 1) {

                        JSONArray name = jsonApps.getJSONArray("app_name");
                        JSONArray pack = jsonApps.getJSONArray("package");
                        JSONArray utc = jsonApps.getJSONArray("utc");

                        for(int i = 0; i < anzahlInt; i++){
                         appName.add(name.get(i));
                         appPackage.add(pack.get(i));
                         appUtc.add(utc.get(i));
                        }

                        Log.e(TAG, appName.toString());
                        Log.e(TAG, appPackage.toString());
                        Log.e(TAG, appUtc.toString());
                        listView.setVisibility(View.VISIBLE);
                        listView.setAdapter(adapter);
                    }


                }

            } catch (JSONException e) {
                throw new RuntimeException(e);
            }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        queue.add(jsonObjectRequest);
    }
}

Mein Adapter:

Java:
package com.andrealfredklug.klugstore.Adapter;

import android.app.Activity;
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 com.andrealfredklug.klugstore.R;

import java.util.ArrayList;

public class App_spenden_Adapter extends ArrayAdapter<String> {
    private final Activity context;
    private ArrayList appname = new ArrayList<String>();
    private ArrayList packagename = new ArrayList<String>();
    private ArrayList utc = new ArrayList<String>();

    public App_spenden_Adapter(Activity context,  ArrayList<String> appname, ArrayList<String> packagename, ArrayList<String> utc){
        super(context, R.layout.app_spenden_listview, packagename);

        this.context = context;
        this.appname = appname;
        this.packagename = packagename;
        this.utc = utc;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        LayoutInflater inflater=context.getLayoutInflater();
        View rowView=inflater.inflate(R.layout.app_spenden_listview, null,true);

        TextView appnameText = (TextView) rowView.findViewById(R.id.as_appname_textView);
        TextView apppackageText = (TextView) rowView.findViewById(R.id.as_list_package_textView);
        TextView apputcText = (TextView) rowView.findViewById(R.id.as_list_utc_textView);

        appnameText.setText(appname.get(position).toString());
        apppackageText.setText(packagename.get(position).toString());
        apputcText.setText(utc.get(position).toString());
        return rowView;
    }
}

Ich weiß nicht woran das liegt, das es diesmal nicht klappt und sonst immer klappt.

Ich bedanke mich mal bei euch für eure Hilfe 😉
 

Robert Zenz

Top Contributor
Java:
189:                        listView.setAdapter(adapter);

Augenscheinlich ist adapter null. Wenn ich raten muesste (und das muss ich weil ich den Code nicht so genau gelesen habe) wuerde ich sagen das onViewCreated erst aufgerufen wird nachdem die Anfrage durchgefuehrt wurde.
 

wer112

Top Contributor
Java:
189:                        listView.setAdapter(adapter);

Augenscheinlich ist adapter null. Wenn ich raten muesste (und das muss ich weil ich den Code nicht so genau gelesen habe) wuerde ich sagen das onViewCreated erst aufgerufen wird nachdem die Anfrage durchgefuehrt wurde.
Ne das Problem habe ich gelöst, musste den Adapter erst deklarieren nachdem der AppsImport erfolgt ist.
 
Ähnliche Java Themen
  Titel Forum Antworten Datum
J ListView Item individuell einfärben Android & Cross-Platform Mobile Apps 17
I Android ListView, Werte aktualisieren ohne die Liste komplett neu zu laden Android & Cross-Platform Mobile Apps 5
W ListView OnItemClicklistener setzen mit Ausgabe Android & Cross-Platform Mobile Apps 35
K Null-Pointer-Exception in ListView - wird über Datenbank gefüllt Android & Cross-Platform Mobile Apps 1
I Android ListView (Custom) soll auf Hardwaretasten nicht reagieren. Android & Cross-Platform Mobile Apps 10
W ListView und Arrays... Android & Cross-Platform Mobile Apps 68
W Android Wieso kann ich keine ListView mehr zum Layout hinzufügen? Android & Cross-Platform Mobile Apps 1
W Android Kann keine ListView mehr in der MainActivtiy anzeigen, obwohl noch sehr viel Platz frei ist Android & Cross-Platform Mobile Apps 1
L ListView aktuallisiert sich nicht Android & Cross-Platform Mobile Apps 15
N Probleme mit custom dynamic ListView Android & Cross-Platform Mobile Apps 15
L Android ListView kollabiert in Scrollview Android & Cross-Platform Mobile Apps 9
A ImageButton in ListView Item bei klick ändern Android & Cross-Platform Mobile Apps 3
J Android Suche in einer ListView Android & Cross-Platform Mobile Apps 3
H Android ArrayList <-> ArrayAdapter <-> ListView Android & Cross-Platform Mobile Apps 10
L Android ListView swipe zum löschen Android & Cross-Platform Mobile Apps 1
B Android ListView set custom check Image and delete Android & Cross-Platform Mobile Apps 0
M Android ListView wird nicht dargestellt Android & Cross-Platform Mobile Apps 2
Maresuke Android Android ListView Textfarbe und Texthintergrund ändern? Android & Cross-Platform Mobile Apps 5
A Android Problem mit ListView und OnItemClickListener.. Android & Cross-Platform Mobile Apps 10
S Listview Einträge aus "xml" Datei Android & Cross-Platform Mobile Apps 1
S Android Studio MySql Daten in Listview mit sub Item Android & Cross-Platform Mobile Apps 11
S Textdatei in ListView einlesen Tutorial gesucht!? Android & Cross-Platform Mobile Apps 3
kaoZ Tutorial .xml Layouting für z.B ListView elemente Android & Cross-Platform Mobile Apps 7
M Android ListView und Checkbox Android & Cross-Platform Mobile Apps 6
L TableRows in ListView darstellen Android & Cross-Platform Mobile Apps 2
M ListView mit ListAdapter füllen Android & Cross-Platform Mobile Apps 5
U Android ListView Frage Android & Cross-Platform Mobile Apps 6
L Android SearchBox für Custom Listview Android & Cross-Platform Mobile Apps 5
H Android ListView Images aus dem Internet via Thread Android & Cross-Platform Mobile Apps 3
T Android: ListView-Adapter: Adapter wird ständig aufgerufen Android & Cross-Platform Mobile Apps 2
H Android SAX|ListView NullPointerException Android & Cross-Platform Mobile Apps 2
A Probleme mit ListView / ArrayAdapter Android & Cross-Platform Mobile Apps 3
W Navigation MenuItem Switch Fehler Android & Cross-Platform Mobile Apps 6
J Das Beispiel von Android erzeugt Fehler Android & Cross-Platform Mobile Apps 8
W Volley onDestroy angemeldet bleiben Fehler... unabhänging vom Login Android & Cross-Platform Mobile Apps 37
P undefinierbarer Fehler Android Android & Cross-Platform Mobile Apps 8
M INSTALL_FAILED_OLDER_SDK - Was muß ich tun damit der Fehler verschwindet Android & Cross-Platform Mobile Apps 8
lolcore android studio: fehler bei laden des emulators Android & Cross-Platform Mobile Apps 10
T Fehler Android Studio: java.net.MalformedURLException: no protocol: http%3A%2F%2Fwww.mal ..... Android & Cross-Platform Mobile Apps 2
Arif Android Android Studio: Fehler beim Einbinden fremder Bibliothek? Android & Cross-Platform Mobile Apps 2
J error: <identifier> expected error: illegal start of type "Wo ist der Fehler?" Android & Cross-Platform Mobile Apps 5
G Gluon Fehler Meldung Android & Cross-Platform Mobile Apps 4
B Android App Fehler Android & Cross-Platform Mobile Apps 21
JavaWolf165 Android Fehler beim Speichern/Downloaden einer Datei Android & Cross-Platform Mobile Apps 2
R Android Wie kann ich diesen Fehler beheben? Android & Cross-Platform Mobile Apps 10
M Android Fehler beim Parsen. Android & Cross-Platform Mobile Apps 29
S IF Anweisung zeigt Fehler trotz richtiger Eingabe? Android & Cross-Platform Mobile Apps 7
S Fehler beim Textdatei einlesen!? Android & Cross-Platform Mobile Apps 7
A Mehrere Fehler beim Compilieren Android & Cross-Platform Mobile Apps 4
H Fehler bei leerem TextEdit Android & Cross-Platform Mobile Apps 4
H Fehler Actionbar Theme ändern Android & Cross-Platform Mobile Apps 2
J Wo liegt der Fehler? Android & Cross-Platform Mobile Apps 0
M Fehler ohne Sinn? java.lang.RuntimeException: Unable to start activity ComponentInfo Android & Cross-Platform Mobile Apps 11
G Fehler beim Import "Invalid project description" Android & Cross-Platform Mobile Apps 2
A Fehler beim Starten eines Intents - alles in einer Klasse funktioniert... Android & Cross-Platform Mobile Apps 4
C Java ME Fehler JSR-172 Android & Cross-Platform Mobile Apps 3
F Bilder in Java importieren (Fehler?) Android & Cross-Platform Mobile Apps 5
Apo Android Dx bad class Fehler Android & Cross-Platform Mobile Apps 4
F Android Fehler in Spinner Android & Cross-Platform Mobile Apps 3
S Android Fehler beim Anzeigen meines Apps auf Galaxy Tab Android & Cross-Platform Mobile Apps 4
J Fehler: Unbehandelte Ausnahme Android & Cross-Platform Mobile Apps 8
A Midlet bei Fehler elegant beenden mit Fehlermeldung Android & Cross-Platform Mobile Apps 4
S Compiler Fehler Android & Cross-Platform Mobile Apps 2
B Fehler bei Midlet installation? "Aktion Abgebrochen&quo Android & Cross-Platform Mobile Apps 10

Ähnliche Java Themen


Oben