0

В Android приложении я присваиваю ListView id Listview из layout, но приложение завершается NPE. Я смотрел дебагером, и действительно мой ListView ни чем не инициализирован. В чем может быть проблема?

  public class MainActivity extends AppCompatActivity {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

//курсоры для работы с БД
private static Cursor cursor;
private DBController dbController;
private UIController uiController;
private ListView lvObjective;
private SimpleCursorAdapter scAdapter;
/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    dbController = new DBController();
    uiController = new UIController();
 //   lvObjective = new ListView();
    lvObjective = (ListView) findViewById(R.id.lvObjective);
    AppContext.getDbAdapterImport().open();
    AppContext.getDbAdapterImport().Check();
    cursor = dbController.getAllData(AppContext.getDbAdapterImport().getmDB(), AppContext.getDbAdapterImport().getDbTable()[0]);

    crRightListView();

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

}

private void crRightListView()
{
    String[] from1 = new String[] { getResources().getString(R.string.TactID),
            getResources().getString(R.string.NameObjective)};
    int[] to1 = new int[] {R.id.tvTID, R.id.tvName};
    scAdapter = new SimpleCursorAdapter(this, R.layout.db_item, cursor, from1, to1);
    Log.d("LOGCOUNT", "" + scAdapter.getCount());
    lvObjective.setAdapter(scAdapter);

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        cursor.moveToFirst();
        textView.setText(cursor.getString(2));
        //getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER))
        return rootView;
    }
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "SECTION 1";
            case 1:
                return "SECTION 2";
            case 2:
                return "SECTION 3";
        }
        return null;
    }
}

}

logcat c NPE:

07-19 09:21:21.277 4463-4463/? E/AndroidRuntime: FATAL EXCEPTION: main
                                             Process: ru.itsmygame.tacticalgenirator, PID: 4463
                                             java.lang.RuntimeException: Unable to start activity ComponentInfo{ru.itsmygame.tacticalgenirator/ru.itsmygame.tacticalgenirator.MainActivity}: 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:2465)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2530)
                                                 at android.app.ActivityThread.access$900(ActivityThread.java:163)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1358)
                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                 at android.os.Looper.loop(Looper.java:135)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5536)
                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:372)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1397)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1192)
                                              Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                                                 at ru.itsmygame.tacticalgenirator.MainActivity.crRightListView(MainActivity.java:94)
                                                 at ru.itsmygame.tacticalgenirator.MainActivity.onCreate(MainActivity.java:74)
                                                 at android.app.Activity.performCreate(Activity.java:5993)
                                                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2418)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2530) 
                                                 at android.app.ActivityThread.access$900(ActivityThread.java:163) 
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1358) 
                                                 at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                 at android.os.Looper.loop(Looper.java:135) 
                                                 at android.app.ActivityThread.main(ActivityThread.java:5536) 
                                                 at java.lang.reflect.Method.invoke(Native Method) 
                                                 at java.lang.reflect.Method.invoke(Method.java:372) 
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1397) 
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1192) 

Вот моя разметка:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="ru.itsmygame.tacticalgenirator.MainActivity$PlaceholderFragment">

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ListView
        android:id="@+id/lvObjective"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/section_label"
        android:layout_marginTop="24dp" />

</RelativeLayout>
2
  • 1
    Разметку покажите
    – ЮрийСПб
    18 июл 2017 в 23:31
  • 1
    Перенесите ваш ListView в fragment_main, а его код из MainActivity в PlaceholderFragment, если он должен быть во фрагменте, или на оборот, перенесите ListView из fragment_main в activity_main` и оставьте на месте код в MainActivity
    – McDaggen
    19 июл 2017 в 7:42

1 ответ 1

5

Дело в том, что метод findViewById может возвращать null в строке lvObjective = (ListView) findViewById(R.id.lvObjective);. А это случается, когда:

  • в файле с разметкой нет такого элемента

  • не совпадает название id

  • id соответствующего элемента не задан

  • неверно установлен id layout'a в методе setContentView

1
  • 1
    Я понял в чём проблема. Мой ListView находился не в том layout. Поэтому и передавался null. 19 июл 2017 в 0:37

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.