An error with my custom listview and my database - android

I have a SQLite Database inside my application and I need to get data out of my database and put these data inside a custom listview I made. This listview is inside my Games fragment, which I use for my Viewpager activity (So you'll be able to swipe through the activies) I wrote all the code for it, but when I run my application, my app keeps crashing and giving me the same crash-report.
It would be great if there would be a way to fix it.
Crash-report:
05-19 11:07:38.096: E/AndroidRuntime(775): FATAL EXCEPTION: main
05-19 11:07:38.096: E/AndroidRuntime(775): java.lang.NullPointerException
05-19 11:07:38.096: E/AndroidRuntime(775): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
05-19 11:07:38.096: E/AndroidRuntime(775): at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
05-19 11:07:38.096: E/AndroidRuntime(775): at com.example.gamenity.DBHelper.getAllGames(DBHelper.java:122)
05-19 11:07:38.096: E/AndroidRuntime(775): at com.example.gamenity.Games.onCreateView(Games.java:40)
05-19 11:07:38.096: E/AndroidRuntime(775): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1478)
05-19 11:07:38.096: E/AndroidRuntime(775): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
05-19 11:07:38.096: E/AndroidRuntime(775): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
05-19 11:07:38.096: E/AndroidRuntime(775): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
05-19 11:07:38.096: E/AndroidRuntime(775): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
05-19 11:07:38.096: E/AndroidRuntime(775): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
05-19 11:07:38.096: E/AndroidRuntime(775): at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
05-19 11:07:38.096: E/AndroidRuntime(775): at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
05-19 11:07:38.096: E/AndroidRuntime(775): at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
05-19 11:07:38.096: E/AndroidRuntime(775): at android.support.v4.view.ViewPager$3.run(ViewPager.java:244)
DBHelper.class
package com.example.gamenity;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
public class DBHelper extends SQLiteOpenHelper {
// database
private static final String DB_NAME = "GamenityDB";
private static final int DB_VERSION = 6;
// tabellen
private static final String TABLE_USERS = "Users";
private static final String TABLE_GAMES = "Games";
public static final String KEY_ID = "userID";
private static final String CREATE_USERS =
"create table Users(userID integer primary key autoincrement, "
+ "username text not null, password text not null, email text not null, gender text, DOB text, picture BLOB);";
public static final String FLD_USERNAME = "username";
public static final String FLD_PASSWORD = "password";
public static final String FLD_EMAIL = "email";
public static final String FLD_GENDER = "gender";
private static final String CREATE_GAMES =
"create table Games (gameID integer primary key autoincrement, "
+ "Title varchar(255) not null, Description text not null, Genre text not null, Release date null, PS4 text null, " +
"PS3 text null, X1 text null, X360 text null, WiiU text null, PC text null, gamePicture blob null);";
public static final String FLD_TITLE = "Title";
public static final String FLD_DESCRIPTION = "Description";
public static final String FLD_GENRE = "Genre";
public static final String FLD_RELEASE = "Release";
public static final String FLD_PS4 = "PS4";
public static final String FLD_PS3 = "PS3";
public static final String FLD_X1 = "X1";
public static final String FLD_X360 = "X360";
public static final String FLD_WiiU = "WiiU";
public static final String FLD_PC = "PC";
public static final String FLD_GAMEIMAGE = "gamePicture";
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USERS);
db.execSQL(CREATE_GAMES);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_GAMES);
onCreate(db);
}
// database functies
public void createUser(String naam, String pw, String mail, String gender) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FLD_USERNAME, naam);
values.put(FLD_PASSWORD, pw);
values.put(FLD_EMAIL, mail);
values.put(FLD_GENDER, gender);
db.insert(TABLE_USERS, null, values);
db.close();
}
public void createGame(String title, String description,String genre, String release,
String PS4, String PS3, String X1, String X360, String WiiU, String PC, byte[] gamePicture) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FLD_TITLE, title);
values.put(FLD_DESCRIPTION, description);
values.put(FLD_GENRE, genre);
values.put(FLD_RELEASE, release);
values.put(FLD_PS4, PS4);
values.put(FLD_PS3, PS3);
values.put(FLD_X1, X1);
values.put(FLD_X360, X360);
values.put(FLD_WiiU, WiiU);
values.put(FLD_PC, PC);
values.put(FLD_GAMEIMAGE, gamePicture);
db.insert(TABLE_GAMES, null, values);
db.close();
}
public ArrayList<Game> getAllGames() {
ArrayList<Game> ArrayGames = new ArrayList<Game>();
String selectQuery = "SELECT * FROM " + TABLE_GAMES + " ORDER BY Release";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Game Game = new Game(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4),cursor.getString(5), cursor.getString(6), cursor.getString(7), cursor.getString(8),cursor.getString(9), cursor.getString(10), cursor.getBlob(1));
ArrayGames.add(Game);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return ArrayGames;
}
Game.class
package com.example.gamenity;
public class Game {
private String title, description, genre, release, PS3, PS4, X1, X360, WiiU, PC;
private byte[] image;
public Game(String title, String description, String genre, String release,
String PS3, String PS4, String X1, String X360, String WiiU, String PC, byte[] image ) {
super();
this.title = title;
this.description = description;
this.genre = genre;
this.release = release;
this.PS3 = PS3;
this.PS4 = PS4;
this.X1 = X1;
this.X360 = X360;
this.WiiU = WiiU;
this.PC = PC;
this.image = image;
}
//Getters
public String getTitle() {
return this.title;
}
public String getDescription() {
return this.description;
}
public String getRelease() {
return this.release;
}
public String getGenre() {
return this.genre;
}
public String getPS3() {
return this.PS3;
}
public String getPS4() {
return this.PS4;
}
public String getX1() {
return this.X1;
}
public String getX360() {
return this.X360;
}
public String getWiiU() {
return this.WiiU;
}
public String getPC() {
return this.PC;
}
public byte[] getImage() {
return this.image;
}
}
ListviewGamesAdapter.class(My custom adapter for my listview)
package com.example.gamenity;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class ListviewGamesAdapter extends ArrayAdapter<Game>{
private final Context context;
private final ArrayList<Game> GamesArrayList;
public ListviewGamesAdapter(Context context, ArrayList<Game> GamesArrayList) {
super(context, R.layout.list_row_games, GamesArrayList);
this.context = context;
this.GamesArrayList = GamesArrayList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// 1. Create inflater
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// 2. Get rowView from inflater
View rowView = inflater.inflate(R.layout.list_row_games, parent, false);
// 3. Get the two text view from the rowView
TextView Title = (TextView) rowView.findViewById(R.id.title);
TextView Genre= (TextView) rowView.findViewById(R.id.genre);
TextView Description = (TextView) rowView.findViewById(R.id.description);
// 4. Set the text for textView
Title.setText(GamesArrayList.get(position).getTitle());
Description.setText(GamesArrayList.get(position).getDescription());
Genre.setText(GamesArrayList.get(position).getGenre());
// 5. return rowView
return rowView;
}
}
list_row_games.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/listview_selector"
android:orientation="horizontal"
android:padding="5dip" >
<!-- Left side Thumbnail image -->
<LinearLayout android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dp"
android:layout_alignParentLeft="true"
android:background="#drawable/stroke"
android:layout_marginRight="5dip">
<ImageView
android:id="#+id/list_image"
android:layout_width="75dp"
android:layout_height="85dp"
android:src="#drawable/no_picture"/>
</LinearLayout>
<!-- Title -->
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:text="Title"
android:textColor="#color/black"
android:typeface="sans"
android:textSize="15dip"
android:textStyle="bold"/>
<!-- Genre -->
<TextView
android:id="#+id/genre"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/title"
android:layout_below="#+id/title"
android:text="Genre"
android:textColor="#color/midGray"
android:textSize="12dip" />
<!-- Description -->
<TextView
android:id="#+id/description"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/follow"
android:layout_alignLeft="#+id/title"
android:layout_below="#+id/genre"
android:layout_toLeftOf="#+id/follow"
android:text="Description"
android:textColor="#color/darkGray"
android:textSize="13dip" />
<!-- Release date -->
<TextView
android:id="#+id/release"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/title"
android:layout_alignBottom="#+id/title"
android:layout_alignRight="#+id/genre"
android:gravity="right"
android:text="Fall 2014"
android:textColor="#color/midBlue"
android:textSize="10dip"
android:textStyle="bold" />
<Button
android:id="#+id/follow"
android:layout_width="75dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/thumbnail"
android:layout_alignRight="#+id/genre"
android:background="#drawable/button_follow"
android:drawableRight="#drawable/portal_stickman"
android:text="Follow"
android:textColor="#color/white"
android:textSize="15dp"
android:textStyle="bold" />
</RelativeLayout>
Games.class (My activity with the listview)
package com.example.gamenity;
import android.content.Intent;
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.RelativeLayout;
public class Games extends Fragment {
DBHelper db = new DBHelper(getActivity());
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
if(container == null) {
return null;
}
RelativeLayout mRelativeLayout = (RelativeLayout)inflater.inflate(R.layout.activity_games, container, false);
Button btn_addGame = (Button)mRelativeLayout.findViewById(R.id.addGame);
ListView list_games = (ListView)mRelativeLayout.findViewById(R.id.listviewGames);
btn_addGame.setOnClickListener(new View.OnClickListener() {
public void onClick (View view) {
Intent intent_addGame = new Intent(getActivity(), AddGame.class);
startActivity(intent_addGame);
}
});
ListviewGamesAdapter adapter = new ListviewGamesAdapter(getActivity(), db.getAllGames());
list_games.setAdapter(adapter);
db.close();
return mRelativeLayout;
}
}
Viewpager.class
package com.example.gamenity;
import java.util.List;
import java.util.Vector;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
public class Viewpager extends FragmentActivity {
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewpager);
initialisePaging();
ActionbarButtons();
}
private void initialisePaging() {
List<Fragment> pages = new Vector<Fragment>();
pages.add(Fragment.instantiate(this, Home.class.getName()));
pages.add(Fragment.instantiate(this, News.class.getName()));
pages.add(Fragment.instantiate(this, Games.class.getName()));
mPagerAdapter = new PagerAdapter(this.getSupportFragmentManager(), pages);
ViewPager pager = (ViewPager)findViewById(R.id.viewpager);
pager.setAdapter(mPagerAdapter);
}
public void ActionbarButtons() {
ImageButton notifications_btn = (ImageButton)findViewById(R.id.notifications_button);
notifications_btn.setOnClickListener(new View.OnClickListener() {
public void onClick (View view) {
Intent notifications = new Intent(Viewpager.this, Notifications.class);
startActivity(notifications);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.viewpager, menu);
return true;
}
}

You need a context in order to get a database instance, but you passed the contstructor of DBHelper null. You should not initialize the DBHelper until at least onCreate. Instead of this:
DBHelper db = new DBHelper(getActivity());
Do this:
DBHelper db;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
db = new DBHelper(getActivity());
//...
}
Also, I believe you aren't accessing your cursor properly. For example, cursor.getBlob(1) should return null because column 1 is TEXT. Also, cursor.getText(4) should return null because column 4 is DATE. Also, you can't store dates in SQLite, you should store them as long milliseconds. Do something like this:
String title = cursor.getString(cursor.getColumnIndex(FLD_TITLE));
String customer = cursor.getString(cursor.getColumnIndex(FLD_DESCRIPTION));
Date date = (Date)cursor.getLong(cursor.getColumnIndex(FLD_RELEASE));
byte[] image = cursor.getBlob(cursor.getColumnIndex(FLD_GAMEIMAGE));
//...
Game Game = new Game(title, customer, date, //etc);
ArrayGames.add(Game);

Related

Cannot add data to database using ContentProvider

I am learning Content Providers and stuff in Android. I cannot figure out why no data is being added using ProductProvider.
I have looked over every class but there is something wrong with the way data is being inserted or queried from the database but i just can't figure out what is broken.
Here are the code files
Activity
HomePage.java
package com.example.tanmay.shoppingapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.example.tanmay.shoppingapp.DataSet.ProductListContract.ProductEntry;
public class HomePage extends AppCompatActivity {
TextView idBox;
TextView nameBox;
String TAG = "com.whatever.tag";
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home_page, menu);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
//Adding custom toolbar
android.support.v7.widget.Toolbar toolbar = findViewById(R.id.homePageToolBar);
setSupportActionBar(toolbar);
insertProduct();
//Projection is just the name of the columns we would like to receive
String[] projection = {
ProductEntry._ID,
ProductEntry.COLUMN_NAME_PRODUCT_NAME
};
Cursor cursorNew = getContentResolver().query(ProductEntry.CONTENT_URI, projection, null, null, null);
cursorNew.moveToNext();
int uweh = cursorNew.getInt(cursorNew.getColumnIndex(ProductEntry.COLUMN_NAME_PRODUCT_NAME));
TextView coco = findViewById(R.id.e83957);
coco.setText(uweh);
ListView listView = findViewById(R.id.productList_homepage);
listView.setAdapter(new productListAdapter(HomePage.this, cursorNew));
}
private void insertProduct() {
ContentValues values = new ContentValues();
//The values contains all the data to be entered into the table
values.put(ProductEntry._ID, 67);
values.put(ProductEntry.COLUMN_NAME_PRODUCT_NAME, R.string.product1Name);
values.put(ProductEntry.COLUMN_NAME_PRODUCT_PRICE, R.integer.product1Price);
values.put(ProductEntry.COLUMN_NAME_PRODUCT_THUMBNAIL, R.drawable.product1thumbnail);
values.put(ProductEntry.COLUMN_NAME_PRODUCT_IMAGE, R.drawable.product1image);
// values.put(ProductEntry.COLUMN_NAME_PRODUCT_NAME, R.string.product2Name);
Uri newUri = getContentResolver().insert(ProductEntry.CONTENT_URI, values);
}
private class productListAdapter extends CursorAdapter {
public productListAdapter(Context context, Cursor c) {
super(context, c);
}
//Returns a new blank view
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
return LayoutInflater.from(context).inflate(R.layout.dummy_item, viewGroup, false);
}
//Actually responsible for the data binding
#Override
public void bindView(View view, Context context, Cursor cursor) {
idBox = (TextView) findViewById(R.id.dummy_item_id_box);
nameBox = (TextView) findViewById(R.id.dummy_item_name_box);
id.setText(cursor.getInt(cursor.getColumnIndexOrThrow(ProductEntry._ID)));
name.setText(getResources().getString(cursor.getInt(cursor.getColumnIndexOrThrow(ProductEntry.COLUMN_NAME_PRODUCT_NAME))));
}
}
}
ProductDbHelper
package com.example.tanmay.shoppingapp.DataSet;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import static com.example.tanmay.shoppingapp.DataSet.ProductListContract.ProductEntry.COLUMN_NAME_PRODUCT_IMAGE;
import static com.example.tanmay.shoppingapp.DataSet.ProductListContract.ProductEntry.COLUMN_NAME_PRODUCT_NAME;
import static com.example.tanmay.shoppingapp.DataSet.ProductListContract.ProductEntry.COLUMN_NAME_PRODUCT_PRICE;
import static com.example.tanmay.shoppingapp.DataSet.ProductListContract.ProductEntry.COLUMN_NAME_PRODUCT_THUMBNAIL;
import static com.example.tanmay.shoppingapp.DataSet.ProductListContract.ProductEntry.TABLE_NAME;
import static com.example.tanmay.shoppingapp.DataSet.ProductListContract.ProductEntry._ID;
/**
* Created by tanmay on 3/3/18.
*/
public class ProductDbHelper extends SQLiteOpenHelper {
//Name of the database file
public static final String DATABASE_NAME = "products.db";
//Database version to be incremented on change in schema
public static final int DATABASE_VERSION = 1;
// SQL command to create the table
// All columns contain integers because they don't contain the actual Strings and Images,
// instead they hold the integral resource identifiers (R.string.* / R.integer.* / R.drawable.*).
public static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TABLE_NAME + " (" +
_ID + " INTEGER PRIMARY KEY, " +
COLUMN_NAME_PRODUCT_NAME + " INTEGER, " +
COLUMN_NAME_PRODUCT_PRICE + "INTEGER, " +
COLUMN_NAME_PRODUCT_THUMBNAIL + "INTEGER, " +
COLUMN_NAME_PRODUCT_IMAGE + "INTEGER)";
// Checks if a particular table already exists and then deletes it.
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + TABLE_NAME;
//Default constructor
public ProductDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// Creates the database bu executing String as SQL command
sqLiteDatabase.execSQL(ProductDbHelper.SQL_CREATE_ENTRIES);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
// Firsts deletes the old database then creates a new one
sqLiteDatabase.execSQL(ProductDbHelper.SQL_DELETE_ENTRIES);
onCreate(sqLiteDatabase);
}
#Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
}
ProductListContract
package com.example.tanmay.shoppingapp.DataSet;
import android.content.ContentResolver;
import android.net.Uri;
import android.provider.BaseColumns;
/**
* Created by tanmay on 26/2/18.
*/
public class ProductListContract {
// Refers to this particular application
public static final String CONTENT_AUTHORITY = "com.example.tanmay.shoppingapp";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
//Empty constructor to prevent instantiation
private ProductListContract() {
}
public static class ProductEntry implements BaseColumns {
// Name of the table
public static final String TABLE_NAME = "productListPrimary";
// Uri pointing to this particular table
public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, ProductEntry.TABLE_NAME);
//MIME type
public static final String CONTENT_LIST_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + TABLE_NAME;
public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + TABLE_NAME;
// Names of various columns
public static final String COLUMN_NAME_PRODUCT_NAME = "name";
public static final String _ID = BaseColumns._ID;
public static final String COLUMN_NAME_PRODUCT_PRICE = "price";
public static final String COLUMN_NAME_PRODUCT_THUMBNAIL = "thumbnail";
public static final String COLUMN_NAME_PRODUCT_IMAGE = "image";
}
}
ProductProvider.java
package com.example.tanmay.shoppingapp.DataSet;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.example.tanmay.shoppingapp.DataSet.ProductListContract.ProductEntry;
/**
* Created by tanmay on 28/2/18.
*/
public class ProductProvider extends ContentProvider {
private static final int ProductListTable = 1;
private static final int ProductListRow = 2;
private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
sUriMatcher.addURI(ProductListContract.CONTENT_AUTHORITY, ProductEntry.TABLE_NAME, ProductListTable);
sUriMatcher.addURI(ProductListContract.CONTENT_AUTHORITY, ProductEntry.TABLE_NAME + "/#", ProductListRow);
}
private ProductDbHelper mDbHelper;
#Override
public boolean onCreate() {
//Creates a new DbHelper object
mDbHelper = new ProductDbHelper(getContext());
return true;
}
#Nullable
#Override
public Cursor query(#NonNull Uri uri, #Nullable String[] projection, #Nullable String selection, #Nullable String[] selectionArgs, #Nullable String sortOrder) {
// Obtain a read-only copy of the database
SQLiteDatabase sqLiteDatabase = mDbHelper.getReadableDatabase();
// This cursor holds the result from the query.
Cursor cursor = null;
// Switch to perform specific kind of query based on type of Uri
switch (sUriMatcher.match(uri)) {
// Uri demanding entire table with the criteria defined in the fundtion params
case ProductListTable:
// All the argumnets are the ones passed
cursor = sqLiteDatabase.query(ProductEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
break;
// Uri demanding a particular row item.
case ProductListRow:
// "?" is a wildcard which gets replaced by any integer
selection = ProductEntry._ID + "=?";
selectionArgs = new String[]{String.valueOf((ContentUris.parseId(uri)))};
cursor = sqLiteDatabase.query(ProductEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
break;
default:
throw new IllegalArgumentException("Cannot query unkown URI " + uri);
}
//Return the cursor containing query results
return cursor;
}
#Nullable
#Override
public String getType(#NonNull Uri uri) {
final int match = sUriMatcher.match(uri);
switch (match) {
case ProductListTable:
return ProductEntry.CONTENT_LIST_TYPE;
case ProductListRow:
return ProductEntry.CONTENT_ITEM_TYPE;
default:
throw new IllegalStateException("Unkown URI " + uri + " with match " + match);
}
}
#Nullable
#Override
public Uri insert(#NonNull Uri uri, #Nullable ContentValues contentValues) {
final int match = sUriMatcher.match(uri);
switch (match) {
case ProductListTable:
return insertProduct(uri, contentValues);
default:
throw new IllegalArgumentException("Insertion is not supported for " + uri);
}
}
public Uri insertProduct(Uri uri, ContentValues contentValues) {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
long id = db.insert(ProductEntry.TABLE_NAME, null, contentValues);
if (id == -1) {
Log.e("com.whatever.tag", "Failed to insert row for " + uri);
return null;
}
return ContentUris.withAppendedId(uri, id);
}
#Override
public int delete(#NonNull Uri uri, #Nullable String s, #Nullable String[] strings) {
return 0;
}
#Override
public int update(#NonNull Uri uri, #Nullable ContentValues contentValues, #Nullable String s, #Nullable String[] strings) {
return 0;
}
}
LayoutFiles
HomePage Activities Layout File
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
android:orientation="vertical" 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.tanmay.shoppingapp.HomePage">
<android.support.v7.widget.Toolbar
android:id="#+id/homePageToolBar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:title="#string/app_name">
</android.support.v7.widget.Toolbar>
<TextView
android:id="#+id/e83957"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="wwt49832"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ListView
android:layout_marginTop="?attr/actionBarSize"
android:id="#+id/productList_homepage"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</android.support.constraint.ConstraintLayout>
Layout of one ListView element
DummyItem because a different layout will be applied once everything works.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_margin="8dp"
android:text="327"
android:id="#+id/dummy_item_id_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_margin="8dp"
android:text="placeholder"
android:id="#+id/dummy_item_name_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

Dual Spinner value,Dual checkbox value,Edit text value insert in to sqlite upon submitting the Button

Experts,
I would like to store my Spinner1,Spinner2 and multiple checkbox value,edit text value in to my sqlite database upon submitting the button. I try to tweak the same but no luck. Could you advise experts..
Layout is attached below. Two spinner and multiple check box and one submit button,one edit text.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dip"
android:text="#string/lblAcc" />
<!-- Spinner Dropdown -->
<Spinner
android:id="#+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dip"
android:layout_marginRight="8dip"
android:layout_marginTop="10dip"
/>
<!-- Select Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dip"
android:text="#string/lblSubAcc" />
<!-- Spinner Dropdown -->
<Spinner
android:id="#+id/spinner2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:layout_marginLeft="8dip"
android:layout_marginRight="8dip"
/>
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Visit Day" />
<CheckBox
android:id="#+id/checkBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Saturday" />
<CheckBox
android:id="#+id/checkBox2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sunday" />
<CheckBox
android:id="#+id/checkBox3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Monday" />
<CheckBox
android:id="#+id/checkBox4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Tuesday" />
<CheckBox
android:id="#+id/checkBox5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Wednesday" />
<CheckBox
android:id="#+id/checkBox6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Thursday" />
<CheckBox
android:id="#+id/checkBox7"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Outlet is Closed" />
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Calling Frequency" />
<Spinner
android:id="#+id/spinner3"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/input_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Comments" />
<Button
android:id="#+id/btn_add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save" />
<!-- Add Button -->
</LinearLayout>
Mainactivity java file.
package aaa.qw.cv;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.database.DatabaseUtils;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
import android.support.v7.app.AppCompatActivity;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import java.util.ArrayList;
import java.util.Arrays;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.SimpleCursorAdapter;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.content.Intent;
import java.util.HashMap;
import java.util.List;
import android.view.View.OnClickListener;
import android.util.Log;
import android.widget.TextView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.EditText;
import java.util.LinkedList;
import android.view.inputmethod.InputMethodManager;
public class ok extends Activity {
Spinner s1,s2,s3;
Button btnAdd;
EditText inputLabel;
DatabaseHandler dbhndlr;
Cursor spinner1csr, spinner2csr;
SimpleCursorAdapter sca, sca2;
long spinner1_selected = 0;
CheckBox ck1,ck2,ck3,ck4,ck5,ck6,ck7;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner_ex4);
s1 = (Spinner)findViewById(R.id.spinner1);
s2 = (Spinner)findViewById(R.id.spinner2);
s3 = (Spinner)findViewById(R.id.spinner3);
btnAdd = (Button) findViewById(R.id.btn_add);
inputLabel = (EditText) findViewById(R.id.input_label);
dbhndlr = new DatabaseHandler(this);
ck1=(CheckBox) findViewById(R.id.checkBox);
ck2=(CheckBox)findViewById(R.id.checkBox2);
ck3=(CheckBox)findViewById(R.id.checkBox3);
ck4=(CheckBox)findViewById(R.id.checkBox4);
ck6=(CheckBox) findViewById(R.id.checkBox5);
ck7=(CheckBox)findViewById(R.id.checkBox6);
loadSpinnerData();
// Get Cursors for Spinners
spinner1csr = dbhndlr.getAllLabelsAsCursor();
//Setup Adapter for Spinner 1
sca = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,spinner1csr,
new String[]{DatabaseHandler.KEY_NAME},
new int[]{android.R.id.text1},
0
);
// Set the Adapters to the Spinners
s1.setAdapter(sca);
// Set Spinner1 OnSelectedItemListener
s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"You Selected: " + id + " - " +
spinner1csr.getString(
spinner1csr.getColumnIndex(DatabaseHandler.KEY_NAME)) +
" - " + spinner1csr.getString(spinner1csr.getColumnIndex(DatabaseHandler.KEY_ID))
,
Toast.LENGTH_SHORT).show();
spinner1_selected = id;
spinner2csr = dbhndlr.getByRowid(spinner1_selected);
sca2.swapCursor(spinner2csr);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//Steup Adapter for Spinner2
spinner2csr = dbhndlr.getByRowid(spinner1_selected);
sca2 = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
spinner2csr,
new String[]{DatabaseHandler.KEY_ID},
new int[]{android.R.id.text1},
0
);
s2.setAdapter(sca2);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String label = inputLabel.getText().toString();
if (label.trim().length() > 0) {
// database handler commeneted out, use dbhndlr instance instead
// inserting new label into database
dbhndlr.insertLabel(label);
// making input filed text to blank
inputLabel.setText("");
// Hiding the keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);
// loading spinner with newly added data
spinner1csr = dbhndlr.getAllLabelsAsCursor();
spinner2csr = dbhndlr.getByRowid(spinner1_selected);
sca.swapCursor(spinner1csr);
sca2.swapCursor(spinner2csr);
} else {
Toast.makeText(getApplicationContext(), "Please enter label name",
Toast.LENGTH_SHORT).show();
}
}
});
}
private void loadSpinnerData() {
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getAllLabels();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter1
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
s3.setAdapter(dataAdapter1);
}
#Override
public void onDestroy() {
spinner1csr.close();
spinner2csr.close();
super.onDestroy();
}
}
database java file.
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
// Database Version
public static final int DATABASE_VERSION = 1;
// Database Name
public static final String DATABASE_NAME = "spinnerExample";
// Labels table name
public static final String TABLE_LABELS = "labels"; //<<<< Made public
public static final String TABLE_LABELS1= "labels1";
public static final String TABLE_LABELS2= "labels2";
// Labels Table Columns names
public static final String KEY_ID = "id"; //<<<< Made public
public static final String KEY_NAME = "name"; //<<<< made public
public static final String KEY_ID1 = "id1"; //<<<< Made public
public static final String KEY_NAME1 = "name1";
public static final String KEY_1 = "number"; //<<<< Made public
public static final String KEY_2 = "outletname"; //<<<< made public
public static final String KEY_3 = "sunday"; //<<<< Made public
public static final String KEY_4 = "monday";
public static final String KEY_5 = "tuesday";
public static final String KEY_6 = "wednesday";
public static final String KEY_7 = "thursday";
public static final String KEY_8 = "saturday";
public static final String KEY_9 = "closed";
public static final String KEY_10 = "calling";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
// Category table create query
String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
+ KEY_ID + " TEXT," + KEY_NAME + " TEXT)";
String CREATE_CATEGORIES_TABLE1 = "CREATE TABLE " + TABLE_LABELS1 + "("
+ KEY_ID1+ " TEXT," + KEY_NAME1+ " TEXT)";
db.execSQL(CREATE_CATEGORIES_TABLE);
db.execSQL(CREATE_CATEGORIES_TABLE1);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS1);
// Create tables again
onCreate(db);
}
/**
* Inserting new lable into lables table
* */
public void insertLabel(String label){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, label);
// Inserting Row
db.insert(TABLE_LABELS, null, values);
db.close(); // Closing database connection
}
public void insertLabel1(String label){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME1, label);
// Inserting Row
db.insert(TABLE_LABELS1, null, values);
db.close(); // Closing database connection
}
public List<String> getAllLabels(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LABELS1;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
// Added for adding new data
public void insertlabel(String id, String label) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_ID,id);
cv.put(KEY_NAME,label);
db.insert(TABLE_LABELS,null,cv);
db.close();
}
// Added to get Cursor for Simple CursorAdapter
public Cursor getAllLabelsAsCursor() {
String[] columns = new String[]{"rowid AS _id, *"}; // Need _id column for SimpleCursorAdapter
return this.getWritableDatabase().query(TABLE_LABELS,columns,null,null,null,null,null);
}
public Cursor getAllLabelsExceptedSelected(long selected) {
String[] columns = new String[]{"rowid AS _id, *"};
String whereclause = "rowid <> ?";
String[] whereargs = new String[]{String.valueOf(selected)};
return this.getWritableDatabase().query(TABLE_LABELS,
columns,
whereclause,
whereargs,
null,
null,
null
);
}
public Cursor getByRowid(long id) {
String[] columns = new String[]{"rowid AS _id, *"};
return this.getWritableDatabase().query(
TABLE_LABELS,
columns,
"rowid=?",
new String[]{String.valueOf(id)},
null,null,null
);
}
}
issue is solved with
public void insertLabel(String message1, String message2,String message3,String message4,String message5,String message6,String message7,String message8,String message9,String message10) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_1, message1);
values.put(KEY_2, message2);
values.put(KEY_10,message10);
values.put(KEY_3,message3);
values.put(KEY_4,message4);
values.put(KEY_5,message5);
values.put(KEY_6,message6);
values.put(KEY_7,message7);
values.put(KEY_9,message9);
values.put(KEY_8,message8);
// Inserting Row
db.insert(TABLE_LABELS2, null, values);
db.close(); // Closing database connection
}
database
public void insertLabel(String message1, String message2,String message3,String message4,String message5,String message6,String message7,String message8,String message9,String message10){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_1, message1);
values.put(KEY_2, message2);
values.put(KEY_10,message10);
values.put(KEY_3,message3);
values.put(KEY_4,message4);
values.put(KEY_5,message5);
values.put(KEY_6,message6);
values.put(KEY_7,message7);
values.put(KEY_9,message9);
values.put(KEY_8,message8);
// Inserting Row
db.insert(TABLE_LABELS2, null, values);
db.close(); // Closing database connection
}
main
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//String label = inputLabel.getText().toString();
String SaveString="No";
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
String message1= ((Cursor) s1.getSelectedItem()).getString(2);
String message2= ((Cursor) s2.getSelectedItem()).getString(1);
String message = inputLabel.getText().toString();
// String message1 = s1.getSelectedItem().toString();
// String message2 = s2.getSelectedItem().toString();
String message10 = s3.getSelectedItem().toString();
String message4 = ck1.getText().toString();
String message5 = ck2.getText().toString();
String message6 = ck3.getText().toString();
String message7 = ck4.getText().toString();
String message9 = ck6.getText().toString();
String message3 = ck7.getText().toString();
String message8 = ck8.getText().toString();
if (ck1.isChecked())
{ message4 = ck1.getText().toString();
}
else
{ message4="No";
}
if (ck2.isChecked())
{ message5 = ck2.getText().toString();
}
else
{ message5="No";
}
if (ck3.isChecked())
{ message6 = ck3.getText().toString();
}
else
{ message6="No";
}
if (ck4.isChecked())
{ message7 = ck4.getText().toString();
}
else
{ message7="No";
}
if (ck6.isChecked())
{ message9 = ck6.getText().toString();
}
else
{ message9="No";
}
if (ck7.isChecked())
{ message3 = ck7.getText().toString();
}
else
{ message3="No";
}
if (ck8.isChecked())
{ message8 = ck8.getText().toString();
}
else
{ message8="No";
}
db.insertLabel(message1,message2,message5,message6,message7,message9,message3,message4,message8,message10);

