Home java Using the finished database of SQLite Android

Using the finished database of SQLite Android

Author

Date

Category

I need to display data in ListView (and better in RecycleView) from the already ready SQLite database.
Tried to follow the instructions from the video https://www.youtube.com/watch?v=alnvhgyDvd8.
But when you start the application, it crashes.

Here is my code …
MainActivity:

Public Class MainActivity Extends AppCompatactivity {
Private ListView LvProduct;
Private ListProductApter Adapter;
Private List & lt; Product & GT; MPRODUCTLIST;
Private Databasehelper Mdbhelper;
@Override
PROTECTED VOID OnCreate (Bundle SavedInstanceState) {
  Super.ONCREATE (SavedInstanceState);
  setContentView (R.Layout.Activity_Main);
  lvproduct = (ListView) FindViewByid (R.ID.ListView_Product);
  MDBHELPER = New Databasehelper (this);
  // Check for the existence of database
  File Database = GetApplicationContext (). GetDatabasePath (databasehelper.dbname);
  if (false == database.exists ())
  {
    mdbhelper.getReadableDatabase ();
    // Copying BD
    If (CopyDatabase)
    {
      Toast.maketext (this, "Copy Database Succes", toast.Length_Short) .Show ();
    }
    ELSE.
    {
      Toast.maketext (this, "Copy Database Error", toast.length_short) .show ();
      Return;
    }
  }
  // Receive data from the database if it is not empty and withdraw it in our Activity_Main
  mdboductlist = mdbhelper.getlistProduct ();
  // in this adapter
  Adapter = New ListProductadadter (this, mproductlist);
  // withdraw the adpter on our listview
  lvproduct.setadapter (Adapter);
}
PRIVATE BOOLEAN COPYDATABASE (CONTEXT CONTEXT)
{
  Try {
    Inputstream inputstream = context.getassets (). Open (databasehelper.dbname);
    String OutfileName = Databasehelper.dblocation + databasehelper.dbname;
    OutputStream OutputStream = New FileoutPutStream (OutfileName);
    BYTE [] Buff = New Byte [1024];
    INT LENGTH = 0;
    While ((Length = InputStream.Read (buff)) & gt; 0)
    {
      outputstream.write (buff, 0, longth);
    }
    outputstream.flush ();
    OutputStream.Close ();
    Log.w ("MainActivity", "DB Copied");
    RETURN TRUE;
    }
    Catch (Exception E)
    {
      E.PrintStackTrace ();
      RETURN FALSE;
    }
  }
}

DatabaseHelper:

Public Class Databasehelper EXTENDS SQLiteOpenHelper {
Public Static Final String Dbname = "sample.sqlite";
Public Static Final String dblocation = "/data/data/com.example.myapplication/databases";
Private Context MContext;
Private Sqlitedatabase mdatabase;
Public DatabaseHelper (CONTEXT CONTEXT)
{
  Super (CONTEXT, DBNAME, NULL, 1);
  this.mcontext = context;
}
@Override
Public Void OnCreate (SQLITEDATABASE DB) {
}
@Override
Public Void Onupgrade (SQLITEDATABASE DB, INT OLDVERSION, INT NEWVERSION) {
}
Public void OpenDatabase ()
{
  String DBPath = MContext.getDatabasePath (DBName) .GetPath ();
  if (mdatabase! = NULL & amp; & amp; mdatabase.isopen ())
  {
    Return;
  }
  mdatabase = sqlitedatabase.opendatabase (dbpath, null, sqlitedatabase.open_readwrite);
}
Public void closedatabase ()
{
  If (mdatabase! = NULL)
  {
    mdatabase.close ();
  }
}
Public List & LT; Product & GT; GetListProduct ()
{
  Product Product = NULL;
  List & lt; Product & GT; ProductList = New ArrayList & LT; & GT; ();
  OpenDatabase ();
  CURSOR CURSOR = MDATABASE.RAWQUERY ("SELECT * FROM PRODUCT", NULL);
  cursor.movetofirst ();
  While (! cursor.isafterlast ())
  {
    Product = NEW Product (Cursor.getint (0), Cursor.getString (1), Cursor.getint (2), Cursor.getString (3));
    ProductList.add (Product);
    cursor.movetonext ();
  }
  cursor.close ();
  closedabase ();
  Return ProductList;
}

}
ListProductadader:

