How to validate and add new users in SQLite database? - java

I have created a database and want to register new user in case of absence of that user in database. So, firstly, app checks whether desired username and email exitsts in database or not. If not, it puts new user data into database. I have written code but it goes down when I try to register new user.
Here is my
MainActivity.java
public class MainActivity extends AppCompatActivity {
DBHelper dbHelper;
EditText email, username, password, passwordconf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
getSupportActionBar().hide();
dbHelper = new DBHelper(this);
}
public void clickButton2(View view) throws Exception {
SQLiteDatabase database = dbHelper.getWritableDatabase();
email = (EditText) findViewById(R.id.email);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
String userName = username.getText().toString();
String userEmail = email.getText().toString();
if (!ValidateUser(userName, userEmail)) {
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.KEY_LOGIN,
username.getText().toString());
contentValues.put(DBHelper.KEY_EMAIL,
email.getText().toString());
contentValues.put(DBHelper.KEY_PASSWORD,
password.getText().toString());
database.insert(DBHelper.TABLE_NAME, null, contentValues);
Toast.makeText(this, "you have registered successfully!",
Toast.LENGTH_SHORT).show();
Intent intent2 = new Intent(Main2Activity.this,
Main3Activity.class);
startActivity(intent2);
}
}
public boolean ValidateUser(String userName, String userEmail) {
SQLiteDatabase database = dbHelper.getWritableDatabase();
Cursor cursor = database.query(DBHelper.TABLE_NAME, null,
DBHelper.KEY_LOGIN + "=? OR " + DBHelper.KEY_EMAIL + "=?",
new String[]{userName, userEmail},
null, null, null);
int i = cursor.getCount();
database.close();
cursor.close();
if(i>0){
return true;
}else{
return false;
}
}
}
My Database Helper DBHelper.java
public class DBHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "Login_register";
public static final String TABLE_NAME = "users";
public static final String KEY_LOGIN = "login";
public static final String KEY_PASSWORD = "passsword";
public static final String KEY_EMAIL = "email";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "(" + KEY_LOGIN + " TEXT," +
KEY_PASSWORD + " TEXT" + KEY_EMAIL + " TEXT"+")");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
My layout XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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.rauf.myapplication.Main2Activity"
android:background="#drawable/bii3">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:layout_editor_absoluteY="8dp"
tools:layout_editor_absoluteX="8dp"
android:paddingLeft="60dp"
android:paddingRight="58dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="600dp"
android:layout_weight="2"
android:gravity="center"
android:orientation="vertical"
android:paddingTop="42dp">
<ImageView
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_gravity="center"
android:src="#drawable/kamera" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:layout_weight="1"
android:paddingTop="35dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_gravity="center"
android:src="#drawable/message" />
<EditText
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:background="#00000000"
android:hint="email address"
android:layout_marginLeft="15dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#4a5a71">
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp">
<ImageView
android:id="#+id/log"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_gravity="center"
android:src="#drawable/usrusr"/>
<EditText
android:id="#+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:background="#00000000"
android:hint="username"
android:layout_marginLeft="15dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#4a5a71"></LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp">
<ImageView
android:id="#+id/red"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_gravity="center"
android:src="#drawable/pswrd"/>
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:background="#00000000"
android:hint="password"
android:layout_marginLeft="15dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#4a5a71"></LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp">
<ImageView
android:id="#+id/red2"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_gravity="center"
android:src="#drawable/pswrd"/>
<EditText
android:id="#+id/passwordconf"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:background="#00000000"
android:hint="password confirm"
android:layout_marginLeft="15dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#4a5a71">
</LinearLayout>
</LinearLayout>
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/button_background2"
android:text="SIGN UP"
android:onClick="clickButton2"
android:clickable="true"
android:layout_marginBottom="20dp"
android:textColor="#ffffff"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center"
android:onClick="clickFunction2"
android:layout_marginBottom="10dp"
android:text="Already have an Account ?"
android:textColor="#000000" />
</LinearLayout>
</LinearLayout>

