This question already has an answer here:
I am trying to pull data from my database created in my MainActivity class into my CompleteListFragmen fragment in order to populate a list of clickable items. I am getting the following error when I run the code but I am not able to identify what I need to change. Can anyone advise in relation to my code below what needs changed?
Unable to start activity ComponentInfo{com.example.claire.androidappcsc3054tabs/com.example.claire.androidappcsc3054tabs.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.example.claire.androidappcsc3054tabs.LocationOperations.getAllLocations()' on a null object reference
NB: For clarity, the app is for displaying a list of film set locations thus the naming of SetLocation etc.
MainActivity class :
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
DatabaseHelper myDb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbCreate();
/**Calls DatabaseHelper class **/
myDb = new DatabaseHelper(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
public void dbCreate () {
try {
SQLiteDatabase GOTdb = this.openOrCreateDatabase("LocationInfo", MODE_PRIVATE, null);
GOTdb.execSQL("CREATE TABLE IF NOT EXISTS LocationInfo (ID integer primary key autoincrement, Name VARCHAR, Title VARCHAR, Image VARCHAR, Lat DOUBLE, Longitude DOUBLE )");
GOTdb.execSQL("INSERT INTO LocationInfo (Name, Title, Image, Lat, Longitude) VALUES('Downhill Beach','Dragonstone','dragonstone.png','-6.807531','55.167984')");
GOTdb.execSQL("INSERT INTO LocationInfo (Name, Title, Image, Lat, Longitude) VALUES('Larrybane','The Stormlands','thestormlandslarrybane.png','-6.362022','55.236086')");
GOTdb.execSQL("INSERT INTO LocationInfo (Name, Title, Image, Lat, Longitude) VALUES('Ballintoy Harbour','Pyke, The Iron Islands','pyketheironislands.png','-6.369466','55.244518')");
Cursor c = GOTdb.rawQuery("SELECT * FROM LocationInfo LIMIT 3", null);
int IDIndex = c.getColumnIndex("ID");
int NameIndex = c.getColumnIndex("Name");
int TitleIndex = c.getColumnIndex("Title");
int ImageIndex = c.getColumnIndex("Image");
int LatIndex = c.getColumnIndex("Lat");
int LongitudeIndex = c.getColumnIndex("Longitude");
c.moveToFirst();
while (c != null) {
Log.i("ID", Integer.toString(c.getInt(IDIndex)));
Log.i("Name", c.getString(NameIndex));
Log.i("Title", c.getString(TitleIndex));
Log.i("Image", c.getString(ImageIndex));
Log.i("Lat", Double.toString(c.getDouble(LatIndex)));
Log.i("Longitude", Double.toString(c.getDouble(LongitudeIndex)));
c.moveToNext();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new CompleteListFragment(), "List Items");
adapter.addFragment(new CompleteMapFragment(), "Complete Map");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
CompleteListFragment class:
public class CompleteListFragment extends ListFragment
{
private LocationOperations locationDBoperations;
List locations = locationDBoperations.getAllLocations();
@Override
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
locationDBoperations = new LocationOperations(getContext());
locationDBoperations.open();
setListAdapter(new ArrayAdapter<>(getActivity(), R.layout.my_list, R.id.locationlistitem, locations));
}
public void onListItemClick(ListView parent, View v, int position, long id)
{
Object selected = locations.get(position);
DetailFragment F
=(DetailFragment)getFragmentManager().findFragmentById(R.id.detailFragment);
if (F != null && F.isInLayout()) {
F.setSelected(selected.toString()); //detail is in same activity as the completelistfragment
}
else
{
//the detail is in its own activity
Intent i = new Intent (getActivity(), DetailActivity.class);
i.putExtra("location", selected.toString());
startActivity(i);
}
}
}
LocationOperations class:
public class LocationOperations {
//Database fields
private DatabaseHelper dbHelper;
private String[] LOCATION_TABLE_COLUMNS = {DatabaseHelper.ID,
DatabaseHelper.Name};
private SQLiteDatabase database;
public LocationOperations(Context context)
{ dbHelper = new DatabaseHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public List getAllLocations() {
List locations = new ArrayList();
Cursor cursor = database.query(DatabaseHelper.TableName, LOCATION_TABLE_COLUMNS, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {SetLocation location = parseLocation(cursor);
locations.add(location);
cursor.moveToNext();
}
cursor.close();
return locations;
}
private SetLocation parseLocation(Cursor cursor) {
SetLocation location = new SetLocation();
location.setId((cursor.getInt(0)));
location.setName(cursor.getString(1));
return location;
}
}
DatabaseHelper class:
public class DatabaseHelper extends SQLiteOpenHelper {
/**Database Name **/
public static final String DBName = "GOT.db";
/**Table Name **/
public static final String TableName = "LocationInfo";
/**Database Version **/
public static final int DBVersion = 1;
/**Column 1 **/
public static final String ID = "ID";
/**Column 2 **/
public static final String Name = "Name";
/**Column 3 **/
public static final String Title = "Title";
/**Column 4 **/
public static final String Description = "Description";
/**Column 5 **/
public static final String Image = "Image";
/**Column 6 **/
public static final String Lat = "Lat";
/**Column 7 **/
public static final String Longitude = "Long";
private static final String DATABASE_CREATE = "create table " + TableName
+ "(" + ID + " integer primary key autoincrement, " + Name +
" text not null, " + Title + " text not null, " + Description + " text not null, " +
Image + " varchar not null, " + Lat + " double not null, " + Longitude + " double not null);";
public DatabaseHelper(Context context) {
super(context, DBName, null, DBVersion);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TableName);
onCreate(db);
}
}
my_list XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://ift.tt/nIICcg"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#b7ffe9">
<TextView
android:id="@+id/locationlistitem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@+id/locationlistitem"
android:textSize="22sp" >
</TextView>
</LinearLayout>
complete_list_fragment XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://ift.tt/LrGmb4"
tools:context="com.example.claire.androidappcsc3054tabs.CompleteListFragment" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/one"
android:textSize="40dp"
android:textStyle="bold"
android:layout_centerInParent="true"/>
<TextView
android:id="@+id/locationName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40dp"
android:textStyle="bold"
android:layout_centerInParent="true"/>
<fragment
android:id="@+id/listFragment"
android:name="com.example.claire.androidappcsc3054tabs.CompleteListFragment"
android:layout_width="150dp"
android:layout_height="match_parent"
/>
<fragment
android:id="@+id/detailFragment"
android:name="com.example.claire.androidappcsc3054tabs.DetailFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="@layout/activity_detail"/>
</RelativeLayout>
Aucun commentaire:
Enregistrer un commentaire