Android NullPointerException when i scroll PagerView with Tabs - android

I use the same code in another App and it works fine, i don't understand why here i receive a NullPointerException.
It's my first time with Fragments and maybe i write something wrong!
Below the code.
This is my Thrd Fragment
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
public class ThreeFragment extends Fragment {
public MySQLiteHelper db = new MySQLiteHelper(getContext());
public List<VotiEsami> esami;
public VotiEsamiAdapter adapter; //Adapter per caricare la listview di voti
public ThreeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_three, container, false);
//Find the listview
final ListView listView = (ListView)view.findViewById(R.id.voti_listView);
//Get all exams inside database
esami = db.getVotiEsami();
adapter = new VotiEsamiAdapter(getContext(), R.layout.listview_voti_line, null);
listView.setAdapter(adapter);
//TODO gestire cancellazione del voto dal DB e dalla listview
Button nuovo_voto = (Button) view.findViewById(R.id.button_add_new_voto);
nuovo_voto.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Start Dialog for input the new vote
Intent myIntent = new Intent(getActivity(), DialogAddVotoEsame.class);
ThreeFragment.this.startActivityForResult(myIntent, 1);
}
});
return view;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
String result_nome = data.getStringExtra("result_name_esame"); //Take the materia from Dialog
int result_cfu = data.getIntExtra("result_cfu_esame", 1); //Take the materia from Dialog
int result_voto = data.getIntExtra("result_voto_esame", 1); //Take the materia from Dialog
//Add exam with vote to DB
db.addEsameVoto(new VotiEsami(result_nome, result_cfu, result_voto));
//Refresh list
List<VotiEsami> newesame = db.getVotiEsami();
//Aggiorno la Listview dell'activity con il nuovo inserimento
esami.clear();
esami.addAll(newesame);
adapter.notifyDataSetChanged();
}
}
}//onActivityResult
}
And here i have how manage the DB
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class MySQLiteHelper extends SQLiteOpenHelper {
//Database version
private static final int DATABASE_VERSION = 1;
//Database name
private static final String DATABASE_NAME = "agendaDB";
//Materie table name
public static final String TABLE_VOTI_ESAMI = "esami";
//Table_voti_esami columns
public static final String COLUMN_NOME_ESAME = "nome_esame";
public static final String COLUMN_CFU_ESAME = "cfu_esame";
public static final String COLUMN_VOTO_ESAME = "voto_esame";
//Stringa di creazione tabelle per database
//Tabella voti esami
private static final String CREATE_VOTO_ESAME_TABLE = "CREATE TABLE "
+ TABLE_VOTI_ESAMI + "("
+ COLUMN_NOME_ESAME + " TEXT,"
+ COLUMN_CFU_ESAME + " INTEGER,"
+ COLUMN_VOTO_ESAME + " INTEGER" + ")";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_VOTO_ESAME_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_VOTI_ESAMI);
// Create tables again
onCreate(db);
}
//Restituisco tutti gli esami dati
public List<VotiEsami> getVotiEsami(){
List<VotiEsami> esamiList = new ArrayList<>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_VOTI_ESAMI;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor != null) {
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
VotiEsami esami = new VotiEsami();
esami.set_nome_esame(cursor.getString(0));
esami.set_cfu(Integer.parseInt(cursor.getString(1)));
esami.set_voto(Integer.parseInt(cursor.getString(2)));
// Adding materia activity voti to list
esamiList.add(esami);
} while (cursor.moveToNext());
}
}else{
return null;
}
// return contact list
return esamiList;
}
// Aggiunta nuova materia sull activity voti
public void addEsameVoto(VotiEsami esam) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NOME_ESAME, esam.get_nome_esame());
values.put(COLUMN_CFU_ESAME, esam.get_cfu());
values.put(COLUMN_VOTO_ESAME, esam.get_voto());
// Inserting Row
db.insert(TABLE_VOTI_ESAMI, null, values);
db.close(); // Closing database connection
}
}//Chiudo classe
With the same DB, and same methods works withouth NullPointerException in another App (With simple Activitys)
And another mistery(for me):
I have 5 Fragments, for the First, no problem i can see it, but if i go to the others (2,3,4 or 5) i get always the same error, and as you can see in the Log it's always write:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at com.application.ddz.agendauniversitaria.MySQLiteHelper.getVotiEsami(MySQLiteHelper.java:70)
at com.application.ddz.agendauniversitaria.ThreeFragment.onCreateView(ThreeFragment.java:48)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:254)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791)
at android.view.Choreographer.doCallbacks(Choreographer.java:591)
at android.view.Choreographer.doFrame(Choreographer.java:560)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:777)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
Can someone tell me where is my epic fail?
Thanks.

I think you might need to initialise db object in your onCreate() method.
onCreate()
The system calls this when creating the fragment. Within
your implementation, you should initialize essential components of the
fragment that you want to retain when the fragment is paused or
stopped, then resumed.
So you can do it like this:
public class ThreeFragment extends Fragment {
public MySQLiteHelper db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new MySQLiteHelper(getContext());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Your code
esami = db.getVotiEsami();
}
}

Related

I can't send data to sqlite to database [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I am trying to add data to the SQLite database but when I add the data it gives me null pointer exception.
This is the error in the logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference
enter code here
package com.llmago.autism;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Objects;
public class StartFragment extends Fragment {
private EditText edtName, edtAge, edtScore;
private Button save, load;
Db db = new Db(getActivity());
public StartFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_start, container, false);
initUI(view);
// Inflate the layout for this fragment
return view;
}
public void initUI(View view) {
edtName = view.findViewById(R.id.name);
edtAge = view.findViewById(R.id.age);
edtScore = view.findViewById(R.id.result);
save = view.findViewById(R.id.save);
save.setOnClickListener(v -> btnSaveAction(view));
}
public void btnSaveAction(View view) {
String name = edtName.getText().toString();
String age = edtAge.getText().toString();
String score = edtScore.getText().toString();
boolean result = db.insertData(name, age, score);
if (result == true) {
Toast.makeText(getActivity(), "Done", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "Error", Toast.LENGTH_LONG).show();
}
}
}
package com.llmago.autism;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class Db extends SQLiteOpenHelper {
public static final String databaseName = "autism.db";
public Db(#Nullable Context context) {
super(context, databaseName, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table autism(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age TEXT, score TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS autiusm");
onCreate(db);
}
public boolean insertData(String name, String age, String score){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("age", age);
contentValues.put("score", score);
long result = sqLiteDatabase.insert("autism", null, contentValues);
if (result == -1)
return false;
else
return true;
}
}
Declare the mContext inside FragmentClass
Context mContext;
Change constructor from
public StartFragment(Context context) {
mContext = context;
db = new Db(mContext);
}
Also replace the db() constructor
public Db(#Nullable Context context) {
super(context, databaseName, null, 1);
this.getWritableDatabase();
}
Note: When you creating fragment instance you have to pass Activity Reference

error while retriving data from the database SQLite in android

my database helper class is
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataHandlerDairy {
public static final String DATE = "date";
public static final String DAIRY = "dairy";
private static final String DATA_BASE_NAME = "mydairy";
private static final String TABLE_NAME = "table_dairy";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_CREATE="create table table_dairy (date text primary key," + "dairy text not null);";
DataBaseHelper1 dbhelper1;
Context ct;
SQLiteDatabase db;
public DataHandlerDairy(Context ct)
{
this.ct=ct;
dbhelper1 = new DataBaseHelper1(ct);
}
private static class DataBaseHelper1 extends SQLiteOpenHelper
{
public DataBaseHelper1(Context ct)
{
super(ct,DATA_BASE_NAME,null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
try
{
db.execSQL(TABLE_CREATE);
}
catch(SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS table_dairy ");
onCreate(db);
}
}
public DataHandlerDairy open()
{
db = dbhelper1.getWritableDatabase();
return this;
}
public void close()
{
dbhelper1.close();
}
public long insertData(String date,String dairy)
{
ContentValues content = new ContentValues();
content.put(DATE, date);
content.put(DAIRY, dairy);
return db.insertOrThrow(TABLE_NAME, null, content);
}
public Cursor returnData(String date1) throws SQLException
{
Cursor c = db.query(true, TABLE_NAME, new String[] { DATE, DAIRY}, DATE + "=" + date1, null, null, null, null, null);
if(c!=null)
{
c.moveToFirst();
}
return c;
}
}
when i try to retrive the data from the database I am getting an error.
I have used the database helper class in the following code.
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class Read_Dairy extends Activity {
String date1;
TextView tv1,tv2;
ImageButton imgb1;
Button bt1;
DataHandlerDairy handler3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read__dairy);
tv1=(TextView) findViewById(R.id.readme);
imgb1=(ImageButton) findViewById(R.id.tick);
bt1=(Button) findViewById(R.id.ready);
tv2=(TextView) findViewById(R.id.love);
Bundle bundle = getIntent().getExtras();
date1 = bundle.getString("kanna");
bt1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getdata=" ";
tv2.setText(date1);
String abcd=tv2.getText().toString();
handler3 = new DataHandlerDairy(getBaseContext());
handler3.open();
Cursor c = handler3.returnData(abcd);
if(c.moveToFirst())
{
do
{
getdata=c.getString(1);
}while(c.moveToNext());
}
handler3.close();
if(getdata==null)
{
tv1.setText("no data exists for this date");
}
else
{
tv1.setText(getdata);
}
}
});
imgb1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent ks = new Intent(Read_Dairy.this,PickYourDate.class);
startActivity(ks);
}
});
Typeface font = Typeface.createFromAsset(getAssets(), "Strato-linked.ttf");
tv1.setTypeface(font);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_read__dairy, menu);
return true;
}
}
I am getting an error while using this and my StackTrace is
FATAL EXCEPTION: main
Process: simple.smile.my_dairy, PID: 4423
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at simple.smile.my_dairy.Read_Dairy$1.onClick(Read_Dairy.java:71)
at android.view.View.performClick(View.java:4832)
at android.view.View$PerformClick.run(View.java:19839)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5315)
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:941)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:736)
Please tell me where the error is and how to rectify it.
getdata=c.getString(1) is not a good way. Instead use getdata=c.getString(c.getColumnIndex(DataHandlerDairy.DAIRY))

Why am I getting this context and database error?

I am trying to...
create a simple listview that can be populated with data from an sqldatabase. The database works, I've seen it work with other code. The XML is fine and I really don't need to share it. When it comes to the XML, there is two buttons in the main activity: new and show. New sends you to the next activity to add to the list. Show will add data to the listview. That's all for the main activity. The other activity called NewEntry has a cancel button and a save button. It also has three editviews to help you add data.
Problems:
Right now it doesn't even compile without errors. The two errors are listed below in the main activity. If I comment out those two errors, I can get the application to run. when I open a new activity and try to save it, it crashes. They have to do with Context. I only sort of understand what Context does besides the fact that it is in everything.
This error has been solved see the bottom
The two compiler errors are in this code here. This is the main activity.
There are no other compiler errors, just logical ones.
I have pointed them out in the comments
""DATA BASE MANAGER CANNOT BE APPLIED TO LISTENER""
"CANNOT RESOLVE CONSTRUCTOR"
Also any explanations of Context will be appreciated.
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import java.util.ArrayList;
public class Main extends Activity {
private DatabaseManager mydManager;
private ListView productRec;
ArrayList<String> tableContent;
private LinearLayout addLayout;
ArrayList<String> arrayAdpt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
productRec=(ListView)findViewById(R.id.list);
Button newButton = (Button) findViewById(R.id.new_button);
Button showButton = (Button) findViewById(R.id.show_button);
Button newButton = (Button) findViewById(R.id.new_button);
newButton.setOnClickListener(new OnClickListener() {
public void onClick(View n) {
Intent x = new Intent(Main.this.getApplicationContext(), NewEntry.class);
startActivity(x);
}
});
showButton.setOnClickListener(new OnClickListener() { //Want this to launch new intent
public void onClick(View s) {
mydManager = new DatabaseManager(this); // <ERROR:
mydManager.openReadable(); //"DATA BASE MANAGER CANNOT BE APPLIED TO LISTENER"
tableContent = mydManager.retrieveRows();
productRec = (ListView)findViewById(R.id.list);
mydManager.retrieveRows(); //ERROR:
ArrayAdapter<String> arrayAdpt=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tableContent); //ERROR:CANNOT RESOLVE CONSTRUCTOR
productRec.setAdapter(arrayAdpt);
productRec.setVisibility(View.VISIBLE);
mydManager.close();
}
});
}
}
This is the NewEntry java class:
import android.content.Context;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
public class NewEntry extends Activity {
// public static final int REQUEST_CODE = 1;
private EditText titleView;
private EditText authorView;
private EditText priceView;
private Button doneButton;
private Button cancelButton;
private DatabaseManager mydManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit);
titleView = (EditText) findViewById(R.id.title_input);
authorView = (EditText) findViewById(R.id.author_input);
priceView = (EditText) findViewById(R.id.price_input);
doneButton = (Button) findViewById(R.id.done_button);
cancelButton = (Button) findViewById(R.id.cancel_button);
Intent i = this.getIntent();
//rec inserted, its a boolean in the other one
doneButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
mydManager = new DatabaseManager(NewEntry.this);
mydManager.addRow(Integer.parseInt(titleView.getText().toString()), authorView.getText().toString(),
Float.parseFloat(priceView.getText().toString())); ///sending in back to database
// InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.hideSoftInputFromWindow(priceView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
mydManager.close();
titleView.setText("");
authorView.setText(""); //SOMETHING TO DO WITH DATA? maybe its blanking it out
priceView.setText("");
finish();
}
});
cancelButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
This is the database:
import android.database.sqlite.SQLiteDatabase;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
public class DatabaseManager {
public static final String DB_NAME = "shopping";
public static final String DB_TABLE = "products";
public static final int DB_VERSION = 1;
private static final String CREATE_TABLE = "CREATE TABLE " + DB_TABLE + " (code INTEGER PRIMARY KEY, product_name TEXT, date FLOAT);";
private SQLHelper helper;
private SQLiteDatabase db;
private Context context;
public DatabaseManager(Context c){
this.context = c;
helper=new SQLHelper(c);
this.db = helper.getWritableDatabase();
}
public DatabaseManager openReadable() throws android.database.SQLException {
helper=new SQLHelper(context);
db = helper.getReadableDatabase();
return this;
}
public void close(){
helper.close();
}
public boolean addRow(int t, String a, float p){
ContentValues newProduct = new ContentValues();
newProduct.put("title", t);
newProduct.put("author", a);
newProduct.put("price", p);
try{db.insertOrThrow(DB_TABLE, null, newProduct);}
catch(Exception e) {
Log.e("Error in inserting rows ", e.toString());
e.printStackTrace();
return false;
}
db.close();
return true;
}
public ArrayList<String> retrieveRows(){ ///Retrieves edit
ArrayList<String> productRows=new ArrayList<String>();
String[] columns = new String[]{"title", "author", "price"};
Cursor cursor = db.query(DB_TABLE, columns, null, null, null, null, null);
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
productRows.add(Integer.toString(cursor.getInt(0)) + ", "+cursor.getString(1)+", "+Float.toString(cursor.getFloat(2)));
cursor.moveToNext();
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return productRows;
}
public class SQLHelper extends SQLiteOpenHelper {
public SQLHelper(Context c){
super(c, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("Products table","Upgrading database i.e. dropping table and recreating it");
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
onCreate(db);
}
}
}
Error when trying to retrieve rows:
04-11 22:08:25.552 21767-21767/com.example.alex.checkbox W/dalvikvm? threadid=1: thread exiting with uncaught exception (group=0x41e7cda0)
04-11 22:08:25.572 21767-21767/com.example.alex.checkbox E/AndroidRuntime? FATAL EXCEPTION: main
Process: com.example.alex.checkbox, PID: 21767
android.database.sqlite.SQLiteException: no such column: title (code 1): , while compiling: SELECT title, author, price FROM products
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1113)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:690)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1448)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1295)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1166)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1334)
at com.example.alex.favoritebooks.DatabaseManager.retrieveRows(DatabaseManager.java:56)
at com.example.alex.favoritebooks.Main$2.onClick(Main.java:45)
at android.view.View.performClick(View.java:4654)
at android.view.View$PerformClick.run(View.java:19438)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5487)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
In your newButton.setOnClickListener(...) code you are using the application Context when creating your Intent. Don't do that - instead use the Activity Context...
newButton.setOnClickListener(new OnClickListener() {
public void onClick(View n) {
// Simply use Main.this on the next line...
Intent x = new Intent(Main.this, NewEntry.class);
startActivity(x);
}
});
In your showButton.setOnClickListener(...) code you are passing a reference to the OnClickListener object to the constructor of your DatabaseManager and also when creating your ArrayAdapter...
showButton.setOnClickListener(new OnClickListener() {
public void onClick(View s) {
mydManager = new DatabaseManager(this); //Here is the error
...
ArrayAdapter<String> arrayAdpt=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tableContent);
...
}
});
The this keyword refers to the current instance of any object which uses it - in this case, this refers to the OnClickListener which is not a Context. Also, as an aside, you're declaring a new ArrayAdapter variable in your OnClickListener code instead of using the one declared in the Activity. Change the code as follows...
showButton.setOnClickListener(new OnClickListener() {
public void onClick(View s) {
mydManager = new DatabaseManager(Main.this);
...
arrayAdpt = new ArrayAdapter<String>(Main.this, android.R.layout.simple_list_item_1, tableContent);
...
}
});

How display field values in new activity when particular listview is clicked?

I have a table on my database.
one of the field from that table is displayed as a listview in the main activity.
i have implemented the setOnItemClickListener to open the new activity to display other field values of that selected list item.
new activiy is successfully opened.
but i have trouble in displaying field values....
i have browsed many sites....
but nothing helped.....
i have displayed department names in listview...
in the new activity i need get the value of DEPT_LIST_COLUMN_ID and DEPT_LIST_COLUMN_NAME
MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends Activity {
private MyDBHelper mydb;
private SimpleCursorAdapter adapter;
public static final String Row_ID = "row_id";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//********************************//
//Begin of Database-Table1_Dept_List
//********************************//
ListView dplist=(ListView)findViewById(R.id.list_view);
//Instantiate table1_dept_list
mydb =new MyDBHelper(this, null, null,4);
SQLiteDatabase db =mydb.getReadableDatabase();
//Removing duplicate values from table1_dept_list
mydb.delete_dep_list();
//Inserting into table1_dept_list
mydb.add_dept_list("DLBIOCHEM","BioChemistry");
mydb.add_dept_list("DLBIOTECH","BioTechnology");
mydb.add_dept_list("DLBOT", "Botany");
mydb.add_dept_list("DLCHEM","Chemistry");
mydb.add_dept_list("DLCOM","Commerce");
mydb.add_dept_list("DLCS","Computer Science");
mydb.add_dept_list("DLECO","Economics");
mydb.add_dept_list("DLEDU","Education");
mydb.add_dept_list("DLENG","English");
mydb.add_dept_list("DLEVS","Environmental Science");
mydb.add_dept_list("DLFSN","Food Science and Nutrition");
mydb.add_dept_list("DLGEO","Geology");
mydb.add_dept_list("DLJMC", "Journalism and Massmedia Communication");
mydb.add_dept_list("DLLIS","Library and Information Science");
mydb.add_dept_list("DLMATH","Mathematics");
mydb.add_dept_list("DLMICRO","Microbiology");
mydb.add_dept_list("DLPE","Physical Education");
mydb.add_dept_list("DLPHY","Physics");
mydb.add_dept_list("DLPRIMS","Periyar Institute of Management Studies");
mydb.add_dept_list("DLPSY","Psychology");
mydb.add_dept_list("DLSOC","Sociology");
mydb.add_dept_list("DLTAM", "Tamil");
mydb.add_dept_list("DLTAD","Textile and Apparel Design");
mydb.add_dept_list("DLZOO","Zoology");
//list view
Cursor AllDeptList = mydb.get_dept_list();
String[] from=new String[] {
MyDBHelper.DEPT_LIST_COLUMN_NAME
};
int[] to=new int[] {R.id.dis_text};
adapter = new SimpleCursorAdapter(this,R.layout.disp_text,AllDeptList,from,to,0 );
dplist.setAdapter(adapter);
//********************************//
//end of Database-Table1_Dept_List//
//********************************//
dplist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
Cursor cursor = mydb.get_dept_list();
cursor.moveToPosition(position);
Intent intent_dp_list = new Intent(MainActivity.this,DepartmentDesignation.class);
intent_dp_list.putExtra(Row_ID,arg3);
startActivity(intent_dp_list);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
DepartmentDesignation.java
package com.example.contact;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class DepartmentDesignation extends Activity {
private SimpleCursorAdapter adapter;
public static String d_id;
public static String d_name;
private String Row_id;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.disp_dept_desig);
TextView tx_id = (TextView)findViewById(R.id.id);
Intent extras = getIntent();
tx_id.setText(extras.getStringExtra(Row_id));
TextView tx_name=(TextView)findViewById(R.id.name);
tx_name.setText(d_name);
}
}
MyDBHelper.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class MyDBHelper extends SQLiteOpenHelper{
public static final String DEPT_LIST_TABLE1_NAME="tbl_dep_list";
public static final String DEPT_LIST_ROW_ID = "_id";
public static final String DEPT_LIST_COLUMN_ID = "fld_tb1_id";
public static final String DEPT_LIST_COLUMN_NAME="fld_tb1_list";
public MyDBHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, "contact_book.db", factory, 11);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase database) {
// TODO Auto-generated method stub
database.execSQL(" CREATE TABLE " + DEPT_LIST_TABLE1_NAME + "(" + DEPT_LIST_ROW_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + DEPT_LIST_COLUMN_ID + " TEXT, " + DEPT_LIST_COLUMN_NAME + " TEXT ) " );
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DEPT_LIST_TABLE1_NAME);
onCreate(db);
}
public void add_dept_list(String dl_id, String dep_list) {
// TODO Auto-generated method stub
ContentValues values = new ContentValues(2);
values.put(MyDBHelper.DEPT_LIST_COLUMN_ID , dl_id);
values.put(MyDBHelper.DEPT_LIST_COLUMN_NAME,dep_list);
getWritableDatabase().insert(MyDBHelper.DEPT_LIST_TABLE1_NAME,null,values);
}
public int delete_dep_list(){
try{
SQLiteDatabase db =this.getWritableDatabase();
return db.delete(DEPT_LIST_TABLE1_NAME, null, null);
}
catch(Exception e){
e.printStackTrace();
}
return 0;
}
public Cursor get_dept_list(){
String[] from = new String[] {MyDBHelper.DEPT_LIST_ROW_ID,MyDBHelper.DEPT_LIST_COLUMN_ID,MyDBHelper.DEPT_LIST_COLUMN_NAME};
Cursor cursor = getReadableDatabase().query(MyDBHelper.DEPT_LIST_TABLE1_NAME, from,null,null,null, null, null);
if(cursor != null){
cursor.moveToFirst();
}
return cursor;
}
}
On your onItemClick method, pass the values you need in an intent to open the activity.
Intent intent = new Intent("blah blah");
intent.putExtra(DEPT_LIST_COLUMN_ID, "value");
intent.putExtra(DEPT_LIST_COLUMN_NAME, "value");
Then on the opened activity, do:
extras.getStringExtra(DEPT_LIST_COLUMN_ID)