Issue 1
You have omitted the comma that separates the KEY_PASSWORD and KEY_EMAIL columns in the CREATE TABLE sql.
Thus you are effectively saying CREATE TABLE users(login TEXT,passsword TEXTemail TEXT)
That is the table is created with a Column named login, with a type of TEXT and a column named password with a type of Textemail TEXT and importantly there is no column named email.
Thus any reference to column email will then result in that column not being found in the table.
To fix this issue :-
db.execSQL("CREATE TABLE " + TABLE_NAME + "(" + KEY_LOGIN + " TEXT," +
KEY_PASSWORD + " TEXT" + KEY_EMAIL + " TEXT"+")");
should be :-
db.execSQL("CREATE TABLE " + TABLE_NAME + "(" + KEY_LOGIN + " TEXT," +
KEY_PASSWORD + " TEXT," + KEY_EMAIL + " TEXT"+")");
Note! You should do one of the following before rerunning the App after making the above change:-
Delete the App's Data (via settings).
Uninstall the App (via settings).
Increase the Database Version number (i.e. change public static final int DATABASE_VERSION = 1; to public static final int DATABASE_VERSION = 2;)
Issue 2
In the clickButton2 method you get a writeable SQLIteDatabase instance via SQLiteDatabase database = dbHelper.getWritableDatabase();
You then invoke the ValidateUser and then subsequently try to insert a row using the same SQLiteDatabase instance.
However as the ValidateUser method closes the database, you will get an exception java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase:
You can easily fix this by one of the following :-
removing the database.close() line from the ValidateUser method
create/open another instance of the SQLiteDatabase before the insert e.g add a line before the insert such as database = dbHelper.getWritableDatabase();
Issue 3
If a user already exists and is thus validated they will remain in the MainActivity.
You will need to decide/determine the logic to be used to fix this issue.

Related

ERROR Android Studio SQLite table "inventory" has no column named "quantity"

I know its simple and I am just new to SQLite and Android Studio, but I am trying to create a database table inventory each item having an ID, item name, and quantity. Then view that database table in RecyclerView. Right now I am getting the error message:
E/SQLiteDatabase: Error inserting item=Apples _id=1 quantity=5
android.database.sqlite.SQLiteException: table inventory has no column named quantity
(code 1 SQLITE_ERROR): , while compiling: INSERT INTO inventory(item,_id,quantity) VALUES
(?,?,?)
Here is my current code:
IventoryDB.java
private static final class InventoryTable {
private static final String TABLE = "inventory";
private static final String COL_ID = "_id";
private static final String COL_ITEM = "item";
private static final String COL_QTY = "quantity";
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + InventoryTable.TABLE + " (" +
InventoryTable.COL_ID + " integer primary key autoincrement, " +
InventoryTable.COL_ITEM + " text, " +
InventoryTable.COL_QTY + "text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
db.execSQL("drop table if exists " + InventoryDB.InventoryTable.TABLE);
onCreate(db);
}
public void addItem(int id, String item, String qty) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(InventoryDB.InventoryTable.COL_ID, id);
values.put(InventoryDB.InventoryTable.COL_ITEM, item);
values.put(InventoryDB.InventoryTable.COL_QTY, qty);
db.insert(InventoryDB.InventoryTable.TABLE, null, values);
}
Inventory.java
private AlertDialog.Builder dialogBuilder;
private AlertDialog dialog;
private InventoryDB DB;
private int id;
public void addItem(View view) {
createNewAddItemDialog();
}
public void createNewAddItemDialog(){
dialogBuilder = new AlertDialog.Builder(this);
final View addItemPopupView = getLayoutInflater().inflate(R.layout.popup_additem, null);
addItemName = (EditText) addItemPopupView.findViewById(R.id.additempopup_itemname);
addItemQuantity = (EditText)addItemPopupView.findViewById(R.id.additempopup_itemquantity);
addItemBtn = (Button) addItemPopupView.findViewById(R.id.additempopup_add);
cancelAddBtn = (Button) addItemPopupView.findViewById(R.id.additempopup_cancel);
dialogBuilder.setView(addItemPopupView);
dialog = dialogBuilder.create();
dialog.show();
addItemBtn.setOnClickListener(v -> {
String itemName = addItemName.getText().toString();
String itemQuantity = addItemQuantity.getText().toString();
if (itemName.equals("") || itemQuantity.equals("")) {
//addError.setText("Please ensure both fields are filled out!");
} else {
Boolean itemExists = DB.checkItemExists(itemName);
if (itemExists){
//addError.setText("Item already exists!");
} else {
DB.addItem(id, itemName, itemQuantity);
dialog.dismiss();
id += 1;
}
}
});
cancelAddBtn.setOnClickListener(v -> dialog.dismiss());
}
popup_additem.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Item"
android:textSize="25dp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.25" />
<EditText
android:id="#+id/additempopup_itemname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Item Name"
android:inputType="text"
android:minHeight="48dp"
android:text=""
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.361" />
<EditText
android:id="#+id/additempopup_itemquantity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Item Quantity"
android:inputType="number"
android:minHeight="48dp"
android:text=""
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/additempopup_itemname"
app:layout_constraintVertical_bias="0.066" />
<Button
android:id="#+id/additempopup_add"
android:layout_width="150dp"
android:layout_height="50dp"
android:text="Add"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.8"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/additempopup_itemquantity"
app:layout_constraintVertical_bias="0.105" />
<Button
android:id="#+id/additempopup_cancel"
android:layout_width="150dp"
android:layout_height="50dp"
android:text="Cancel"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/additempopup_add"
app:layout_constraintHorizontal_bias="0.8"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/additempopup_itemquantity"
app:layout_constraintVertical_bias="0.105" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is a long shot, but I think that you're missing a blank space in the last sentence of the method onCreate(SQLiteDatabase db) ... it seems that you're creating a column named: quantitytext instead of quantity text ...