How to convert a row of a sqLite db into an arrayList and then choose a random element of the list?

I am currently working on an app, the final goal of it is that you click a button and it will display a random challenge that is stored in the sqlLite DB.
I can't manage to take a random row of it, even with all the tutorials and the posts on StackOverflow talking about it, maybe my current level and knowledge are to small to make it work. Perhaps the fact that I use it in a Fragment can make it even harder.
Because I can't manage to take directly a random row in my DB, I thought about using an arrayList to store the string stored in the column "Gage" of all the rows of my db, and then take a random element of this arrayList.
So, if someone knows what is wrong, please help me.
Data Base Class
package com.thebatz.game20;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class PenanceDB extends SQLiteOpenHelper {
private static final int DATA_BASE_VERSION = 1;
private static final String TABLE_NAME = "Penance";
private static final String ID = "ID";
private static final String Gage = "GAGE";
private static final String DATABASE_NAME = "Penance.db";
public PenanceDB(Context context){
super(context, DATABASE_NAME, null, DATA_BASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase dbPen) {
dbPen.execSQL("create table " + TABLE_NAME+ "(ID INTEGER PRIMARY KEY AUTOINCREMENT, GAGE TEXT, TIME INTEGER)" );
}
#Override
public void onUpgrade(SQLiteDatabase dbPen, int oldVersion, int newVersion) {
dbPen.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
onCreate(dbPen);
}
public boolean insertPen(String gageNom) {
SQLiteDatabase dbPen = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Gage, gageNom);
long result = dbPen.insert(TABLE_NAME, null, contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getDataPen(){
SQLiteDatabase dbPen = this.getWritableDatabase();
Cursor res = dbPen.rawQuery("select * from " +TABLE_NAME, null);
return res;
}
public boolean penitenceUpdate(String id, String penitence) {
SQLiteDatabase dbPen = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(ID, id);
contentValues.put(Gage, penitence);
dbPen.update(TABLE_NAME, contentValues, "ID = ?", new String[] {id});
return true;
}
}
Fragment class
package com.thebatz.game20;
import android.database.Cursor;
import android.support.v7.app.AlertDialog;
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 java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.lang.String;
public class GameActivity extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_game, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final Button btnViewPen = (Button) getView().findViewById(R.id.btnGamePen);
final Button btnViewAw = (Button) getView().findViewById(R.id.btnGameAw);
final PenanceDB myPen = new PenanceDB(getActivity());
final AwardDB myAw = new AwardDB(getActivity());
final List<String> Penance = new ArrayList<>();
final List<String> Award = new ArrayList<>();
btnViewPen.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = myPen.getDataPen();
if(res.getCount() == 0){
showMessage("Erreur 404", "Base de données vide");
return;
}
//Putt sqlite data into an array list
while (res.moveToNext()) {
Penance.add(res.getString(res.getColumnIndex("Gage")));
}
//Take a randome one
int iD = new Random().nextInt(Penance.size());
String item = Penance.get(iD);
//call the methode to display it
showMessage("Gages: ", item);
}
}
);
btnViewAw.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = myAw.getDataRec();
if(res.getCount() == 0){
showMessage("Erreur 404", "Base de données vide");
return;
}
while (res.moveToNext()) {
Award.add(res.getString(res.getColumnIndex("Gage")));
}
int iD = new Random().nextInt(Award.size());
String item = Award.get(iD);
showMessage("Gages", item);
}
}
);
}
public void showMessage(String title, String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
}
XML file of the fragment
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.thebatz.game20.GameActivity">
<Button
android:id="#+id/btnGamePen"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="138dp"
android:background="#android:color/holo_red_dark"
android:text="#string/p_nitence"
app:layout_constraintHorizontal_bias="0.501"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btnGameAw"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:background="#android:color/holo_green_dark"
android:text="#string/r_compences"
android:textColorLink="#android:color/background_light"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btnGamePen"
app:layout_constraintVertical_bias="0.509" />
</android.support.constraint.ConstraintLayout>
How about creating the random number before executing the SQL command - Then when you use your SELECT statement you could include the random number variable as the ID to query?