Public Class ListProductadaPter Extends Baseadapter {
Private Context MContext; 
Private List & lt; Product & GT; MPRODUCTLIST;
Public ListProductadader (Context MContext, List & LT; Product & GT; MPRODUCTLIST) {
  this.mcontext = mctextext;
  this.mproductlist = mproductlist;
}
@Override
Public int getCount () {
  Return mproductlist.size ();
}
@Override
Public Object GetItem (Int Position) {
  RETURN MPRODUCTLIST.GET (POSITION);
}
@Override
Public Long GetItemid (Int Position) {
  RETURN MPRODUCTLIST.GET (POSITION) .GETID ();
}
@Override
Public View GetView (Int Position, View ConvertView, ViewGroup Parent) {
  View v = view.inflate (MContext, R.Layout.Inthem_ListView, NULL);
  TextView tvname = (textView) v.findViewByID (R.ID.TV_PRODUCT_NAME);
  TextView TVPrice = (TextView) v.findViewByID (R.ID.TV_PRODUCT_PRICE);
  TextView TVDescription = (TextView) v.FindViewByID (R.ID.TV_PRODUCT_DESRIFTION);
  tvname.settext (MPRODUCTLIST.GET (Position) .GetName ());
  TVPrice.SetText (String.Valueof (MPRODUCTLIST.GET (Position) .GetPrice ()) + "$");
  TVDescription.setText (MPRODUCTLIST.GET (POSITION) .GetDescription ());
  RETURN V;
}

}

and directly Product:

Public Class Product {
Private int id;
Private String Name;
Private INT Price;
Private String Description;
Public Product (int ID, String Name, Int Price, String Description) {
  this.id = id;
  this.name = Name;
  this.price = Price;
  this.Description = Description;
}
Public int GetID () {
  Return ID;
}
Public Void Setid (int ID) {
  this.id = id;
}
Public String GetName () {
  RETURN NAME;
}
Public Void SetName (String Name) {
  this.name = Name;
}
Public int GetPrice () {
  Return Price;
}
Public Void SetPrice (int price) {
  this.price = Price;
}
Public String GetDescription () {
  RETURN DESRIPTION;
}
Public Void SetDescription (String Description) {
  this.Description = Description;
}

}

When you start the application in the logs, the following in-julation:

2020-04-28 23: 12: 17.886 12730-12730 / com.example.Myapplication E / SQLITELOG: ( 1) No Such Table: Product

2020-04-28 23: 12: 17.889 12730-12730 / com.example.Myapplication E / AndroidRuntime: Fatal Exception: Main
Process: com.example.Myapplication, PID: 12730
java.lang.RuntimeException: Unable to start activity ComponentInfo {com.example.myapplication / com.example.myapplication.MainActivity}: android.database.sqlite.SQLiteException: no such table: PRODUCT (code 1 SQLITE_ERROR):, while compiling: SELECT * FROM Product
at Android.app.ActivityThread.PerformLaunchaactivity (ActivityThread.java:2913)
at Android.app.activityThread.HandlelaUnchaactivity (ActivityThread.java:3048)
at Android.app.ServertRansAction.LaunchaactivityItem.Execute (launchaactivityItem.java:78)
AT Android.app.Servertransaction.TransActionExecutor.ExecuteCallbacks (transactionexecutor.java:108)
AT Android.app.Servertransaction.TransActionExecutor.Execute (transactionexecutor.java:68)
AT Android.app.activityThread $ H.HlandleMessage (ActivityThread.java:1808)
at android.os.Handler.DispatchMessage (handler.java:106)
at android.os.looper.loop (Looper.java:193)
at Android.app.AntivityThread.Main (ActivityThread.java:6669)
at java.lang.reflect.method.invoke (Native Method)
at com.android.internal.os.runtimeinit $ methodargscaller.run (runtimeinit.java:49)
at com.android.Internal.os.zygoteinit.main (zygoteinit.java:858)
Caused by: Android.Database.sqlite.SQLiteException: No Such Table: Product (code 1 sqlite_error):, While Compiling: SELECT * from Product
at android.database.sqlite.sqliteConnection.NativePrePareStement (Native Method)
at android.database.sqlite.sqliteConnection.acquirePreParedStatement (SQLiteConnection.java:903)
at android.database.sqlite.sqliteconnection.prepare (SQLiteConnection.java:14)
at android.database.sqlite.sqlitesession.prepare (SQLiteSession.java:88)
at android.database.sqlite.sqliteprogram. (SQLITEPROGRAM.JAVA:8)
at android.database.sqlite.sqlitequery. (SQLiteQuery.java: 7)
at android.database.sqlite.sqlited seasoncursOrdriver.Query (SqlitedRectcursOrdRiver.java:46)
at android.database.sqlite.sqliteDatabase.RawQueryWithFactory (SQLITEDATABASE.JAVA: 408)
at android.database.sqlite.sqlitedatabase.RawQuery (SqliteDatabase.java:1347)
at com.example.myapplication.database.databasehelper.getlistProduct (Databasehelper.java:8)
at com.example.myapplication.mainActivity.ONCREATE (MainActivity.java ::11)
at android.app.activity.performcreate (Activity.java:7136)
at android.app.activity.performcreate (Activity.java:7127)
at android.app.Instrumentation.callantationIncreate (Instrumentation.java:1271)
AT Android.app.ActivityThread.PerformLaunchaactivity (ActivityThread.java:2893)
at android.app.activityThread.HandlelaUnchaactivity (ActivityThread.java:3048) & nbsp;
at android.app.ServertRansAction.LaunchaactivityItem.Execute (launchaactivityItem.java:78) & nbsp;
at android.app.Servertransaction.TransActionExecutor.Executecallbacks (transactionexecutor.java:108) & nbsp;
at android.app.Servertransaction.TransActionExecutor.Execute (transactionexecutor.java:68) & nbsp;
at android.app.activityThread $ H.HandleMessage (ActivityThread.java:1808) & nbsp;
at android.os.Handler.DispatchMessage (Handler.java:106) & nbsp;
at android.os.looper.loop (Looper.java:193) & nbsp;
at android.app.ActivityThread.Main (ActivityThread.java:6669) & NBSP;
at java.lang.reflect.method.invoke (Native Method) & NBSP;
at com.android.Internal.os.runtimeinit $ methodargscaller.run (runtimeinit.java:493) & nbsp;
at com.android.Internal.os.zygoteinit.main (zygoteinit.java:858) & nbsp;
He swears directly on the line in MainActivity:

