sqlLite in android didnt insert my data to table - java

I dont know why i have return result = -1 after execute insertGasData. In other similiar structure the result was != -1, but there is = -1.
There is DatabaseHelper class and main class
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "car.db";
public static final String TABLE_NAME2 = "car_gas_table";
public static final String COL_G_1 = "GAS_ID";
public static final String COL_G_2 = "GAS_DATE";
public static final String COL_G_3 = "GAS_MILEAGE";
public static final String COL_G_4 = "FUEL_TYPE";
public static final String COL_G_5 = "FUEL_COST";
public static final String COL_G_6 = "FUEL_VOLUME";
public DatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("create table " + TABLE_NAME2 + " (GAS_ID INTEGER PRIMARY KEY AUTOINCREMENT, GAS_DATE TEXT, GAS_MILEAGE TEXT, FUEL_TYPE TEXT, FUEL_COST TEXT, FUEL_VOLUME TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME2);
}
public boolean insertGasData(String date, String mileage, String fuel_type, String fuel_price, String fuel_volume) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_G_2, date);
contentValues.put(COL_G_3, mileage);
contentValues.put(COL_G_4, fuel_type);
contentValues.put(COL_G_5, fuel_price);
contentValues.put(COL_G_6, fuel_volume);
long result = sqLiteDatabase.insert(TABLE_NAME2, null, contentValues);
if (result == -1)
return false;
else return true;
}
there is a call method
i use there Strings to eliminate other mistakes but it doesnt help
public void AddRefuelrData() {
bDodaj.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// boolean isInsert = myDb.insertGasData(eRefDate.getText().toString(), eRefMileage.getText().toString(), eRefType.getText().toString(), eRefPrice.getText().toString(), eRefVolume.getText().toString());
boolean isInsert = myDb.insertGasData("dd","mm", "tt", "pr", "vo");
if (isInsert == true)
Toast.makeText(MainActivity.this, "Data inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Data not inserted", Toast.LENGTH_LONG).show();
}
});
}
after call method insertGasData i have return false
enter image description here

Are you sure the table is actually created properly?
Use Device File Explorer to check if the database is created or not.
that should help with narrowing down the problem.

Related

how to override sqlite database in android studio using integer as argument

I am making an application in android studio developed in java that allows to show a profile image in imageview and store the url of the location of said image in a database, besides that every time a button is pressed it can be changed the profile image and the path where the new image is located is overwritten. So far I am taking the facebook profile picture and I am storing its url in the table but when I press the button to change the image (which does good way) and try to override the url the value of the field is not modified. The idea is to override the url field of the image from the database by giving as an argument the id of the user associated with said image (which is an integer ). I hope you understand and can help me. Greetings
ConstantUser.class
public class ConstantUser {
//table user
public static final String TABLA_USUARIO="usuario";
public static final String CAMPO_ID="user_id";
public static final String CAMPO_FK_ID="id_profile";
public static final String CAMPO_PASSWORD="password";
public static final String CAMPO_USERNAME="username";
public static final String CAMPO_FIRSTNAME="first_name";
public static final String CAMPO_LASTNAME="last_name";
public static final String CAMPO_EMAIL="email";
public static final String CAMPO_DATE="date";
public static final String CAMPO_DATE_JOINED="date_joined";
//table perfil_user
public static final String TABLE_PROFILE="profile";
public static final String FIELD_ID_PROFILE="id_profile";
public static final String FIELD_ALIAS="alias";
public static final String FIELD_REPUTATION="reputation";
public static final String FIELD_IMAGE="image_perfil";
public static final String CREAR_TABLA_USUARIO="CREATE TABLE "+TABLA_USUARIO+"("+CAMPO_ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"+CAMPO_PASSWORD+" TEXT,"+
CAMPO_USERNAME+" TEXT,"+CAMPO_FIRSTNAME+" TEXT,"+CAMPO_LASTNAME+" TEXT,"+CAMPO_EMAIL+" TEXT,"+CAMPO_DATE+
" TEXT,"+CAMPO_DATE_JOINED+" TEXT,"+CAMPO_FK_ID+" INTEGER,"+" FOREIGN KEY"+"("+CAMPO_FK_ID+")" +
" REFERENCES "+TABLE_PROFILE+"(id_profile)"+")";
public static final String CREATE_TABLE_PROFILE="CREATE TABLE "+TABLE_PROFILE+"("+FIELD_ID_PROFILE+" INTEGER PRIMARY KEY AUTOINCREMENT,"+FIELD_ALIAS+" TEXT,"+FIELD_REPUTATION+
" INTEGER,"+FIELD_IMAGE+" TEXT"+")";
}
sqlitehelper.class
public class ConexionSQliteHelper extends SQLiteOpenHelper {
public ConexionSQliteHelper(#Nullable Context context, #Nullable String name, #Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREAR_TABLA_USUARIO);
db.execSQL(CREATE_TABLE_PROFILE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLA_USUARIO);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PROFILE);
}
public void insertUser(String user_name, String name, String last_name, String date, String date_joined, String alias, String email, String password,String photo) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FIELD_ALIAS, alias);
values.put(FIELD_IMAGE,photo);
values.put(FIELD_REPUTATION, 0);
Long idresultante = db.insert(TABLE_PROFILE, null, values);
ContentValues values_2 = new ContentValues();
values_2.put(CAMPO_PASSWORD,password);
values_2.put(CAMPO_USERNAME, user_name);
values_2.put(CAMPO_FIRSTNAME, name);
values_2.put(CAMPO_LASTNAME, last_name);
values_2.put(CAMPO_EMAIL, email);
values_2.put(CAMPO_DATE, date);
values_2.put(CAMPO_DATE_JOINED, date_joined);
values_2.put(CAMPO_FK_ID, idresultante);
Long idresultante_2 = db.insert(TABLA_USUARIO, null, values_2);
db.close();
}
public int requestId(String username){
Integer id = null;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(" SELECT "+CAMPO_ID+" FROM " + TABLA_USUARIO + " WHERE " + CAMPO_USERNAME + " =? ", new String[]{username});
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
id = cursor.getInt(0);
}
}
return id;
}
public void overWriteImage(String url,String id){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FIELD_IMAGE, stringUri);
Cursor cursor = db.rawQuery(" SELECT "+FIELD_IMAGE+" FROM " + TABLE_PROFILE + " WHERE " + FIELD_ID_PROFILE+ " =? ", new String[]{id});
long row = db.update(TABLE_PROFILE,values,FIELD_IMAGE+ " = ?", new String[]{id});
db.close();
}
}
Main.class
public class loggin extends AppCompatActivity {
Button buttonSelectImage
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.perfil_user,container,false);
buttonSelectImage=view.findViewById(R.id.change_image);
ConexionSQliteHelper conn=new ConexionSQliteHelper(getContext(),"db_testwuad_7",null,15);
AccessToken accessToken = AccessToken.getCurrentAccessToken();
buttonSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,3);
}
});
//in this part I get the name, email and profile picture from facebook
//and store it in the database structure
//mentioned above and show it in the view
if ( accessToken != null && !accessToken.isExpired()){
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
Blob my_blob= null;
facebook_firstname=object.getString("first_name");
facebook_lastname =object.getString("last_name");
facebook_user_name=object.getString("name");
email_facebook = object.getString("email");
String url_perfil_facebook=object.getJSONObject("picture").getJSONObject("data").getString("url");
Picasso.get().load(url_perfil_facebook).into(image_user);
name_user.setText(facebook_user_name);
email.setText(email_facebook);
str_datefb = date_now;
str_datejoinedfb = date_now;
tag_date.setText(str_datefb);
boolean exist_user = conn.verifyIfUserExists(email_facebook);
if (exist_user) {
alias_perfil = conn.getUserName(email_facebook);
alias_facebook = conn.requestAlias(alias_perfil);
alias.setText(alias_facebook);
String last_season = conn.getLastDateofConnection(facebook_user_name);
tag_date.setText(last_season);
conn.overwriteDate(date_now,facebook_user_name);
}
else {
alias_name= generateAliasRandom();
conn.insertUser(facebook_user_name,facebook_firstname,facebook_lastname,str_datefb,str_datejoinedfb,alias_name,email_facebook,null,url_perfil_facebook);
Toast.makeText(getContext(), "nuevo usuario creado", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields","id,first_name,last_name,name,email,link,picture.type(large)");
request.setParameters(parameters);
request.executeAsync();
}
return view
}
//here I get the url of the new image once the changeimage button is
//selected and I pass
//that value to the overwriteimage method along with the user id
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ConexionSQliteHelper conn=new ConexionSQliteHelper(getContext(),"db_testwuad_7",null,15);
if(resultCode == RESULT_OK && data != null){
Uri selectedImage = data.getData();
image_user.setImageURI(selectedImage);
String stringUri = selectedImage.toString();
Toast.makeText(getContext(), "el valor es"+stringUri, Toast.LENGTH_LONG).show();
int id_user = conn.requestId(name_user.getText().toString());
//convert id integer to string
String id_string=Integer.toString(id_string);
conn.overWriteImage(stringUri,id_string);
}}