Failed to retrieve data in Search View in android

I'm trying to do a simple retrieval of data from SQLite Database to the SearchView.
My problem is the SearchView is not populated with respect to the data stored in the database, although it always shows the green signal of
successfully created the database
Below is the code.
fragment_search.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#E6E6E6"
android:orientation="vertical" >
<View
android:id="#+id/view1"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_alignParentTop="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:background="#FFFFFF" />
<SearchView
android:id="#+id/searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp" >
</SearchView>
<ListView
android:id="#+id/listview_search"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/searchView"
android:layout_centerHorizontal="true"
android:divider="#E6E6E6"
android:dividerHeight="5dp" />
<LinearLayout
android:id="#+id/rightLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/view1"
android:layout_alignTop="#+id/view1"
android:orientation="vertical"
android:paddingTop="25dp" >
</LinearLayout>
</RelativeLayout>
Search_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/hotelLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TableRow
android:id="#+id/section_search"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<GridLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:columnCount="2" >
<ImageView
android:id="#+id/hotel_image"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="left"
android:src="#drawable/aaa" />
<EditText
android:id="#+id/hotel_name"
android:layout_width="209dp"
android:layout_height="56dp"
android:layout_gravity="fill_horizontal" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/hotel_city"
android:layout_width="96dp"
android:layout_column="1"
android:layout_gravity="left|bottom"
android:layout_row="0"
android:ems="10" />
<EditText
android:id="#+id/hotel_country"
android:layout_width="106dp"
android:layout_column="1"
android:layout_gravity="right|bottom"
android:layout_row="0"
android:ems="10" />
</GridLayout>
</TableRow>
</LinearLayout>
</RelativeLayout>
TableData.java
package com.mytry.test;
import android.provider.BaseColumns;
public class TableData
{
public TableData()
{
}
public static abstract class TableInfo implements BaseColumns
{
public static final String DATABASE_NAME = "tourDguide";
public static final String TABLE_NAME = "Hotels";
public static final String HOTEL_ID = "id";
public static final String HOTEL_NAME = "hotel_name";
public static final String HOTEL_ADDRESS = "hotel_address";
public static final String HOTEL_CITY = "hotel_city";
public static final String HOTEL_COUNTRY = "hotel_country";
public static final String HOTEL_POSTAL = "postal_code";
}
}
DataBaseHandler.java
package com.mytry.test;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.mytry.test.TableData.TableInfo;
public class DataHandler
{
public static final int DATABASE_VERSION = 1;
SQLiteDatabase db;
DataBaseHelper dbhelper;
Context ctx;
private static class DataBaseHelper extends SQLiteOpenHelper
{
public String CREATE_QUERY = "CREATE TABLE "+TableInfo.TABLE_NAME+"("+TableInfo.HOTEL_ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"+TableInfo.HOTEL_NAME+" VARCHAR,"+TableInfo.HOTEL_ADDRESS+" VARCHAR,"+TableInfo.HOTEL_CITY+" VARCHAR,"+TableInfo.HOTEL_COUNTRY+" VARCHAR,"+TableInfo.HOTEL_POSTAL+" INT );";
public DataBaseHelper(Context ctx) {
super(ctx,TableInfo.DATABASE_NAME, null, DATABASE_VERSION);
Log.d("Database Operations", "Successfully Created Database");
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
try{
db.execSQL(CREATE_QUERY);
Log.d("Database Operations", "Successfully Created Table");
}
catch(SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("Drop table if exists "+TableInfo.TABLE_NAME);
onCreate(db);
}
}
public DataHandler(Context ctx) {
this.ctx = ctx;
dbhelper = new DataBaseHelper(ctx);
// TODO Auto-generated constructor stub
}
public DataHandler open()
{
dbhelper = new DataBaseHelper(ctx);
db = dbhelper.getReadableDatabase();
return this;
}
public void close()
{
dbhelper.close();
}
public Cursor searchHotels(String inputText) throws SQLException
{
String query = "Select "+TableInfo.HOTEL_ID+" as _id,"+TableInfo.HOTEL_NAME+","+TableInfo.HOTEL_ADDRESS+","+TableInfo.HOTEL_CITY+","+TableInfo.HOTEL_COUNTRY+","+TableInfo.HOTEL_POSTAL+" from "+TableInfo.TABLE_NAME+" where "+TableInfo.HOTEL_NAME+" LIKE '" + inputText + "';";
Log.d("table operations","Successfully transferred query");
Cursor cr = db.rawQuery(query, null);
if(cr!=null)
{
cr.moveToFirst();
}
return cr;
}
}
SeachViewActivity.java
package com.mytry.test;
import com.mytry.test.TableData.TableInfo;
import android.R.anim;
import android.app.Activity;
import android.app.DownloadManager.Query;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class SearchViewActivity extends Activity implements SearchView.OnQueryTextListener,SearchView.OnCloseListener
{
private ListView list;
private SearchView search;
private DataHandler dbHandler;
private TextView name,city,country;
private EditText edit;
Context ctx=this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_search);
search = (SearchView) this.findViewById(R.id.searchView);
list = (ListView) this.findViewById(R.id.listview_search);
name = (TextView)this.findViewById(R.id.hotel_name);
city = (TextView)this.findViewById(R.id.hotel_city);
country = (TextView)this.findViewById(R.id.hotel_country);
search.setIconifiedByDefault(false);
search.setOnQueryTextListener(this);
search.setOnCloseListener(this);
dbHandler = new DataHandler(getBaseContext());
dbHandler.open();
}
public boolean onQueryTextSubmit(String query)
{
showResults(query + "*");
return false;
}
public boolean onQueryTextChange(String newText)
{
showResults(newText + "*");
return false;
}
public boolean onClose()
{
showResults("");
return false;
}
private void showResults(String query)
{
Cursor cr = dbHandler.searchHotels((query!=null?query.toString(): "####"));
if(cr==null)
{
}
else
{
String[] from = new String[]
{TableInfo.HOTEL_NAME,TableInfo.HOTEL_ADDRESS,TableInfo.HOTEL_CITY,TableInfo.HOTEL_COUNTRY,TableInfo.HOTEL_POSTAL};
int[] to = new int[]{R.id.hotel_name,R.id.hotel_city,R.id.hotel_country};
SimpleCursorAdapter hotels = new SimpleCursorAdapter(this,R.layout.search_list, cr, from, to);
list.setAdapter(hotels);
list.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Cursor cr = (Cursor)list.getItemAtPosition(position);
String hotel_name = cr.getString(cr.getColumnIndexOrThrow("hotel_name"));
String hotel_city = cr.getString(cr.getColumnIndexOrThrow("hotel_city"));
String hotel_country = cr.getString(cr.getColumnIndexOrThrow("hotel_country"));
LinearLayout hotelLayout = (LinearLayout)findViewById(R.id.hotelLayout);
if(hotelLayout == null){
//Inflate the Customer Information View
LinearLayout leftLayout = (LinearLayout)findViewById(R.id.rightLayout);
View hotelInfo = getLayoutInflater().inflate(R.layout.search_list, leftLayout, false);
leftLayout.addView(hotelInfo);
}
name.setText(hotel_name);
city.setText(hotel_city);
country.setText(hotel_country);
search.setQuery("", true);
}
});
}
}
}