How to store images in SQLite and also how I can export input text and image in any tabular format?

1) Please help me out to store image submitted by button to SQLite.
2) How can I implement export function in my app so that all the input text and images stored in SQLite can be exported in any format but in tabular way so that exported file can be used to retrieve data again.
DatabaseHelper.java
package com.example.himanshu.instrumentalinformationcollector;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_NAME = "instruments.db";
private static final String TABLE_NAME = "instrument_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "LOCATION";
public static final String COL_4 = "INFORMATION";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String CREATE_TABLE="CREATE TABLE " + DatabaseHelper.TABLE_NAME + " (" +
DatabaseHelper.COL_1 + " INTEGER,"
+ DatabaseHelper.COL_2 + " TEXT,"
+ DatabaseHelper.COL_3 + " TEXT,"
+ DatabaseHelper.COL_4 + " TEXT);";
sqLiteDatabase.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " +DatabaseHelper.TABLE_NAME);
onCreate(sqLiteDatabase);
}
public boolean insertData(Integer ID, String name, String location, String information){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.COL_1,ID);
contentValues.put(DatabaseHelper.COL_2,name);
contentValues.put(DatabaseHelper.COL_3,location);
contentValues.put(DatabaseHelper.COL_4,information);
sqLiteDatabase.insert(DatabaseHelper.TABLE_NAME,null,contentValues);
return true;
}
}
MainActivity.java
package com.example.himanshu.instrumentalinformationcollector;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.FileDescriptor;
import java.io.IOException;
public class MainActivity extends AppCompatActivity{
private static int RESULT_LOAD_IMAGE = 1;
DatabaseHelper myDB;
EditText editMessage,editMessage1,editMessage2,editMessage3;
Button submitData;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonLoadImage = (Button)findViewById(R.id.imgButton);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
myDB = new DatabaseHelper(this);
editMessage=(EditText)findViewById(R.id.editText);
editMessage1=(EditText)findViewById(R.id.editText1);
editMessage2=(EditText)findViewById(R.id.editText2);
editMessage3=(EditText)findViewById(R.id.editText3);
submitData=(Button)findViewById(R.id.submit);
AddData();
}
public void AddData(){
submitData.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
boolean isInserted = myDB.insertData(Integer.valueOf(editMessage.getText().toString()),editMessage1.getText().toString(),editMessage2.getText().toString(),editMessage3.getText().toString());
if(isInserted == true)
Toast.makeText(MainActivity.this,"Data Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not Inserted",Toast.LENGTH_LONG).show();
}
}
);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.img);
Bitmap bmp = null;
try {
bmp = getBitmapFromUri(selectedImage);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
imageView.setImageBitmap(bmp);
}
}
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.himanshu.instrumentalinformationcollector.MainActivity">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_alignParentLeft="true"
android:layout_marginTop="30dp"
android:layout_marginLeft="16sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ID"
android:id="#+id/textView"
android:textColor="#android:color/black"
/>
<ImageView
android:layout_alignParentRight="true"
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/img"
android:background="#drawable/gray"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
/>
<Button
android:layout_alignParentRight="true"
android:layout_below="#id/img"
android:layout_marginRight="10dp"
android:id="#+id/imgButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:text="Upload"
android:textSize="16sp"
/>
<EditText
android:layout_marginTop="15dp"
android:id="#+id/editText"
android:layout_toRightOf="#id/textView"
android:layout_toLeftOf="#id/imgButton"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginLeft="45sp"
android:layout_marginRight="30sp"
android:hint="Please enter here"
android:maxLength="6"
android:textSize="16sp"
android:inputType="number"
/>
<TextView
android:layout_alignParentLeft="true"
android:layout_below="#id/textView"
android:layout_marginTop="50dp"
android:layout_marginLeft="16sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="16sp"
android:id="#+id/textView1"
android:textColor="#android:color/black"
/>
<EditText
android:id="#+id/editText1"
android:layout_marginTop="30dp"
android:layout_below="#id/editText"
android:layout_toRightOf="#id/textView1"
android:layout_toLeftOf="#id/imgButton"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginLeft="16sp"
android:hint="Full Name"
android:textSize="16sp"
android:inputType="textCapWords"
/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:layout_marginTop="5dp"
android:layout_marginLeft="16sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Location"
android:textSize="16sp"
android:id="#+id/textView3"
android:textColor="#android:color/black"
/>
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Please enter here"
android:textSize="16sp"
android:inputType="textCapSentences"
android:layout_weight="1"
/>
</LinearLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp">
<TextView
android:layout_marginTop="16dp"
android:layout_marginLeft="16sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Information"
android:textSize="16sp"
android:id="#+id/textView2"
android:textColor="#android:color/black"
/>
<EditText
android:layout_alignParentLeft="true"
android:layout_toRightOf="#id/textView2"
android:layout_below="#id/textView2"
android:layout_marginTop="5dp"
android:layout_marginLeft="16sp"
android:id="#+id/editText3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine|textCapSentences"
android:gravity="top"
android:hint="Describe briefly"
android:textSize="16sp"
>
</EditText>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="#+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_weight="1"
android:layout_marginRight="16dp"
android:layout_marginLeft="16dp"
/>
<Button
android:id="#+id/export"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Export"
android:layout_weight="1"
android:layout_marginRight="16dp"
android:layout_marginLeft="16dp"/>
</LinearLayout>
</LinearLayout>
The answer to your question is lengthy - and will require you to make many changes.
Saving Images:
If you want to save the images, you will need to convert the image to a byte array
A more feasible approach, is to save the image as a File within your app's internal storage, add a column to your database which saves the name of the image in a common directory "s8u903wmips.jpg" as an example.
Exporting Data:
Content Providers are created for exactly this reason. https://developer.android.com/guide/topics/providers/content-providers.html
Content providers are one of the primary building blocks of Android applications, providing content to applications. They encapsulate data and provide it to applications through the single ContentResolver interface. A content provider is only required if you need to share data between multiple applications. For example, the contacts data is used by multiple applications and must be stored in a content provider. If you don't need to share data amongst multiple applications you can use a database directly via SQLiteDatabase.