How to delete a user from sqlite database in android studio?

Im trying to figure out how I can delete one user at a time by typing in the edittext the users username and clicking deleting which I then want all the users information (username, usernum, password, birthdate, phone, address) to be deleted from the database. Below is my code and for some reason it isnt working can any one please please help me!! Im very desperate and ive been trying to figure out the problem for hours.
DatabaseHelperUser class:
public class DatabaseHelperUser extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "User.db";
public static final String TABLE_NAME = "User_table";
public static final String COL1 = "ID";
public static final String COL2 = "UserNum";
public static final String COL3 = "UserName";
public static final String COL4 = "Password";
public static final String COL5 = "BirthDate";
public static final String COL6 = "Phone";
public static final String COL7 = "Address";
public DatabaseHelperUser(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, UserNum TEXT,UserName Text,Password Text,BirthDate Text,Phone Text,Address Text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;
}
public boolean deleteData(String UserName) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "UserName" + "=?" + UserName, null) > 0;
}
}
RemoveUser class:
public class RemoveUser extends AppCompatActivity {
Button btdelete;
EditText txtUser;
DatabaseHelperUser myDb;
private String selectedName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_remove_user);
btdelete = (Button) findViewById(R.id.butRemove);
txtUser = (EditText) findViewById(R.id.etxtUserName);
myDb = new DatabaseHelperUser(this);
btdelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean delete = myDb.deleteData(txtUser.getText().toString());
if(delete == true)
Toast.makeText(RemoveUser.this,"User has been deleted", Toast.LENGTH_LONG).show();
else
Toast.makeText(RemoveUser.this,"User has not been deleted", Toast.LENGTH_LONG).show();
}
});
}
}
You must pass the variable UserName as the 3d argument of the method delete(), so it will replace the placeholder ? when the statement is executed:
public boolean deleteData(String UserName) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "UserName = ?", new String[] {UserName}) > 0;
}

Picasso is loading URL but no picture is shown