mproductlist = mdbhelper.getlistproduct ();

in DatabaseHelper:

cursor cursor = mdatabase.rawquery ("Select * from Product", NULL);

Answer 1, Authority 100%

I did not watch the video tutorial, but I will tell you

1 For work with the finished database, the easiest way is to use an excellent solution for this – the SQLiteAssetShelper library Tych

The essence of her work is that when you first start it is unpacking automatically. To do this, the base itself must be put in the ASSETS / Databases folder, the file itself must have the kind of my_database.db all this can be done with handles but so really easier.

Next, you should create a database control class and inherit it from the Halper itself

Public Class MyDatabase Extends Sqliteassethelper

To work the database, you need a context.

Here is an example of the class itself.

Public Class MyDatabase Extends SQLiteAssethelper {

Private Static Final String Tag = "Tag";
Private Static Final int database_version = 1;
Private static string database_name = "database_1.db";
Private Final Context Context;
Private Sqlitedatabase MyDatabase;
Public MyDatabase (CONTEXT CONTEXT) {
  Super (Context, Database_Name, Null, Database_Version);
  this.context = context;
  Try {
    MyDatabase = this.GetWritableDatabase ();
  } Catch (SQLiteException E) {
    Try {
      CleardB ();
    } Catch (Exception EX) {
      setForcedUpgrade ();
    }
    Log.d (Tag, "MyDatabase:" + E);
  }
}
// Get all the elements
Public Cursor GetAllData (String Table_Name) {
  MyDatabase = getWritableDatabase ();
  Return MyDatabase.Query (
    Table_Name, NULL, NULL, NULL, NULL, NULL, NULL
  );
}
Public void closedb () {
  SQLITEDATABASE DB = this.getReadableDatabase ();
  if (db! = NULL & amp; & amp; db.isopen ())
    db.close ();
}
Public void CleardB () {
  if (MyDatabase! = NULL & AMP; & amp; MyDatabase.isopen ()) {
    MyDatabase.Close ();
  }
  File File = New File (CONTEXT.GETDATABASEPATH (Database_Name) .GetPath ()); 
SQLITEDATABASE.DELETEDATABASE (FILE);
}

}

, respectively, somewhere in activat you need to create an object of the database
For example

MyDatabase MyDatabase = New MyDatabase (Context)

and make a query that will return the list

private list & lt; bus_list & gt; BUSLISTS = NEW ARRAYLIST & LT; & GT; ();
 Public List & lt; bus_list & gt; RetRieveLeLData () {
    Cursor Cursor = Database.GetAllData (Table_Bus);
    While (cursor.movetonext ()) {
      Long _Id = Cursor.getlong (0);
      String Bus_Number = Cursor.getString (1);
      String Start_station = Cursor.getString (2);
      String End_station = Cursor.getString (3);
      Bus_list BUSLIST = new bus_list (bus_number, start_station, end_station);
      buslists.add (BUSLIST);
    }
    database.closedb ();
    RETURN BUSLISTS;
  }

or so

if (getActivity ()! = NULL) {
   Database = ((MyApplication) getActivity (). GetApplication ()). GetDatabase ();
   Retriever = New Retriever (Database); `
 Public Retriever (MyDatabase Database) {
    this.database = Database;
  }

and the resulting list stuff in the adapter

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions