0

Layout->

activity_main.xml
content_main.xml

Logic ->

ActivityMain.java
MainLogic.java

2 Issues: (second issue is the actual issue)

1) java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.app./com.test.app.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object referenc

2) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference at android.app.Activity.findViewById(Activity.java:2124) at com.test.app.MainLogic.CreateListView(MainLogic.java:51)

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.CoordinatorLayout
    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:fitsSystemWindows="true"
    tools:context=".MainActivity">

<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
    android:layout_width="match_parent" android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar android:id="@+id/toolbar"
        android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main" />


<android.support.design.widget.FloatingActionButton android:id="@+id/fab"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"     android:layout_margin="@dimen/fab_margin"
    android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

content_main.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main"
    android:id="@+id/main_layout">

<LinearLayout
    android:id="@+id/linLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_centerHorizontal="true">
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/origin_string"
        android:textSize="20sp"/>
    <TextView
        android:id="@+id/textView2"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="@string/random_string_sample"
        android:textSize="20sp"
        />
</LinearLayout>
    <Button
        android:id="@+id/btnClick1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/linLayout"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="61dp"
        android:text="@string/app_name" />
<ListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/listview1"
    android:layout_below="@+id/btnClick1">
</ListView>

</RelativeLayout>

ActivityMain.java->

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setIcon(R.drawable.logo);
        start();
    }
    void start(){
        ListView listView = (ListView) findViewById(R.id.listview1); //ADDED
        MainLogic ml = new MainLogic();
        ml.CreateListView(>ADDED: listview<);
    }
}

MainLogic.java-> EDIT: added class line below Removed extends Activity

public class MainLogic {

public void CreateListView() {
    final ListView list_View1 = (ListView) findViewById(R.id.listview1);
    final String[] listViewStrings = new String[]{"first_item", "second_item", "third_item", "fouth_item", "fifth_item", "sixth_item", "seventh_item", "eigth_item"};
    ArrayAdapter list_adapter = new ArrayAdapter<String>(`<s>`getApplicationContext()`</s>`, android.R.layout.simple_list_item_1,listViewStrings);
    //list_adapter.addAll(>REMOVED: listViewStrings.toString()<);
    list_View1.setAdapter(list_adapter); // Use data, pass the adapter with the strings, numbers, etc.
    }
}

Whom ever does answer this if you can explain why I am doing things wrong and also possibly show me how to fix the code, that would be great. I have read over these links:

http://www.vogella.com/tutorials/AndroidListView/article.html

http://developer.android.com/guide/topics/ui/layout/listview.html

http://www.tutorialspoint.com/android/android_list_view.htm

I do not see the inherent flaw in my code except that i am implementing the logic in an external class then creating an object to call the method.

SOLUTION ->

ActivityMain.java->

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setIcon(R.drawable.logo);
        start();
    }

    public void start(){
        MainLogic ml = new MainLogic();
        ml.CreateListView(this);
    }

}

MainLogic.java->

public class MainLogic {

public void CreateListView(final MainActivity newActivity) {

    final ListView list_View1 = (ListView) newActivity.findViewById(R.id.listview1);
        final String[] listViewStrings = new String[]{"first_item", "second_item", "third_item", "fouth_item", "fifth_item", "sixth_item", "seventh_item", "eigth_item"};
//      This will adapt array that listview can work with i.e. generate all rows
        ArrayAdapter list_adapter = new ArrayAdapter<>(newActivity.getApplicationContext(), android.R.layout.simple_list_item_1, listViewStrings);
        list_adapter.addAll();
        list_View1.setAdapter(list_adapter); // Use data, pass the adapter with the strings, numbers, etc.

        list_View1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapter, View view, int position_in_array, long id) {
                // Logic for what happens when clicked
                // Context => http://stackoverflow.com/questions/3572463/what-is-context-in-android
                int position = position_in_array;
                String item_value = (String) adapter.getItemAtPosition(position);
                String item = "Item: " + listViewStrings.toString() + " / value " + item_value + " ." ;
                Toast.makeText(newActivity.getApplicationContext(), item, Toast.LENGTH_SHORT).show();
            }
        });  

} }

codelinx
  • 107
  • 1
  • 1
  • 10
  • Please, add full MainLogic class. – v.ladynev Dec 06 '15 at 22:25
  • I added the wrapping class holder-> public class MainLogic extends Activity{ ... } public class MainActivity extends AppCompatActivity { ... } – codelinx Dec 07 '15 at 02:47
  • **If you are wondering why the error line number is so high its because i have lots of lines of notes in commented blocks** – codelinx Dec 07 '15 at 03:29
  • Okay so this code does work, but only when it is placed inside the MainActivity.java file public void CreateListView() { ... **list_adapter.addAll(); // CHANGED THIS LINE** ... } Can anyone tell me why this is not able to be run outside the MainActivity.java file, is it the context, is it the permissions, is it the reference to **final ListView list_View1 = (ListView) findViewById(R.id.listview1);** or something else? – codelinx Dec 07 '15 at 03:45

1 Answers1

1

The error Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference indicates that the ListView could not be found.

The findViewById you are calling is of MainLogic instead of MainActivity. And since your ListView is in MainActivity, that's why it could not find the ListView. Try to pass the MainActivity.this from MainActivity to MainLogic. Also, I think that there is no need to use list_adapter.addAll since you have passed the array in the constructor of ArrayAdapter.

So here's an example:

MainActivity:

ml.CreateListView(this);

MainLogic:

public void CreateListView(Activity activity) {
    ListView list_View1 = (ListView) activity.findViewById(R.id.listview1);
    final String[] listViewStrings = new String[]{"first_item", "second_item", "third_item", "fouth_item", "fifth_item", "sixth_item", "seventh_item", "eigth_item"};
    ArrayAdapter list_adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,listViewStrings);
    list_View1.setAdapter(list_adapter); // Use data, pass the adapter with the strings, numbers, etc.
}
David Fang
  • 1,777
  • 1
  • 14
  • 19
  • I thought this was the issue(obviously because of the error), however i did try passing list_view1, but not like this. I will try this now and let you know the results. – codelinx Dec 07 '15 at 03:52
  • Another thing I forgot: remove `extends Activity` from MainLogic because it's not an Activity. – David Fang Dec 07 '15 at 04:05
  • Things i have done: 1) Removed "extends Activity" from MainLogic.java 2) added "private Context context;" in MainLogic.java 3) added in ActivityMain.java "ListView listView = (ListView) findViewById(R.id.listview1);" 4) pass this object to the class "ml.CreateListView(listView);" _However the list are not populating any longer and there are no more errors. If i use this class in the MainActivity.java it works without questions asked._How can i pass or setup the proper "context" from a non-Activity class? – codelinx Dec 07 '15 at 04:18
  • One more note, I have added the "context.getApplicationContext()" and also I have tried using "context" for *ArrayAdapter list_adapter = new ArrayAdapter(context,...,...)* and this still does not show the items in the list. what am i missing here about the proper context outside of an activity class? – codelinx Dec 07 '15 at 04:25
  • Ok, I have some misunderstanding in passing objects in Java. The view passed to CreateListView is copied so modifying it would not change what you actually see. Sorry for guiding you the wrong way. According to http://stackoverflow.com/questions/8323777/ you can pass `this`. I've updated answer with new code. – David Fang Dec 07 '15 at 04:45
  • Thank you david, we both worked on the same thing at times and i appreciate all your help.The last and final issue with list not populating was i did not call "start();" from onCreate() method. – codelinx Dec 07 '15 at 05:33