I have one of the weirdest problems I've had so far. I am creating an app which sends information about books and authors through different activities. I am sending them with the help of intents. My problem is within the authors section. I am sending name, age and the picture. Name and age are send successfully and to my knowledge with the debugger, the image is sent successfully as well. However, Picasso refuses to load it in ImageView. There are no errors shown and I have no idea what is going on. Here is some code.
This function resets the information in my database:
public void resetAuthor()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME_AUTHORS);
db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + TABLE_NAME_AUTHORS + "'");
addBegginingInfoAuthor("J.K.Rowling", 54, "https://www.biographyonline.net/wp-content/uploads/2014/05/jk-rowling4.jpg");
addBegginingInfoAuthor("J.R.R. Tolken", 81, "https://www.biography.com/.image/t_share/MTE5NTU2MzE2Mzg4MzYxNzM5/jrr-tolkien-9508428-1-402.jpg");
addBegginingInfoAuthor("Arthur Conan Doyle", 71, "https://upload.wikimedia.org/wikipedia/commons/b/bd/Arthur_Conan_Doyle_by_Walter_Benington%2C_1914.png");
}
AuthorAdapter class. This is the adapter for my recycler view which displays details about the author. It is also where I start up the intent to move to the other activity:
#Override
public void onBindViewHolder(#NonNull AuthorsViewHolder holder, int position) {
if (!mCursor.moveToPosition(position))
{
return;
}
final int author_id = mCursor.getInt(mCursor.getColumnIndex(DatabaseHelper.AUTHORS_COL_1));
final String name = mCursor.getString(mCursor.getColumnIndex(DatabaseHelper.AUTHORS_COL_2));
final String age = mCursor.getString(mCursor.getColumnIndex(DatabaseHelper.AUTHORS_COL_3));
final String image = mCursor.getString(mCursor.getColumnIndex(DatabaseHelper.AUTHORS_COL_4));
holder.authorIndex.setText(String.valueOf(author_id));
holder.authorName.setText(name);
holder.authorAge.setText(String.valueOf(age));
holder.authorName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), displayBooksFromAuthor.class);
intent.putExtra("Author_id", author_id);
intent.putExtra("Author_name", name);
intent.putExtra("Author_age", age);
intent.putExtra("Author_image", image);
mContext.startActivity(intent);
}
});
}
And finally, my DisplayAuthorDetails class which receives the data from the intent and displays it:
int author_id = intent.getIntExtra("Author_id", 0);
String author_name = intent.getStringExtra("Author_name");
String author_age = intent.getStringExtra("Author_age");
String author_picture = intent.getStringExtra("Author_image");
et_name.setText(author_name);
et_age.setText(author_age);
et_id.setText(String.valueOf(author_id));
Picasso.get().load(author_picture).into(author_image);
I have the library dependency and also the two permissions in the manifest file
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
implementation 'com.squareup.picasso:picasso:2.71828
The weirdest part of this problem is that when I create a brand new project and try to load an image it loads successfully. Any help is appreciated. Thank you for your time
EDIT
DatabaseHelper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Books and Authors.db";
public static final String TABLE_NAME_AUTHORS = "Authors_table";
public static final String AUTHORS_COL_1 = "Author_ID";
public static final String AUTHORS_COL_2 = "Name";
public static final String AUTHORS_COL_3 = "Age";
public static final String AUTHORS_COL_4 = "Author_picture";
public static final String TABLE_NAME_BOOKS = "Books_table";
public static final String BOOKS_COL_1 = "Book_ID";
public static final String BOOKS_COL_2 = "Author_Foreign";
public static final String BOOKS_COL_3 = "Title";
public static final String BOOKS_COL_4 = "Price";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 2);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME_BOOKS + " (Book_ID INTEGER PRIMARY KEY AUTOINCREMENT, Title TEXT," + "Author_Foreign INT," + "Price TEXT)");
db.execSQL("create table " + TABLE_NAME_AUTHORS + " (Author_ID INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT," + "Age INTEGER," + "Author_picture TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_AUTHORS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_BOOKS);
onCreate(db);
}
public boolean insertDataBooks(String title, float price) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(BOOKS_COL_3, title);
contentValues.put(BOOKS_COL_4, price);
long result = db.insert(TABLE_NAME_BOOKS, null, contentValues);
if (result == 1) {
return false;
} else {
return true;
}
}
public boolean insertDataAuthors(String name, int age) {
SQLiteDatabase mydb = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(AUTHORS_COL_2, name);
contentValues.put(AUTHORS_COL_3, age);
long result = mydb.insert(TABLE_NAME_AUTHORS, null, contentValues);
if (result == 1) {
return false;
} else {
return true;
}
}
public boolean addBegginingInfo(int foreign_author_id, String title, double price) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(BOOKS_COL_2, foreign_author_id);
contentValues.put(BOOKS_COL_3, title);
contentValues.put(BOOKS_COL_4, price);
long result = db.insert(TABLE_NAME_BOOKS, null, contentValues);
if (result == 1) {
return false;
} else {
return true;
}
}
public boolean addBegginingInfoAuthor(String name, int age, String image)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(AUTHORS_COL_2, name);
contentValues.put(AUTHORS_COL_3, age);
contentValues.put(AUTHORS_COL_4, image);
long result = db.insert(TABLE_NAME_AUTHORS, null, contentValues);
if (result == 1) {
return false;
} else {
return true;
}
}
public Integer deleteBook(String index) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME_BOOKS, "Book_ID = ?", new String[]{index});
}
public Integer deleteAuthor(String authorIndex) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME_AUTHORS, "Author_ID = ?", new String[]{authorIndex});
}
public void resetBookTable() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME_BOOKS);
db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + TABLE_NAME_BOOKS + "'");
addBegginingInfo(1, "Harry Potter", 9.99);
addBegginingInfo(1, "Fantastic Beasts", 14.99);
addBegginingInfo(2, "Lord of the Rings", 8.99);
addBegginingInfo(2, "The Hobbit", 12.99);
addBegginingInfo(3, "Sherlock Holmes", 6.99);
addBegginingInfo(3, "Valley of Fear", 7.99);
}
public void resetAuthor()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME_AUTHORS);
db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + TABLE_NAME_AUTHORS + "'");
addBegginingInfoAuthor("J.K.Rowling", 54, "https://www.biographyonline.net/wp-content/uploads/2014/05/jk-rowling4.jpg");
addBegginingInfoAuthor("J.R.R. Tolken", 81, "https://www.biography.com/.image/t_share/MTE5NTU2MzE2Mzg4MzYxNzM5/jrr-tolkien-9508428-1-402.jpg");
addBegginingInfoAuthor("Arthur Conan Doyle", 71, "https://upload.wikimedia.org/wikipedia/commons/b/bd/Arthur_Conan_Doyle_by_Walter_Benington%2C_1914.png");
}
}
After many hours of trying I finally found out that to fix this issue I just had to re-install the app on the emulator.