Fetching values from Cursor but Application Crashes

I am trying to fetch values from the database when I click on the view button which is another activity for navigation when I click on the view all button the CustodianViewActivity is triggered to display all the values from the database on a list view but in my case the application crashes every time I try to view the data from the database. Am not sure where I am going wrong.
Database Class
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;
public class DBHandler extends SQLiteOpenHelper {
private static DBHandler instance;
// Database Name
public static final String DATABASE_NAME ="AssetDB.db";
//Database version
public static final int Databasevr = 1;
//Custodian Table Name
public static final String TABLE_CUSTODIAN = " Custodian";
// Columbs in the Custodian Table
public static final String CUSTODIAN_ID = "_CustID";
public static final String CUSTODIAN_NAME = "CustName";
public static final String CUSTODIAN_DESIGNATION = "CustDesign";
public static final String CUSTODIAN_DEPARTMENT = "CustDepart";private static final String CREATE_TABLE_CUSTODIAN = "CREATE TABLE" + TABLE_CUSTODIAN + "("
+ CUSTODIAN_ID + " INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,"
+ CUSTODIAN_NAME + " TEXT NOT NULL,"
+ CUSTODIAN_DESIGNATION + " TEXT NOT NULL,"
+ CUSTODIAN_DEPARTMENT + " TEXT NOT NULL" + ");";
// constructor passing parameter passing Database name and Database version
public DBHandler(Context ct)
{
super(ct, DATABASE_NAME, null, Databasevr);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
// Creating the tables
db.execSQL(CREATE_TABLE_CUSTODIAN);
db.execSQL(CREATE_TABLE_ASSET);
Log.d("Tables","Tables have been created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// dropping the tables
db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_CUSTODIAN );
db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_ASSET);
// recreate the tables
onCreate(db);
}
public Cursor getAllCustodians(){
try {
SQLiteDatabase db_database = getWritableDatabase();
Cursor cursor = db_database.rawQuery("SELECT * FROM" + TABLE_CUSTODIAN, null);
if (cursor != null) {
return cursor;
} else {
return null;
}
}
catch(Exception e)
{
return null;
}
}}
CustodianViewActivity
package com.example.nfcams;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class CustodianViewActivity extends Activity {
ListView CustodianListview;
DBHandler db_database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custodian_view);
db_database = new DBHandler(getApplicationContext());
CustodianListview = (ListView) findViewById(R.id.custodianlistView);
new Handler().post(new Runnable() {
#Override
public void run() {
populateCustoListView();
}
});
}
#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_custodian_view, 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);
}
private void populateCustoListView()
{
Cursor c = db_database.getAllCustodians();
CustodianListview.setAdapter(new CustodiansListAdapter(this,c));
}
private class CustodiansListAdapter extends CursorAdapter
{
private Cursor cursor;
public CustodiansListAdapter(Context context, Cursor cur) {
super(context, cur);
cursor = cur;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView custID = (TextView) view.findViewById(R.id.Custodianid_view);
int CustodID = cursor.getInt(cursor.getColumnIndex("_CustID"));
custID.setText(String.valueOf(CustodID));
TextView name = (TextView) view.findViewById(R.id.Custodianname_view);
String Custname = cursor.getString(cursor.getColumnIndex("CustName"));
name.setText(Custname);
TextView Designation = (TextView) view.findViewById(R.id.CustodianDesignation_view);
String CustDesignation = cursor.getString(cursor.getColumnIndex("CustDesign"));
Designation.setText(CustDesignation);
TextView Department = (TextView) view.findViewById(R.id.CustodianDepartment_view);
String CustDepartment = cursor.getString(cursor.getColumnIndex("CustDepart"));
Department.setText(CustDepartment);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View retView = inflater.inflate(R.layout.custodianrow_views, parent, false);
bindView(retView,context,cursor);
return retView;
}
}
}
Custodianview Activity layout
<RelativeLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.nfcams.CustodianViewActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/custodianlistView"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
List view layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/list_item_bg"
android:descendantFocusability="blocksDescendants" >
<RelativeLayout
android:id="#+id/layout_item"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/Custodianname_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="6dp" />
<TextView
android:id="#+id/Custodianid_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/Custodianname_view"
android:padding="6dp" />
<TextView
android:id="#+id/CustodianDesignation_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Custodianid_view"
android:padding="6dp" />
<TextView
android:id="#+id/CustodianDepartment_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/CustodianDesignation_view"
android:padding="6dp" />
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#+id/layout_item"
android:background="#color/view_divider_color" />
</RelativeLayout>
Error Log
05-30 09:42:16.471 1334-1334/com.example.nfcams E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.nfcams, PID: 1334
java.lang.IllegalArgumentException: column '_id' does not exist
at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:303)
at android.widget.CursorAdapter.init(CursorAdapter.java:172)
at android.widget.CursorAdapter.<init>(CursorAdapter.java:120)
at com.example.nfcams.CustodianViewActivity$CustodiansListAdapter.<init>(CustodianViewActivity.java:95)
at com.example.nfcams.CustodianViewActivity.populateCustoListView(CustodianViewActivity.java:84)
at com.example.nfcams.CustodianViewActivity.access$000(CustodianViewActivity.java:17)
at com.example.nfcams.CustodianViewActivity$1.run(CustodianViewActivity.java:42)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
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:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)

Categories

Resources