0

I am trying to create an Android App that fetch data from the SQLite database and display them in a PageView( Swipe View). The App crashes anytime I try to run. Please help me to look at my code to see where I am getting it wrong.

My Main Activity is this :

public class MainActivity extends AppCompatActivity {

SectionsPagerAdapter mSectionsPagerAdapter;

ViewPager mViewPager;

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

    DataBaseAccess databaseAccess = DataBaseAccess.getInstance(this);
    databaseAccess.open();
    List<String> quotes = databaseAccess.getQuotes();
    databaseAccess.close();

    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(),getApplicationContext());


    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();
        }
    });

}


@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";
    private static final String Name_Key = "Name_Key";

    /*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);

        Bundle bundle=getArguments();

        if (bundle!=null)
        {
            String name=bundle.getString(Name_Key);
            setValues(rootView,name);
        }


        return rootView;
    }
    private void setValues( View v, String name)
    {
        TextView textview=(TextView) v.findViewById(R.id.name);
        textview.setText(name);
    }
}

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

    List<String> name;
    String[] name1;
    public SectionsPagerAdapter(FragmentManager fm, Context context) {
        super(fm);
        DataBaseAccess databaseAccess = DataBaseAccess.getInstance(null);
        databaseAccess.open();
        name=databaseAccess.getQuotes();
        for (int i=0; i<=name.size();i++)
        {
           name1[i]=name.get(i);
        }

    }

    @Override
    public Fragment getItem(int position) {

        Bundle bundle=new Bundle();
        bundle.putString(PlaceholderFragment.Name_Key,name1[position]);

        PlaceholderFragment deviceFragment= new PlaceholderFragment();
        deviceFragment.setArguments(bundle);
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return deviceFragment;


    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        return name1[position];
    }
}
}

My Class that Access the database and returns a list of Strings

public class DataBaseAccess {
private SQLiteOpenHelper openHelper;
private static SQLiteDatabase database;
private static DataBaseAccess instance;

/**
 * Private constructor to aboid object creation from outside classes.
 *
 * @param context
 */
public DataBaseAccess(Context context) {
    this.openHelper = new DatabaseOpenHelper(context);
}

/**
 * Return a singleton instance of DatabaseAccess.
 *
 * @param context the Context
 * @return the instance of DabaseAccess
 */
public static DataBaseAccess getInstance(Context context) {
    if (instance == null) {
        instance = new DataBaseAccess(context);
    }
    return instance;
}

/**
 * Open the database connection.
 */
public void open() {
    this.database = openHelper.getWritableDatabase();
}

/**
 * Close the database connection.
 */
public void close() {
    if (database != null) {
        //this.database.close();
    }
}

/**
 * Read all quotes from the database.
 *
 * @return a List of quotes
 */
public ArrayList getQuotes() {
    ArrayList<String> list = new ArrayList<>();
    Cursor cursor = database.rawQuery("SELECT * FROM quotes", null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        list.add(cursor.getString(0));
        cursor.moveToNext();
    }
    cursor.close();
    return list;
}
}

My Activity_main file

<?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:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="org.heywhyconcept.myapplicationscroll.MainActivity">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    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:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay">

    </android.support.v7.widget.Toolbar>

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

<android.support.v4.view.ViewPager
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

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

My Fragment_main file

<LinearLayout 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="org.heywhyconcept.myapplicationscroll.MainActivity$PlaceholderFragment">

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

<TextView
    android:id="@+id/name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="text"
    />
</LinearLayout>
halfer
  • 19,824
  • 17
  • 99
  • 186

1 Answers1

0

From the code you have provided, it seems that you are trying to access the table quotes using a SELECT statement without properly defining and creating the database's tables first.

You need to explicitly define the tables that should be present in your database. There is an excellent example of how to do this in the docs which I will paraphrase here:

public class FeedReaderDbHelper extends SQLiteOpenHelper {

    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "myDatabase.db";
    private static final String SQL_CREATE_ENTRIES =
    "CREATE TABLE quotes (" +
    "id INTEGER PRIMARY KEY, " +
    "quote TEXT)";

    public FeedReaderDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    //Create tables here
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_ENTRIES);
    }
}
Ed Holloway-George
  • 5,092
  • 2
  • 37
  • 66
  • I have a ready database in my program that I'm accessing through a class with this code. ' public class DatabaseOpenHelper extends SQLiteAssetHelper { private static final String DATABASE_NAME = "quotes.db"; private static final int DATABASE_VERSION = 1; public DatabaseOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } }' . It worked fine when I displayed it on a list view. Please help me out – Ayomide Adekunle Jan 14 '16 at 15:09
  • @AyomideAdekunle Then please provide the output of any logs you have that show the crash – Ed Holloway-George Jan 14 '16 at 15:10
  • FATAL EXCEPTION: main Process: org.heywhyconcept.myapplicationscroll, PID: 15057 java.lang.RuntimeException: Unable to start activity ComponentInfo{org.heywhyconcept.myapplicationscroll/org.heywhyconcept.myapplicationscroll.MainActivity}: java.lang.NullPointerExceptionat android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2447) – Ayomide Adekunle Jan 14 '16 at 15:22
  • Please see: [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Ed Holloway-George Jan 14 '16 at 15:28
  • Thank you very much @Ed George I will look into it. Please do you have any tutorial of step-to-follow to use SQLite with PageView(SwipeView) – Ayomide Adekunle Jan 14 '16 at 15:33
  • Stack Overflow is not a tutorial site - please use a search engine – Ed Holloway-George Jan 14 '16 at 15:34