Android Studio, how to retrieve data from Sqlite database and display it into textview?

I created an SQLite Database in my app, and I insert the data into it. And now I want to retrieve data from it but I want just insert one data and retrieve it then display it into a TextView.
public class Db_sqlit extends SQLiteOpenHelper{
String TABLE_NAME = "BallsTable";
public final static String name = "db_data";
public Db_sqlit(Context context) {
super(context, name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+TABLE_NAME+" (id INTEGER PRIMARY KEY AUTOINCREMENT, ball TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String balls){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("ball",balls);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1){
return false;
}
else
return true;
}
public void list_balls(TextView textView) {
Cursor res = this.getReadableDatabase().rawQuery("select ball from "+TABLE_NAME+"",null);
textView.setText("");
while (res.moveToNext()){
textView.append(res.getString(1));
}
}
}
Here is an example of how I achieved this.
In this example I will store, retrieve, update and delete a students name and age.
First create a class, I called mine
DBManager.java
public class DBManager {
private Context context;
private SQLiteDatabase database;
private SQLiteHelper dbHelper;
public DBManager(Context c) {
this.context = c;
}
public DBManager open() throws SQLException {
this.dbHelper = new SQLiteHelper(this.context);
this.database = this.dbHelper.getWritableDatabase();
return this;
}
public void close() {
this.dbHelper.close();
}
public void insert(String name, String desc) {
ContentValues contentValue = new ContentValues();
contentValue.put(SQLiteHelper.NAME, name);
contentValue.put(SQLiteHelper.AGE, desc);
this.database.insert(SQLiteHelper.TABLE_NAME_STUDENT, null, contentValue);
}
public Cursor fetch() {
Cursor cursor = this.database.query(SQLiteHelper.TABLE_NAME_STUDENT, new String[]{SQLiteHelper._ID, SQLiteHelper.NAME, SQLiteHelper.AGE}, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public int update(long _id, String name, String desc) {
ContentValues contentValues = new ContentValues();
contentValues.put(SQLiteHelper.NAME, name);
contentValues.put(SQLiteHelper.AGE, desc);
return this.database.update(SQLiteHelper.TABLE_NAME_STUDENT, contentValues, "_id = " + _id, null);
}
public void delete(long _id) {
this.database.delete(SQLiteHelper.TABLE_NAME_STUDENT, "_id=" + _id, null);
}
}
Then create a SQLiteOpenHelper I called mine
SQLiteHelper.java
public class SQLiteHelper extends SQLiteOpenHelper {
public static final String AGE = "age";
private static final String CREATE_TABLE_STUDENT = " create table STUDENTS ( _id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL , age TEXT );";
private static final String DB_NAME = "STUDENTS.DB";
private static final int DB_VERSION = 1;
public static final String NAME = "name";
public static final String TABLE_NAME_STUDENT = "STUDENTS";
public static final String _ID = "_id";
public SQLiteHelper(Context context) {
super(context, DB_NAME, null, 1);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_STUDENT);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS STUDENTS");
onCreate(db);
}
}
TO ADD:
In this example I take the text from EditText and when the button is clicked I check if the EditText is empty or not. If it is not empty and the student doesn't already exist I insert the students name and age into the database. I display a Toast, letting the user know of the status:
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (edtName.getText().toString().trim().length() == 0) {
Toast.makeText(getApplicationContext(), "Please provide your students name", Toast.LENGTH_SHORT).show();
} else{
try {
if (edtAge.getText().toString().trim().length() != 0) {
String name = edtName.getText().toString().trim();
String age = edtAge.getText().toString().trim();
String query = "Select * From STUDENTS where name = '"+name+"'";
if(dbManager.fetch().getCount()>0){
Toast.makeText(getApplicationContext(), "Already Exist!", Toast.LENGTH_SHORT).show();
}else{
dbManager.insert(name, age);
Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "please provide student age!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
TO UPDATE:
Here I take the Text in EditText and update the student when the button is clicked. You can also place the following in a try/catch to make sure it is updated successfully.
btnupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = nameText.getText().toString();
String age = ageText.getText().toString();
dbManager.update(_id, name, age);
Toast.makeText(getApplicationContext(), "Updated successfully!", Toast.LENGTH_SHORT).show();
}
});
TO DELETE:
dbManager.delete(_id);
Toast.makeText(getApplicationContext(), "Deleted successfully!", Toast.LENGTH_SHORT).show();
TO GET:
Here I get the name of the student and display it in a TextView
DBManager dbManager = new DBManager(getActivity());
dbManager.open();
Cursor cursor = dbManager.fetch();
cursor.moveToFirst();
final TextView studentName = (TextView) getActivity().findViewById(R.id.nameOfStudent);
studentName.settext(cursor.getString(0));
Then I have implement the code in main java class where I want to show using cursor.moveToNext()
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor result = databaseSQLite2.searchData(searchET.getText().toString());
while (result.moveToNext()){
searchresultTV.setText(result.getString(2));
}
}
});
For fetching data from sqlite I have done this method in DatabaseHelper class
public Cursor searchData(String id){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
//String qry = "SELECT * FROM "+TABLE_NAME+" WHERE ID="+id;
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE ID="+id,null);
return cursor;
}