Eclipse LogCat Error about "no such table" SQLite

I am trying to write a Race database where you would enter a race name, then click on that race name, and edit/delete it.
So I am getting an error in my logcat (error code=1). It tells me there is no table created so I think I am not calling my variables correctly.
//LogCat
12-08 12:46:21.019: I/INFORMATION(650): You entered the insert method
12-08 12:46:21.019: I/Database(650): sqlite returned: error code = 1, msg = no such table: Note
12-08 12:46:21.062: E/Database(650): Error inserting note=ft
12-08 12:46:21.062: E/Database(650): android.database.sqlite.SQLiteException: no such table: Note: , while compiling: INSERT INTO Note(note) VALUES(?);
12-08 12:46:21.062: E/Database(650): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
12-08 12:46:21.062: E/Database(650): at android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:92)
12-08 12:46:21.062: E/Database(650): at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:65)
//View races java code
package com.CIS2818.tritracker;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class View_races extends Activity {
NoteAdapter adapter=null;
RaceHelper helper2=null;
Cursor dataset_cursor=null;
EditText editNote2=null;
String noteId2=null;
String TAG = "INFORMATION";
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try
{
setContentView(R.layout.activity_view_races);
ListView list2=(ListView)findViewById(R.id.list2);
editNote2 = (EditText)findViewById(R.id.myEditText2);
helper2=new RaceHelper(this);
dataset_cursor=helper2.getAll();
startManagingCursor(dataset_cursor);
adapter=new NoteAdapter(dataset_cursor);
list2.setAdapter(adapter);
Button btnSimple2 = (Button) findViewById(R.id.btnSimple2);
btnSimple2.setOnClickListener(onSave);
Button btnDelete2 = (Button) findViewById(R.id.btnDelete2);
btnDelete2.setOnClickListener(onDelete);
list2.setOnItemClickListener(onListClick);
}
catch (Exception e)
{
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
helper2.close();
}
private View.OnClickListener onSave=new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
Log.i(TAG,"You passed through the save method");
if (noteId2==null) {
helper2.insert(editNote2.getText().toString());
}
else{
helper2.update(noteId2, editNote2.getText().toString());
noteId2=null;
}
dataset_cursor.requery();
editNote2.setText("");
}
};
private View.OnClickListener onDelete=new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
if (noteId2==null) {
return;
}
else{
helper2.delete(noteId2);
noteId2=null;
}
dataset_cursor.requery();
editNote2.setText("");
}
};
private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view, int position,
long id2)
{
noteId2 =String.valueOf(id2);
Cursor c=helper2.getById(noteId2);
c.moveToFirst();
editNote2.setText(helper2.getNote(c));
}
};
class NoteAdapter extends CursorAdapter {
#SuppressWarnings("deprecation")
NoteAdapter(Cursor c) {
super(View_races.this, c);
}
#Override
public void bindView(View row, Context ctxt,Cursor c) {
NoteHolder2 holder=(NoteHolder2)row.getTag();
holder.populateFrom(c, helper2);
}
#Override
public View newView(Context ctxt, Cursor c,ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.row2, parent, false);
NoteHolder2 holder=new NoteHolder2(row);
row.setTag(holder);
return(row);
}
}
static class NoteHolder2 {
private TextView noteText2=null;
NoteHolder2(View row) {
noteText2=(TextView)row.findViewById(R.id.note2);
}
void populateFrom(Cursor c, RaceHelper helper) {
noteText2.setText(helper.getNote(c));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_view_races, menu);
return true;
}
//Button Method to return to the main Menu
public void Menu(View v){
Intent intent = new Intent(this, MainMenuActivity.class);
startActivity(intent);
}
//Button Method to go to the Race Activity
public void Races(View v){
Intent intent = new Intent(this, UpComingRaceActivity.class);
startActivity(intent);
}}
//RaceHelper java code
package com.CIS2818.tritracker;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
class RaceHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="note2.db";
private static final int SCHEMA_VERSION=1;
String TAG ="INFORMATION";
public RaceHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE Note (_id INTEGER PRIMARY KEY AUTOINCREMENT, note TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void insert(String note2) {
Log.i(TAG,"You entered the insert method");
ContentValues cv2=new ContentValues();
cv2.put("note", note2);
getWritableDatabase().insert("Note", "note", cv2);
}
public void update(String id, String note2) {
ContentValues cv2=new ContentValues();
String[] args={id};
cv2.put("note", note2);
getWritableDatabase().update("Note", cv2, "_id=?", args);
}
public void delete(String id2) {
getWritableDatabase().delete("Note", "_id=?", new String[] {id2});
}
public Cursor getAll() {
return(getReadableDatabase()
.rawQuery("SELECT _id, note FROM Notes",
null));
}
public String getNote(Cursor c2) {
return(c2.getString(1));
}
public Cursor getById(String id2) {
String[] args={id2};
return(getReadableDatabase()
.rawQuery("SELECT _id, note FROM Note WHERE _id=?",
args));
}
}
It appears you have changed your SQL schema in your Java code but haven't informed SQLite. In order for your SQLiteOpenHelper class to use the new schema you provided in onCreate(), you need to upgrade your database. This is the most basic approach.
First add some functionality to onUpgrade():
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS Note");
onCreate(db);
}
Now increment SCHEMA_VERSION to trigger an upgrade:
private static final int SCHEMA_VERSION=2;
Understand that SQLiteOpenHelper does not check the code inside onCreate() for you, you must tell SQLite there is a change by incrementing SCHEMA_VERSION.
In your insert method make the second value null. For example getWritableDatabase().insert("Note",null,cv2);
I have the same question as yours.I solved it.At first I rename the table that I create but do nothing with the CREATE_DATABASE order.Then I notice it. Although I corrected the order it does not works.So I add the onUpgrade method, and increment DATABASE_VERSION to a higher number,it works!!!Hope it works also for you.

Categories

Resources