Why is the issue with my main activity?

I want my application to be able to display average rating when the user click onto the get average button but how can I do it? I have already created the database and the database is working but I have issues with the main activity.
manifest:
<?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"
android:orientation="vertical"
>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="left">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="10dp">
<ImageView
android:layout_width="150dp"
android:layout_height="50dp"
android:scaleType="fitXY"
android:src="#drawable/logo_jpg" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:text="Product:"
android:id="#+id/textView"
android:textStyle="bold"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:ems="10"/>
</TableRow>
<ListView
android:layout_width="match_parent"
android:layout_height="200dp"
android:scrollingCache="true"
android:smoothScrollbar="true"
android:id="#+id/averagelistView"
android:layout_alignParentLeft="true"
>
</ListView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/buttonaverage"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:onClick="Average"
android:text="Get Average"/>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:text="Get Average:"
android:onClick="average"
android:id="#+id/textView2"
android:textStyle="bold"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText2"
android:ems="10"/>
</TableRow>
</TableLayout>
</ScrollView>
</LinearLayout>
MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.averagerating2ndpage);
lvInfo = (ListView) findViewById(R.id.averagelistView);
txtProduct = (EditText) findViewById(R.id.editText);
txtAvg = (EditText) findViewById(R.id.editText2);
db = new Database_rbar(this);
dbAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, ArrayofName);
lvInfo.setAdapter(dbAdapter);
lvInfo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
currentId = results.get(position).getId();
txtProduct.setText(results.get(position).getProduct());
}
});
DisplayAll();
btnAvg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtAvg = db.getAverage();
}
});
}
public void DisplayAll() {
results = db.getAllResults();
ArrayofName.clear();
for (Result rs : results) {
ArrayofName.add(rs.getId() + ".\t" + rs.getProduct());
}
dbAdapter.notifyDataSetChanged();
txtProduct.setText("");
}
}
Database:
public class Database_rbar extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = Environment.getExternalStorageDirectory().toString() + "/result.db";
private static final String TABLE_RESULT = "Result";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_RATING = "rating";
private static final String KEY_PHONE = "phone";
private static final String KEY_PRODUCT = "product";
private static final String KEY_EMAIL = "email";
public Database_rbar(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//creating Tables
#Override
public void onCreate(SQLiteDatabase db){
String CREATE_RESULTS_TABLE = "CREATE TABLE " + TABLE_RESULT + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME +
" TEXT,"+ KEY_PHONE + " TEXT," + KEY_EMAIL + " TEXT," + KEY_PRODUCT + " TEXT," + KEY_RATING + " REAL" + ")";
db.execSQL(CREATE_RESULTS_TABLE);
}
//upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
//drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_RESULT);
//create tables again
onCreate(db);
}
public int getAverage(String product){
String countquery = "SELECT AVG(rating) * FROM" + TABLE_RESULT + "WHERE" + KEY_PRODUCT + "='" + product + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countquery, null);
cursor.close();
return cursor.getCount();
}
public List<Result> getAllResults() {
List<Result> resultList = new ArrayList<Result>();
String selectQuery = "SELECT * FROM " + TABLE_RESULT;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
//looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Result result = new Result();
result.setId(Integer.parseInt(cursor.getString(0)));
result.setName(cursor.getString(1));
result.setPhone(cursor.getString(2));
result.setEmail(cursor.getString(3));
result.setProduct(cursor.getString(4));
result.setRating(Float.parseFloat(cursor.getString(5)));
resultList.add(result);
} while (cursor.moveToNext());
}
return resultList;
}
}
From your code txtAvg is an EditText variable but in onClick() method you assign to an integer value from db.getAverage().
The appropriate way would be to convert the integer to String then set it to txtAvg using setText() method:
txtAvg.setText(String.valueOf(db.getAverage()));
Your getAverage() method in Database_rbar has a String parameter, but when you call it in MainActivity it has no arguments:
txtAvg = db.getAverage();
It should (from what I can infer from your code) look more like:
txtAvg = db.getAverage("product_key_here");
There may be other errors, but this is the one referred to by your stack trace.
Edit: Ramadan Juma has correctly identified another issue. In addition, I expect your countquery String will create a problem as well, as it has an incorrect number of spaces.
Edit 2: You also call cursor.close() before you call cursor.getCount(). I expect this will also throw an error.

