NullPointException w adapterze ListView.

Odpowiedz Nowy wątek
2019-08-18 00:02
0

Oto listingi:

MainAcivity.java

package com.example.polmedia;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnCheckedChangeListener{

    ArrayList<ChannelData> list = new ArrayList<ChannelData>();

    public void onListItemClick(ListView parent, View v, int position, long id){

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

        ((RadioGroup)findViewById(R.id.radioGroup1)).setOnCheckedChangeListener((OnCheckedChangeListener) this);
        RadioButton S1 = (RadioButton) findViewById(R.id.S1);
        S1.setChecked(true);

        ////////////////////////////////////////

        ChannelsList tmp = new ChannelsList();

        try {
            list = tmp.getChannelsList("server1");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        Collections.sort(list);

        //////////////////////////////////////////////////

        ArrayAdapter<ChannelData> adapter = new ArrayAdapter<ChannelData>(getApplicationContext(), 
                android.R.layout.test_list_item, list) {

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view = super.getView(position, convertView, parent);

                ChannelData currentChannel = getItem(position);

                // Inflate only once
                if(convertView == null) {
                    convertView = getLayoutInflater()
                                    .inflate(R.layout.custom_item, 
                                            null, false);

                } 

                ViewHolder viewHolder = new ViewHolder();
                viewHolder.ChannelName =
                        (TextView)convertView.findViewById(R.id.channel_name);

                convertView.setTag(viewHolder);

                TextView text = 
                        ((ViewHolder)convertView.getTag()).ChannelName;
                text.setText(currentChannel.getAName());
                text.setTextColor(Color.WHITE);

                return view;
            }
        };

        // Lista.
        ListView lv = (ListView) findViewById(R.id.listView1);

        // Powiązanie  ListView z adapterem.
        lv.setAdapter(adapter);

    }

    static class ViewHolder{
        TextView ChannelName;           
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        String groupName ="";

        groupName+="Fancy radio group: ";

        RadioButton rb = (RadioButton) findViewById(checkedId);
        Toast.makeText(this, groupName+rb.getText(), Toast.LENGTH_LONG).show();
    }

}

custom_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="@dimen/activity_horizontal_margin">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/channel_name" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Small Text"
        android:id="@+id/channel_url" />
</LinearLayout>

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#080000"
        android:orientation="horizontal" >

        <RadioButton
            android:id="@+id/S1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_weight=".335"
            android:background="@drawable/radio_states_red"
            android:button="@null"
            android:checked="false"
            android:gravity="center"
            android:padding="10dp"
            android:text="S1"
            android:textColor="@drawable/radio_text" />

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/radio_states_red"
            android:button="@null"
            android:padding="10dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:textColor="@drawable/radio_text"
            android:text="S2"
            android:layout_weight=".335"
            android:gravity="center"/>

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/radio_states_red"
            android:button="@null"
            android:padding="10dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:textColor="@drawable/radio_text"
            android:text="S3"
            android:layout_weight=".335"
            android:gravity="center"/>

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/radio_states_red"
            android:button="@null"
            android:padding="10dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:textColor="@drawable/radio_text"
            android:text="S4"
            android:layout_weight=".335"
            android:gravity="center"/>

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/radio_states_red"
            android:button="@null"
            android:padding="10dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:textColor="@drawable/radio_text"
            android:text="S5"
            android:layout_weight=".335"
            android:gravity="center"/>

    </RadioGroup>

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@drawable/listview_border"
        android:clickable="true"
        android:fitsSystemWindows="true"
        android:layoutMode="opticalBounds"
        android:padding="25dp"
        android:textColor="#A0E0ED"
        android:textSize="17sp"
        android:textStyle="bold" >

    </ListView>

</LinearLayout>

i logi:

08-17 17:57:31.780: D/AndroidRuntime(802): Shutting down VM
08-17 17:57:31.780: W/dalvikvm(802): threadid=1: thread exiting with uncaught exception (group=0xb4af0ba8)
08-17 17:57:31.860: E/AndroidRuntime(802): FATAL EXCEPTION: main
08-17 17:57:31.860: E/AndroidRuntime(802): Process: com.example.polmedia, PID: 802
08-17 17:57:31.860: E/AndroidRuntime(802): java.lang.NullPointerException
08-17 17:57:31.860: E/AndroidRuntime(802):  at com.example.polmedia.MainActivity$1.getView(MainActivity.java:87)
08-17 17:57:31.860: E/AndroidRuntime(802):  at android.widget.AbsListView.obtainView(AbsListView.java:2240)
08-17 17:57:31.860: E/AndroidRuntime(802):  at android.widget.ListView.measureHeightOfChildren(ListView.java:1263)
08-17 17:57:31.860: E/AndroidRuntime(802):  at android.widget.ListView.onMeasure(ListView.java:1175)
08-17 17:57:31.860: E/AndroidRuntime(802):  at android.view.View.measure(View.java:16497)
08-17 17:57:31.860: E/AndroidRuntime(802):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
08-17 17:57:31.860: E/AndroidRuntime(802):  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
08-17 17:57:31.860: E/AndroidRuntime(802):  at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
08-17 17:57:31.860: E/AndroidRuntime(802):  at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
08-17 17:57:31.860: E/AndroidRuntime(802):  at android.view.View.measure(View.java:16497)
08-17 17:57:31.860: E/AndroidRuntime(802):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
08-17 17:57:31.860: E/AndroidRuntime(802):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
08-17 17:57:31.860: E/AndroidRuntime(802):  at android.view.View.measure(View.java:16497)
08-17 17:57:31.860: E/AndroidRuntime(802):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
08-17 17:57:31.860: E/AndroidRuntime(802):  at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
08-17 17:57:31.860: E/AndroidRuntime(802):  at android.view.View.measure(View.java:16497)
08-17 17:57:31.860: E/AndroidRuntime(802):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
08-17 17:57:31.860: E/AndroidRuntime(802):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
08-17 17:57:31.860: E/AndroidRuntime(802):  at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
08-17 17:57:31.860: E/AndroidRuntime(802):  at android.view.View.measure(View.java:16497)
08-17 17:57:31.860: E/AndroidRuntime(802):  at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916)
08-17 17:57:31.860: E/AndroidRuntime(802):  at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113)
08-17 17:57:31.860: E/AndroidRuntime(802):  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295)

Jak widać w pewnym momencie następuje wyjątek NullPointException. Jak to mogę naprawić i jaka jest przyczyna? Dodam, że program piszę w Eclipse.

edytowany 5x, ostatnio: cerrato, 2019-08-18 00:38

Pozostało 580 znaków

2019-08-18 00:46
0

Kijowy ten logger trochę, ale zapnij się breakpointem na na linijce 87 i puść debug sobie i będzie jasne.
Pewnie ta metoda findViewById() rzuca npe.
No ale Clean Code aż się prosi do przeczytania.

ListView lv = (ListView) findViewById(R.id.listView1);

        // Powiązanie  ListView z adapterem.
        lv.setAdapter(adapter);

Pozostało 580 znaków

2019-08-18 09:06
0

Zmieniłem trochę kod, ale terz wyświetla mi się tylko ekran główny .

package com.example.polmedia;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

public class MainActivity extends Activity implements OnCheckedChangeListener{

    ArrayList<ChannelData> list = new ArrayList<ChannelData>();
    private ListView lv;

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

         lv = (ListView) findViewById(R.id.listView1);

        ((RadioGroup)findViewById(R.id.radioGroup1)).setOnCheckedChangeListener((OnCheckedChangeListener) this);
        RadioButton S1 = (RadioButton) findViewById(R.id.S1);
        S1.setChecked(true);

        ////////////////////////////////////////

        ChannelsList tmp = new ChannelsList();

        try {
            list = tmp.getChannelsList("server1");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        Collections.sort(list);

        initChannelsListView();
    }

    private void initChannelsListView() {
        ChannelsArrayAdapter adapter = new ChannelsArrayAdapter(this, 0, null, list);
        lv.setAdapter(adapter);

    }

}
package com.example.polmedia;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class ChannelsArrayAdapter extends ArrayAdapter<String> {
    private Activity context;
    private ArrayList<ChannelData> list;

    public ChannelsArrayAdapter(Context context, int resource, Activity context2, ArrayList<ChannelData> list) {
        super(context, resource);
        context = context2;
        this.list = list;
    }

    static class ViewHolder {
        public TextView text;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        View rowView = convertView;
        if(rowView == null) {
            LayoutInflater layoutInflater = context.getLayoutInflater();
            rowView = layoutInflater.inflate(R.layout.custom_item, null, true);
            viewHolder = new ViewHolder();
            viewHolder.text = (TextView) rowView.findViewById(R.id.channel_name);
            rowView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) rowView.getTag();
        }
        System.out.println(list.get(position).getAName());

        viewHolder.text.setTextColor(Color.WHITE);
        viewHolder.text.setText(list.get(position).getAName());
        return rowView;
    }
}

Ale teraz nie wyśwetla sie nawet pasek postępu.

edytowany 1x, ostatnio: xenix33, 2019-08-18 09:19

Pozostało 580 znaków

2019-08-19 06:57
0
  1. Nie używaj Listview - słowem kluczem jest RecyclerView
  2. ChannelsArrayAdapter adapter = new ChannelsArrayAdapter(this, 0, null, list); przekazujesz null jako context, potem próbujesz wczytać layoutów na nim. Tip: context w metodzie getView możesz pobrać z parenta. Pewnie jeszcze jest metoda getContext() w samym adapterze.

Pozostało 580 znaków

2019-08-19 16:10
0

Ad. Neutrino. Napisałeś , że Clean Code ,aż się prosi. Poczytałem sobie
https://1024kb.pl/programowanie/java/clean-code/.

Ja tak piszę od 20 lat. Tylko ten program , to prowizorka. Robię nawet więcej, niż tam jest napisane, bo stosuję prefiksy do nazw zmiennych. Ameryki nie odkryli.

Ale dziwi mnie jedna rzecz na tej stronie. Napisali, że im mniej komentarzy, tym lepiej. Dla mnie , to bzdet. Gość nie wie o czym mówi.

Aha. Problem rozwiązałem. Dziękuję za pomysły.

Pozostało 580 znaków

Odpowiedz
Liczba odpowiedzi na stronę

1 użytkowników online, w tym zalogowanych: 0, gości: 1, botów: 0