How to resolve index out of bounds error with SQLite?

I'm trying to get data from SQLite databse and when I'm trying, my app crashes and the error is: "android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1".
What am I doing wrong?
This is my activity:
public class EventInfo extends AppCompatActivity {
DatabaseHelper myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_info);
myDb=new DatabaseHelper(this);
SharedPreferences sp = getSharedPreferences("key", 0);
final String event_title=sp.getString("event_title", "");
final String event_date=sp.getString("event_date", "");
String event_content=sp.getString("event_content","");
String age_limit=sp.getString("age_limit","");
String event_hour=sp.getString("event_hour","");
String location_left=sp.getString("location_left","");
String location_right=sp.getString("location_right","");
TextView txt5=(TextView)findViewById(R.id.textView5);
TextView txt6=(TextView)findViewById(R.id.textView6);
TextView txt7=(TextView)findViewById(R.id.textView7);
TextView txt8=(TextView)findViewById(R.id.textView8);
TextView txt9=(TextView)findViewById(R.id.textView9);
TextView txt10=(TextView)findViewById(R.id.textView10);
TextView txt14=(TextView)findViewById(R.id.textView14);
txt5.setText(event_title);
txt6.setText(event_date);
txt7.setText(age_limit);
txt8.setText(event_content);
txt9.setText(event_hour);
txt10.setText("Press here for event location");
String votes_count=myDb.getVotesCount(event_title);
if(votes_count.equals("1")) {
txt14.setText("Cancel Attending");
}
else {
if(votes_count.equals("0")||votes_count.isEmpty()) {
txt14.setText("Accept Attending");
}
else
{
txt14.setText("Error");
}
}
txt10.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(EventInfo.this, MapsActivity3.class);
startActivity(intent);
}
});
txt14.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String votes_count=myDb.getVotesCount(event_title);
if(votes_count.equals("0")||votes_count.isEmpty()) {
boolean insert = myDb.insertData("1", event_title, event_date);
if (insert == true)
Toast.makeText(EventInfo.this, "You have accepted the arrival", Toast.LENGTH_LONG).show();
else
Toast.makeText(EventInfo.this, "Error", Toast.LENGTH_LONG).show();
}
else
{
if(votes_count.equals("1"))
{
boolean insert = myDb.insertData("0", event_title, event_date);
if (insert == true)
Toast.makeText(EventInfo.this, "You have canceled the arrival", Toast.LENGTH_LONG).show();
else
Toast.makeText(EventInfo.this, "Error, Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(EventInfo.this, votes_count.toString(), Toast.LENGTH_LONG).show();
}
}
}
});
}
}
And this is my DatabaseHelper Class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="usersDB.db";
public static final String TABLE_NAME="votes_table";
public static final String COL2="VOTESCOUNT";
public static final String COL3="EVENTTITLE";
public static final String COL4="EVENTDATE";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (VOTESCOUNT TEXT, EVENTTITLE TEXT, EVENTDATE TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String votes_count, String event_title, String event_date){
SQLiteDatabase db =this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put(COL2,votes_count);
contentValues.put(COL3,event_title);
contentValues.put(COL4, event_date);
long result=db.insert(TABLE_NAME,null,contentValues);
if(result==-1)
{
return false;
}
else
return true;
}
public Cursor getAllData()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
public Cursor getEventTitles()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res=db.rawQuery("select EVENTTITLE from "+TABLE_NAME,null);
return res;
}
public Cursor getEventDate(String eventtitle)
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res=db.rawQuery("select EVENTDATE from "+TABLE_NAME+" where EVENTTITLE='"+eventtitle+"'",null);
return res;
}
public String getVotesCount(String eventtitle)
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res=db.rawQuery("select VOTESCOUNT from "+TABLE_NAME+" where EVENTTITLE='"+eventtitle+"'",null);
String votes_count=res.getString(0);
return votes_count;
}
}
You have to move the Cursor to the first row before you access data from it, and it's a good idea to check the return value of moveToFirst() as well to make sure that the Cursor has data. Also, be sure to close any Cursor when you're done with it:
public String getVotesCount(String eventtitle)
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res=db.rawQuery("select VOTESCOUNT from "+TABLE_NAME+" where EVENTTITLE='"+eventtitle+"'",null);
String votes_count = null;
if (res.moveToFirst()) {
votes_count =res.getString(0);
}
res.close();
return votes_count;
}
And add a null check for the return value:
String votes_count = myDb.getVotesCount(event_title);
if(votes_count != null && (votes_count.equals("0")||votes_count.isEmpty())) {
//...............

Categories