Display SQLite table data row by row in Android using TableLayout dynamically

I'm new to android coding. I simply want to display data row by row from my database table.
Here is the part where I have created database/table and added data.
SQLiteDatabase glucoDB = openOrCreateDatabase("glucoDB",MODE_PRIVATE,null);
glucoDB.execSQL("CREATE TABLE IF NOT EXISTS Results(Timestamp VARCHAR, Level_using_hsv_range VARCHAR,Level_using_hsv_gradient VARCHAR,Level_using_lab_range VARCHAR,Level_using_lab_gradient VARCHAR);");
String query=new String("INSERT INTO Results VALUES ('" + currentDateTimeString + "', '" + str + "mg/dL', '" + glucose[1] + "mg/dL', '" + gvalue + "-" + largeg + "mg/dL', '" + LabRes2 + "mg/dL');");
glucoDB.execSQL(query);
Below is the activity code (ViewResults.java) for displaying database values.I can't figure out what I'm doing wrong. On exporting and running the app, the rest of the app works fine but the part where data is displayed shows a black screen and app exits instantly. Although if I display data using simple TextView and not TableLayout, it is displayed normally. So database part is working fine, there's something wrong with my TableLayout code.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_page);
int i=0,j=0;
SQLiteDatabase Glucodb = openOrCreateDatabase("glucoDB",MODE_PRIVATE,null);
Cursor resultSet = Glucodb.rawQuery("Select * from Results",null);
resultSet.moveToFirst();
TableLayout l1 = (TableLayout) findViewById(R.id.table2);
l1.setStretchAllColumns(true);
l1.bringToFront();
do
{ TableRow tr = new TableRow(getBaseContext());
TextView t1 = new TextView(getBaseContext());
TextView t2 = new TextView(getBaseContext());
TextView t3 = new TextView(getBaseContext());
TextView t4 = new TextView(getBaseContext());
TextView t5 = new TextView(getBaseContext());
t1.setBackgroundResource(R.drawable.border);
t1.setText(resultSet.getString(0));
t2.setText(resultSet.getString(1));
t3.setText(resultSet.getString(2));
t4.setText(resultSet.getString(3));
t5.setText(resultSet.getString(5));
tr.addView(t1);
tr.addView(t2);
tr.addView(t3);
tr.addView(t4);
tr.addView(t5);
l1.addView(tr);
}while(resultSet.moveToNext());
}
Below is the code of XML file associate with displaying results in table format.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TableLayout
android:id="#+id/table2"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_marginBottom="0dp"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:layout_weight="0.80"
android:stretchColumns="*" >
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:gravity="left"
android:text="Timestamp"
android:background="#drawable/border"
android:textStyle="bold" />
<TextView
android:gravity="center"
android:text="Gvalue1"
android:background="#drawable/border"
android:textStyle="bold" />
<TextView
android:gravity="center"
android:text="Gvalue2"
android:background="#drawable/border"
android:textStyle="bold" />
<TextView
android:gravity="center"
android:text="Gvalue3"
android:background="#drawable/border"
android:textStyle="bold" />
<TextView
android:gravity="center"
android:text="Gvalue4"
android:background="#drawable/border"
android:textStyle="bold" />
</TableRow>
</TableLayout>
</LinearLayout>

