dimanche 11 janvier 2015

Trying to make a sqlite database search app

I'm new to Android and have been working on this app for a while. Pretty much I'm loading initial values into the sqlite database with 3 columns: _id, product, and ingredients. I have an EditText box for the user to search the products to see if they have a certain ingredient in it. A listview is then printed out showing the products with these ingredients. I'm having some overall trouble with this code, specifically when I run it, it shows "Could not read row 0 col 1" from logcat.


However I also need help making sure that the rest of the code will be functional after fixing this? I've been looking at other StackOverflow hours and they've helped me get this far so I was very much appreciated. However I'm very stuck at this point and need to ask directly. Any help would be appreciated thank you!


Logcat:



01-11 15:34:11.674: D/AbsListView(19090): Get MotionRecognitionManager
01-11 15:34:11.864: E/SpannableStringBuilder(19090): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
01-11 15:34:11.864: E/SpannableStringBuilder(19090): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
01-11 15:34:12.625: E/CursorWindow(19090): Failed to read row 0, column 1 from a CursorWindow which has 3 rows, 1 columns.
01-11 15:34:12.625: D/AndroidRuntime(19090): Shutting down VM
01-11 15:34:12.625: W/dalvikvm(19090): threadid=1: thread exiting with uncaught exception (group=0x416f1da0)
01-11 15:34:12.625: E/AndroidRuntime(19090): FATAL EXCEPTION: main
01-11 15:34:12.625: E/AndroidRuntime(19090): Process: com.lapetit, PID: 19090
01-11 15:34:12.625: E/AndroidRuntime(19090): java.lang.IllegalStateException: Couldn't read row 0, col 1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
01-11 15:34:12.625: E/AndroidRuntime(19090): at android.database.CursorWindow.nativeGetString(Native Method)
01-11 15:34:12.625: E/AndroidRuntime(19090): at android.database.CursorWindow.getString(CursorWindow.java:439)
01-11 15:34:12.625: E/AndroidRuntime(19090): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
01-11 15:34:12.625: E/AndroidRuntime(19090): at com.lapetit.ProductsDataSource.cursorToProduct(ProductsDataSource.java:108)
01-11 15:34:12.625: E/AndroidRuntime(19090): at com.lapetit.ProductsDataSource.getSearchedProducts(ProductsDataSource.java:91)
01-11 15:34:12.625: E/AndroidRuntime(19090): at com.lapetit.WithActivity$1.onClick(WithActivity.java:49)
01-11 15:34:12.625: E/AndroidRuntime(19090): at android.view.View.performClick(View.java:4654)
01-11 15:34:12.625: E/AndroidRuntime(19090): at android.view.View$PerformClick.run(View.java:19438)
01-11 15:34:12.625: E/AndroidRuntime(19090): at android.os.Handler.handleCallback(Handler.java:733)
01-11 15:34:12.625: E/AndroidRuntime(19090): at android.os.Handler.dispatchMessage(Handler.java:95)
01-11 15:34:12.625: E/AndroidRuntime(19090): at android.os.Looper.loop(Looper.java:146)
01-11 15:34:12.625: E/AndroidRuntime(19090): at android.app.ActivityThread.main(ActivityThread.java:5487)
01-11 15:34:12.625: E/AndroidRuntime(19090): at java.lang.reflect.Method.invokeNative(Native Method)
01-11 15:34:12.625: E/AndroidRuntime(19090): at java.lang.reflect.Method.invoke(Method.java:515)
01-11 15:34:12.625: E/AndroidRuntime(19090): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
01-11 15:34:12.625: E/AndroidRuntime(19090): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)


MySQLiteHelper.java



package com.lapetit;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MySQLiteHelper extends SQLiteOpenHelper {

public static final String TABLE_PRODUCTS = "products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PRODUCT = "product";
public static final String COLUMN_INGREDIENTS = "ingredients";
private SQLiteDatabase database;

private static final String DATABASE_NAME = "products.db";
private static final int DATABASE_VERSION = 1;

// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_PRODUCTS + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_PRODUCT
+ " text not null, " + COLUMN_INGREDIENTS + " text not null);";

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

@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);

Cursor check = database.rawQuery("select * from products",null);

//First Time we open Database, add default Values
if ( check.getCount() < 1 )
{

database.execSQL("insert into " + TABLE_PRODUCTS + "(" + COLUMN_ID + ","
+ COLUMN_PRODUCT + "," + COLUMN_INGREDIENTS + ")" + "values(1,'Le Mieux Retinol Serum', 'Apples,Bananas,Carrots')");

database.execSQL("insert into " + TABLE_PRODUCTS + "(" + COLUMN_ID + ","
+ COLUMN_PRODUCT + "," + COLUMN_INGREDIENTS + ")" + "values(2,'Le Mieux Essence Toner', 'Apricots, Beets, Cats')");

database.execSQL("insert into " + TABLE_PRODUCTS + "(" + COLUMN_ID + ","
+ COLUMN_PRODUCT + "," + COLUMN_INGREDIENTS + ")" + "values(3,'Le Mieux Body Wash', 'Alcohol, Marijuana, Meth')");

}
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
onCreate(db);
}


}


Products.java



package com.lapetit;

public class Products {
private long id;
private String product;
private String ingredient;

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

public String getProduct() {
return product;
}

public void setProduct(String product) {
this.product = product;
}

public String getIngredients() {
return product;
}

public void setIngredients(String ingredient) {
this.ingredient = ingredient;
}

// Will be used by the ArrayAdapter in the ListView
@Override
public String toString() {
return product;
}

}


ProductsDataSource.java



package com.lapetit;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class ProductsDataSource {

// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_PRODUCT,
MySQLiteHelper.COLUMN_INGREDIENTS};

public ProductsDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}

public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}

public void close() {
dbHelper.close();
}


public Products createProduct(String product) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_PRODUCT, product);
long insertId = database.insert(MySQLiteHelper.TABLE_PRODUCTS, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_PRODUCTS,
allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
Products newProduct = cursorToProduct(cursor);
cursor.close();
return newProduct;
}


public void deleteProduct(Products product) {
long id = product.getId();
System.out.println("Product deleted with id: " + id);
database.delete(MySQLiteHelper.TABLE_PRODUCTS, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}




public List<Products> getAllProducts() {
List<Products> products = new ArrayList<Products>();

Cursor cursor = database.query(MySQLiteHelper.TABLE_PRODUCTS,
allColumns, null, null, null, null, null);

cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Products product = cursorToProduct(cursor);
products.add(product);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return products;
}



//Search queries
public List<Products> getSearchedProducts(String search) {
List<Products> products = new ArrayList<Products>();

//Cursor cursor = database.query(MySQLiteHelper.TABLE_PRODUCTS, new String[] {MySQLiteHelper.COLUMN_PRODUCT},
// MySQLiteHelper.COLUMN_INGREDIENTS + " like ?" + new String[] {"%" + search + "%" }, null, null, null, null);

String[] args = new String[1];
args[0] = "%"+search+"%";
Cursor cursor = database.rawQuery("SELECT product FROM products WHERE ingredients like ?", args);

cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Products product = cursorToProduct(cursor);
products.add(product);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();


return products;
}




private Products cursorToProduct(Cursor cursor) {
Products product = new Products();
product.setId(cursor.getLong(0));
product.setProduct(cursor.getString(1));
return product;
}

public Products createIngredient(String ingredient) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_INGREDIENTS, ingredient);
long insertId = database.insert(MySQLiteHelper.TABLE_PRODUCTS, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_PRODUCTS,
allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
Products newIngredient = cursorToProduct(cursor);
cursor.close();
return newIngredient;
}

public void deleteIngredient(Products ingredient) {
long id = ingredient.getId();
System.out.println("Product deleted with id: " + id);
database.delete(MySQLiteHelper.TABLE_PRODUCTS, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}
}


WithActivity.java



package com.lapetit;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.EditText;
import android.view.View.OnClickListener;
import android.widget.ImageView;


public class WithActivity extends ListActivity {
private ProductsDataSource datasource;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.with);

// Capture our button from layout
ImageView searchbutton = (ImageView)findViewById(R.id.imageButton1);
//Register the onClick listener with the implementation above

datasource = new ProductsDataSource(this);
datasource.open();


List<Products> values = new ArrayList<Products>();


searchbutton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
EditText inputSearch = (EditText) findViewById(R.id.text);
String stringinput = (String)inputSearch.getText().toString();
List<Products> values = datasource.getSearchedProducts(stringinput);
}
});

ArrayAdapter<Products> adapter = new ArrayAdapter<Products>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}

@Override
protected void onResume() {
datasource.open();
super.onResume();
}

@Override
protected void onPause() {
datasource.close();
super.onPause();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.splash, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}


with.xml



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://ift.tt/nIICcg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.26"
android:background="@android:color/darker_gray" >

<EditText
android:id="@+id/text"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:hint="Search products.."
android:inputType="text" />

<ImageButton
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:src="@drawable/search" />

</RelativeLayout>

<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="400dp" />

</LinearLayout>

Aucun commentaire:

Enregistrer un commentaire