How to View data, based on date input(edittext)?

I wanted to do a view output using table layout.
My idea goes like this.
I have a main page, known as activity_main.xml
when you click on the cancel button, it will go to a summary page,
know as data.xml.
In data.xml, I have a date edittext, whereby ,when I enter a date,eg 12/2/2013,
and after I click the button search, it will show me the record of it.
However, I'm not sure how to do it.
If I didn't enter any date and click "search", it will show all the records.
Right now,I am able to show all the records, without searching the data.
Below is my code.
Can someone kindly help me out with the search by date?
I hope that I've explained myself clear enough.
DBAdapter.java
public class DBAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_DATE = "date";
public static final String KEY_PRICE = "fuelprice";
public static final String KEY_FUEL = "fuelpump";
public static final String KEY_COST = "tcost";
public static final String KEY_ODM = "odometer";
public static final String KEY_CON = "fcon";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "MyDB";
private static final String DATABASE_TABLE = "fuelLog";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE =
"create table fuelLog (_id integer primary key autoincrement, " + "date text not null, fuelprice text not null, fuelpump text not null, tcost text not null, odometer text not null, fcon text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx){
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db)
{
try{
db.execSQL(DATABASE_CREATE);
}catch (SQLException e){
e.printStackTrace();
}
}//onCreate
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}//onUpgrade
}//DatabaseHelper
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}//open
//---closes the database---
public void close()
{
DBHelper.close();
}//close
//---insert a log into the database---
public long insertLog(String date, String fuelprice, String fuelpump,String tcost,String odometer,String fcon )
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_DATE, date);
initialValues.put(KEY_PRICE, fuelprice);
initialValues.put(KEY_FUEL, fuelpump);
initialValues.put(KEY_COST, tcost);
initialValues.put(KEY_ODM, odometer);
initialValues.put(KEY_CON, fcon);
return db.insert(DATABASE_TABLE, null, initialValues);
}//insertLog
// --retrieves all the data
public Cursor getAllLog()
{
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_DATE, KEY_PRICE, KEY_FUEL,KEY_ODM,KEY_CON}, null, null, null, null, null);
}
}
summary.java
public class summary extends Activity{
TableLayout tablelayout_Log = null;
Button searchButton = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data);
tablelayout_Log = (TableLayout) findViewById(R.id.tableLayout_Log);
tablelayout_Log.setStretchAllColumns(true);
tablelayout_Log.setShrinkAllColumns(true);
//View
searchButton = (Button) findViewById(R.id.searchBtn);
searchButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try{
refreshTable();
}
catch (Exception e)
{
Log.d("Fuel Log", e.getMessage());
}
}
});
}//oncreate
public void refreshTable()
{
tablelayout_Log.removeAllViews();
TableRow rowTitle = new TableRow(this);
rowTitle.setGravity(Gravity.CENTER_HORIZONTAL);
TextView title = new TextView(this);
title.setText("Fuel Log");
title.setTextSize(TypedValue.COMPLEX_UNIT_DIP,18);
title.setGravity(Gravity.CENTER);
title.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
TableRow.LayoutParams params = new TableRow.LayoutParams();
params.span = 5;
rowTitle.addView(title, params);
tablelayout_Log.addView(rowTitle);
DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
Cursor cursor = null;
try
{
dbAdaptor.open();
cursor = dbAdaptor.getAllLog();
cursor.moveToFirst();
do{
long id = cursor.getLong(0);
String date = cursor.getString(1);
String price = cursor.getString(2);
String pump = cursor.getString(3);
String odometer = cursor.getString(4);
String fcon = cursor.getString(5);
TextView viewId = new TextView(getApplicationContext());
viewId.setText("" + id);
TextView viewDate = new TextView(getApplicationContext());
viewDate.setText(date);
TextView viewPrice = new TextView(getApplicationContext());
viewPrice.setText(price);
TextView viewPump = new TextView(getApplicationContext());
viewPump.setText(pump);
TextView viewOdometer = new TextView(getApplicationContext());
viewOdometer.setText(odometer);
TextView viewCon = new TextView(getApplicationContext());
viewCon.setText(fcon);
TableRow row = new TableRow(this);
row.setGravity(Gravity.CENTER_HORIZONTAL);
row.addView(viewId);
row.addView(viewDate);
row.addView(viewPrice);
row.addView(viewPump);
row.addView(viewOdometer);
row.addView(viewCon);
tablelayout_Log.addView(row);
}
while(cursor.moveToNext());
}
catch(Exception e){
Log.d("Fuel Log", e.getMessage());
}
finally
{
if (cursor != null)
cursor.close();
if(dbAdaptor != null)
dbAdaptor.close();
}
}//refreshTable
}//main
MainActivity.java
public class MainActivity extends Activity {
TableLayout tablelayout_Contacts = null;
Button insertButton = null;
EditText nameEdit = null;
EditText contactEdit = null;
Button viewButton = null;
Button deleteButton = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tablelayout_Contacts = (TableLayout) findViewById(R.id.tableLayout_Contacts);
tablelayout_Contacts.setStretchAllColumns(true);
tablelayout_Contacts.setShrinkAllColumns(true);
nameEdit = (EditText) findViewById(R.id.editText_Name);
contactEdit = (EditText) findViewById(R.id.editText_Number);
insertButton = (Button) findViewById(R.id.button1);
insertButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
try{
dbAdaptor.open();
String name = nameEdit.getText().toString();
String number = contactEdit.getText().toString();
dbAdaptor.insertContact(name, number);
}
catch (Exception e)
{
Log.d("Contact Manager",e.getMessage());
}
finally{
if(dbAdaptor != null)
dbAdaptor.close();
}
}
});
//View records
viewButton = (Button) findViewById(R.id.button2);
viewButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try{
refreshTable();
}
catch (Exception e)
{
Log.d("Contact Manager",e.getMessage());
}
}
});
//delete records
deleteButton = (Button) findViewById(R.id.button3);
deleteButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
try{
refreshTable();
String name = nameEdit.getText().toString();
if(!name.equals(""))
{
dbAdaptor.deleteContact(name);
}
}
catch (Exception e)
{
Log.d("Contact Manager",e.getMessage());
}
}
});
}//oncreate
//refresh table
public void refreshTable()
{
tablelayout_Contacts.removeAllViews();
TableRow rowTitle = new TableRow(this);
rowTitle.setGravity(Gravity.CENTER_HORIZONTAL);
TextView title = new TextView(this);
title.setText("Contacts");
title.setTextSize(TypedValue.COMPLEX_UNIT_DIP,18);
title.setGravity(Gravity.CENTER);
title.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
TableRow.LayoutParams params = new TableRow.LayoutParams();
params.span =3;
rowTitle.addView(title,params);
tablelayout_Contacts.addView(rowTitle);
DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
Cursor cursor = null;
try{
dbAdaptor.open();
cursor = dbAdaptor.getAllContacts();
cursor.moveToFirst();
do{
long id = cursor.getLong(0);
String name = cursor.getString(1);
String contact = cursor.getString(2);
TextView idView = new TextView(getApplicationContext());
idView.setText("" + id);
TextView nameView = new TextView(getApplicationContext());
nameView.setText(name);
TextView contactView = new TextView(getApplicationContext());
nameView.setText(contact);
TableRow row = new TableRow(this);
row.setGravity(Gravity.CENTER_HORIZONTAL);
row.addView(idView);
row.addView(nameView);
row.addView(contactView);
tablelayout_Contacts.addView(row);
}
while (cursor.moveToNext());
}
catch (Exception e)
{
Log.d("Contact Manager", e.getMessage());
}
finally{
if (cursor != null)
cursor.close();
if(dbAdaptor != null)
dbAdaptor.close();
}
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_height="fill_parent"
tools:context=".MainActivity" >
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1">
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/datetxtview"
android:text="#string/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/date"
android:text=""
android:inputType="date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fuelpricetxtview"
android:text="#string/fuelprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/fuelprice"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fuelpumptxtview"
android:text="#string/fuelpump"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/fuelpump"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow4"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/totalcosttxtview"
android:text="#string/totalcost"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<TextView
android:id="#+id/tcost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</TableRow>
<TableRow
android:id="#+id/tableRow5"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/odometertxtview"
android:text="#string/odometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/odometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow6"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fctxtview"
android:text="#string/fc"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<TextView
android:id="#+id/fcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</TableRow>
</TableLayout>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/saveBTN"
android:text="#string/save"
android:layout_width="wrap_content"
android:layout_height="60px" >
</Button>
<Button
android:id="#+id/updateBTN"
android:text="Update"
android:layout_width="wrap_content"
android:layout_height="60px" >
</Button>
<Button
android:id="#+id/cancelBTN"
android:text="#string/cancel"
android:layout_width="wrap_content"
android:layout_height="60px" >
</Button>
</LinearLayout>
</LinearLayout>
data.xml
<?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"
android:orientation="vertical" >
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1">
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/datetxtview"
android:text="#string/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/datepast"
android:text=""
android:inputType="date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fctxtview"
android:text="#string/fc"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/fc"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/highpricetxtview"
android:text="#string/highprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/highprice"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow4"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/searchBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search" />
<Button
android:id="#+id/deleteBTN"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete" />
<Button
android:id="#+id/backBTN"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back" />
</TableRow>
</TableLayout>
<TableLayout
android:id="#+id/tableLayout_Log"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</TableLayout>
</LinearLayout>
The error you are getting is a nullpointer that means that some object that is at line 205 in MainActivity or it is used at that line is null. Check that first and then try to run again.
The immediate problem is here:
catch (Exception e)
{
Log.d("Fuel Log", e.getMessage());
}
Not all throwables have a message and a null can be returned. A null cannot be logged. It causes the "println needs a message" exception in the stacktrace.
So first, change that to e.g.
catch (Exception e)
{
Log.e("Fuel Log", "", e);
}
This will log the exception with error level, empty message and with full stacktrace.
Then you can see what causes that exception in the first place.
Hello date type is not supported in Sqlite Database.you have assign date as text so it will take string so you need to keep string in proper order so that it can work as date search.
You can store date in form of 2013-12-23 (20131223) then you can get your query by passing date
by the way you can try like below
public ArrayList<String> getEventsForNotification(String dateSearch)
{
ArrayList<String> arrayList=new ArrayList<String>();
String sql="SELECT "+KEY_EVENT_NAME+" FROM "+ TABLE_EVENT +" WHERE SUBSTR("+KEY_EVENT_DATE+",6) like '"+dateSearch+"'";
Cursor cursor=sqLiteDatabase.rawQuery(sql, null);
if(cursor.moveToFirst())
{
do
{
arrayList.add(cursor.getString(0));
}while(cursor.moveToNext());
cursor.close();
cursor=null;
}
return arrayList;
}
modify according to your need.

Categories