How to display specific data from a sqlite database in a listview with a condition like 'where'? - database

I made an application with an SQLite database. I want to show the data in a listview, but I don't want to show all the data from the database, but just some data. So, I want to add a condition. I only want to show the data where string 'dag' is 'maandag'.
Can anyone help me?
This is the code from my DatabaseHelper, where the database is created:
package com.persoonlijk.rooster.test2;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import java.util.ArrayList;
import java.util.List;
//A helper class to manage database creation and version management.
public class DataManipulator
{
//Database attributes
private static final String DATABASE_NAME = "mydatabase.db";
static final String TABLE_NAME = null;
private static final int DATABASE_VERSION = 12;
//Table attributes
public static final String KEY_ROWID = "id";
public static final String KEY_DAG = "dag";
public static final String KEY_UUR = "uur";
public static final String KEY_VAK = "vak";
public static final String KEY_LOKAAL = "lokaal";
private static Context context;
static SQLiteDatabase db;
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into " + TABLE_NAME + " (dag,uur,vak,lokaal) values (?,?,?,?)";
public DataManipulator(Context context) {
DataManipulator.context = context;
OpenHelper openHelper = new OpenHelper(DataManipulator.context);
DataManipulator.db = openHelper.getWritableDatabase();
this.insertStmt = DataManipulator.db.compileStatement(INSERT);
}
public long insert(String dag,String uur,String vak,String lokaal) {
this.insertStmt.bindString(1, dag);
this.insertStmt.bindString(2, uur);
this.insertStmt.bindString(3, vak);
this.insertStmt.bindString(4, lokaal);
return this.insertStmt.executeInsert();
}
public void deleteAll() {
db.delete(TABLE_NAME, null, null);
}
public List<String[]> selectAll()
{
List<String[]> list = new ArrayList<String[]>();
Cursor cursor = db.query(TABLE_NAME, new String[] { "id","dag","uur","vak","lokaal" }, null, null, null, null, "dag asc");
int x=0;
if (cursor.moveToFirst()) {
do {
String[] b1=new String[]{cursor.getString(0),cursor.getString(1),cursor.getString(2),
cursor.getString(3),cursor.getString(4)};
list.add(b1);
x=x+1;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor.close();
return list;
}
public boolean delete(long id) {
return db.delete(TABLE_NAME, KEY_ROWID + "=" + id, null) > 0;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY, dag TEXT, uur TEXT, vak TEXT, lokaal TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
This is the code from the Activity where I want to display the specific data. Right now, all the data from the database is displayed.
package com.persoonlijk.rooster.test2;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class RoosterMaandag extends ListActivity{
TextView selection;
public int idToModify;
DataManipulator dm;
List<String[]> list = new ArrayList<String[]>();
List<String[]> names2 =null ;
String[] stg1;
/** Called when the activity is first created. */
//zorgt voor het overzicht van de gegevens uit de database
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.rooster);
dm = new DataManipulator(this);
names2 = dm.selectAll();
stg1=new String[names2.size()];
int x=0;
String stg;
for (String[] dag : names2) {
stg = dag[1]+" - "+dag[2]+ " - "+dag[3]+" - "+dag[4];
stg1[x]=stg;
x++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,stg1);
this.setListAdapter(adapter);
selection=(TextView)findViewById(R.id.selection);
}
//menuknoppen
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, 0, 0, "Voeg gegevens toe");
menu.add(Menu.NONE, 1, 1, "Verwijder gegevens");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
startActivity(new Intent(this, SaveData.class));
return true;
case 1:
startActivity(new Intent(this, VerwijderData.class));
return true;
}
return false;
}
}
Please let me know when my question isn't clear enough. I really hope someone can help me!
I added this code in my DataManipulator.java:
public List<String[]> selectSome(String arg) {
String[] columns = new String[] { "id", "dag", "uur", "vak", "lokaal" };
String[] selectionArgs = {arg};
Cursor cursor = db.query(TABLE_NAME, columns, "dag = ?", selectionArgs, null, null, "dag asc");
List<String[]> list = new ArrayList<String[]>(cursor.getCount());
while (cursor.moveToNext()) {
String[] b1 = new String[] { cursor.getString(0),
cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4) };
list.add(b1);
}
cursor.close();
return list;
}
and this code in my RoosterMaandag.java:
public void onCreate(Bundle savedInstanceState){
....
dm.selectSome("maandag");
....
}

I don't know about android but for sql
try this
select data_to_print from table_name where REGEXP_LIKE(column_name_where_to_match,'dag$');
more info here http://docs.oracle.com/cd/B12037_01/server.101/b10759/ap_posix001.htm#i690819
Example:
SQL> select job_id from jobs where regexp_like(job_id,'N$');
JOB_ID
----------
MK_MAN
PU_MAN
SA_MAN
ST_MAN

you need a new method in your DataManipulator class:
public List<String[]> selectSome(String arg) {
String[] columns = new String[] { "id", "dag", "uur", "vak", "lokaal" };
String[] selectionArgs = {arg};
Cursor cursor = db.query(TABLE_NAME, columns, "dag = ?", selectionArgs, null, null, "dag asc");
List<String[]> list = new ArrayList<String[]>(cursor.getCount());
while (cursor.moveToNext()) {
String[] b1 = new String[] { cursor.getString(0),
cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4) };
list.add(b1);
}
cursor.close();
return list;
}
I'll say it again. consider using a CursorAdapter for these tasks.

Related

Tableview update database on edit

So the thing that i want to happen, is making the tableview update the data in the database after editing it. I wanted to use the SetOnEditCommit method here. The cell editing does work, but it never gets updated, with no error either. In the first place im a bit clueless if this method is actually efficient (probably not), since its hard to find some sources for this specific thing. And the sources that i found weren't really helpful. So it would be nice if someone had an idea as to why it doesn't update, or maybe provide an alternate option here.
The mentioned part:
columnType.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<UserDetails, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<UserDetails, String> event) {
updataData();
}
});
tableview.setItems(null);
tableview.setItems(data);
}
public void updataData() {
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://37.128.148.113:3306/FYS", "FYS", "Kcj8g87~");
Statement con = connection.createStatement();
//connection
TablePosition pos = tableview.getSelectionModel().getSelectedCells().get(0);
int row = pos.getRow();
TableColumn col = pos.getTableColumn();
String data1 = (String) col.getCellObservableValue(row).getValue();
//cell
UserDetails row1 = tableview.getSelectionModel().getSelectedItem();
c1 = row1.getId();
//row
//tableview variables
con.execute("UPDATE gevonden_bagage SET type = 'data1' WHERE koffer_id = 'c1' ");
//Query
} catch (SQLException ex) {
System.err.println("Error" + ex);
}
}
//get connection, get celldata, get id data from first row, update cell with selected id
full controller class:
package simple;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TablePosition;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
/**
*
* #author admin
*/
public class FXMLUserController extends SimpleController implements Initializable {
#FXML
public TableView<UserDetails> tableview;
#FXML
public TableColumn<UserDetails, String> columnId;
#FXML
public TableColumn<UserDetails, String> columnType;
#FXML
public TableColumn<UserDetails, String> columnKleur;
#FXML
public TableColumn<UserDetails, String> columnLuchthaven;
#FXML
public TableColumn<UserDetails, String> columnKenmerken;
#FXML
public TableColumn<UserDetails, String> columnStatus;
#FXML
public TableColumn<UserDetails, String> columnDatum;
#FXML
private Button btnLoad;
//declare observable list for database data
private ObservableList<UserDetails> data;
private DbConnection dc;
String c1;
#FXML
//strings for getRow method
#Override
public void initialize(URL url, ResourceBundle rb) {
dc = new DbConnection();
loadDataFromDatabase();
}
#FXML
public void loadDataFromDatabase() {
try {
Connection conn = dc.Connect();
data = FXCollections.observableArrayList();
// Execute query and store result in a resultset
ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM gevonden_bagage");
while (rs.next()) {
//get strings
data.add(new UserDetails(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5),
rs.getString(6), rs.getString(7)));
}
} catch (SQLException ex) {
System.err.println("Error" + ex);
}
//Set cell values to tableview.
tableview.setEditable(true);
tableview.getSelectionModel().setCellSelectionEnabled(true);
columnType.setCellFactory(TextFieldTableCell.forTableColumn());
columnKleur.setCellFactory(TextFieldTableCell.forTableColumn());
columnLuchthaven.setCellFactory(TextFieldTableCell.forTableColumn());
columnKenmerken.setCellFactory(TextFieldTableCell.forTableColumn());
columnStatus.setCellFactory(TextFieldTableCell.forTableColumn());
columnDatum.setCellFactory(TextFieldTableCell.forTableColumn());
//makes columns editable
columnId.setCellValueFactory(new PropertyValueFactory<>("id"));
columnType.setCellValueFactory(new PropertyValueFactory<>("type"));
columnKleur.setCellValueFactory(new PropertyValueFactory<>("kleur"));
columnLuchthaven.setCellValueFactory(new PropertyValueFactory<>("luchthaven"));
columnKenmerken.setCellValueFactory(new PropertyValueFactory<>("kenmerken"));
columnStatus.setCellValueFactory(new PropertyValueFactory<>("status"));
columnDatum.setCellValueFactory(new PropertyValueFactory<>("datum"));
columnType.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<UserDetails, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<UserDetails, String> event) {
updataData();
}
});
tableview.setItems(null);
tableview.setItems(data);
}
public void updataData() {
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://37.128.148.113:3306/FYS", "FYS", "Kcj8g87~");
Statement con = connection.createStatement();
//connection
TablePosition pos = tableview.getSelectionModel().getSelectedCells().get(0);
int row = pos.getRow();
TableColumn col = pos.getTableColumn();
String data1 = (String) col.getCellObservableValue(row).getValue();
//cell
UserDetails row1 = tableview.getSelectionModel().getSelectedItem();
c1 = row1.getId();
//row
//tableview variables
con.execute("UPDATE gevonden_bagage SET type = 'data1' WHERE koffer_id = 'c1' ");
//Query
} catch (SQLException ex) {
System.err.println("Error" + ex);
}
}
//get connection, get celldata, get id data from first row, update cell with selected id
#FXML
public void getRow() {
TablePosition pos = tableview.getSelectionModel().getSelectedCells().get(0);
int row = pos.getRow();
TableColumn col = pos.getTableColumn();
// this gives the value in the selected cell:
String data1 = (String) col.getCellObservableValue(row).getValue();
System.out.println(data1);
//CURRENTLY UNUSED METHOD
}
}
Model class:
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
*
* #author admin
*/
public class UserDetails {
private final StringProperty id;
private final StringProperty type;
private final StringProperty kleur;
private final StringProperty luchthaven;
private final StringProperty kenmerken;
private final StringProperty status;
private final StringProperty datum;
//Default constructor
public UserDetails(String id, String type, String kleur, String luchthaven, String kenmerken, String status, String datum) {
this.id = new SimpleStringProperty(id);
this.type = new SimpleStringProperty(type);
this.kleur = new SimpleStringProperty(kleur);
this.luchthaven = new SimpleStringProperty(luchthaven);
this.kenmerken = new SimpleStringProperty(kenmerken);
this.status = new SimpleStringProperty(status);
this.datum = new SimpleStringProperty(datum);
}
//getters
public String getId() {
return id.get();
}
public String getType() {
return type.get();
}
public String getKleur() {
return kleur.get();
}
public String getLuchthaven() {
return luchthaven.get();
}
public String getKenmerken() {
return kenmerken.get();
}
public String getStatus() {
return status.get();
}
public String getDatum() {
return datum.get();
}
//setters
public void setId(String value) {
id.set(value);
}
public void setType(String value) {
type.set(value);
}
public void setKleur(String value) {
kleur.set(value);
}
public void setLuchthaven(String value) {
luchthaven.set(value);
}
public void setKenmerken(String value) {
kenmerken.set(value);
}
public void setStatus(String value) {
status.set(value);
}
public void setDatum(String value) {
datum.set(value);
}
//property values
public StringProperty idProperty() {
return id;
}
public StringProperty typeProperty() {
return type;
}
public StringProperty kleurProperty() {
return kleur;
}
public StringProperty luchthavenProperty() {
return luchthaven;
}
public StringProperty kenmerkenProperty() {
return kenmerken;
}
public StringProperty statusProperty() {
return status;
}
public StringProperty datumProperty() {
return datum;
}
}
From the TableView documentation:
By default the TableColumn edit commit handler is non-null, with a
default handler that attempts to overwrite the property value for the
item in the currently-being-edited row. It is able to do this as the
Cell.commitEdit(Object) method is passed in the new value, and this is
passed along to the edit commit handler via the CellEditEvent that is
fired. It is simply a matter of calling
TableColumn.CellEditEvent.getNewValue() to retrieve this value.
It is very important to note that if you call
TableColumn.setOnEditCommit(javafx.event.EventHandler) with your own
EventHandler, then you will be removing the default handler. Unless
you then handle the writeback to the property (or the relevant data
source), nothing will happen.
So the problem is that by setting the onEditCommit on columnType, you remove the default handler that actually updates typeProperty in the UserDetails instance. Consequently
String data1 = (String) col.getCellObservableValue(row).getValue();
gives the old value, and your update to the database won't change anything.
Additionally, you have errors in the way you create the SQL statement. You are making the id in the WHERE clause the literal value 'c1' (instead of the value contained in the variable c1, and similarly setting the value of type to the literal value 'data1', instead of the value in the variable data1.
Here is a fix, along with some simplification of the code and some better practices for avoiding SQL injection attacks:
columnType.setOnEditCommit(event -> {
UserDetails user = event.getRowValue();
user.setType(event.getNewValue());
updateData("type", event.getNewValue(), user.getId());
});
and then
private void updateData(String column, String newValue, String id) {
// btw it is way better to keep the connection open while the app is running,
// and just close it when the app shuts down....
// the following "try with resources" at least makes sure things are closed:
try (
Connection connection = DriverManager.getConnection("jdbc:mysql://37.128.148.113:3306/FYS", "FYS", "Kcj8g87~");
PreparedStatement stmt = connection.prepareStatement("UPDATE gevonden_bagage SET "+column+" = ? WHERE koffer_id = ? ");
) {
stmt.setString(1, newValue);
stmt.setString(2, id);
stmt.execute();
} catch (SQLException ex) {
System.err.println("Error");
// if anything goes wrong, you will need the stack trace:
ex.printStackTrace(System.err);
}
}

Javafx - Binding data from database to choicebox using JPA - EclipseLink

I have created an entity of a table with name Category and I want to get the data as an entity and display the name of the category into a choicebox using StringConverter.
The problem is when I call addAll() method, it occurs a NullPointerException.
Here is my code:
private ChoiceBox<Category> chbDisplayCustomCategory;
#Override
public void initialize(URL location, ResourceBundle resources) {
emFactory = Persistence.createEntityManagerFactory("Glory_StorePU");
eManager = emFactory.createEntityManager();
Query query = eManager.createNamedQuery("Category.findAll", Category.class);
List<Category> list = query.getResultList();
ObservableList<Category> result=FXCollections.observableArrayList(list);
chbDisplayCustomCategory.getItems().addAll(result);
}
Here is the Entity class (Automatically generated):
package MainPack.Entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "CATEGORY")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Category.findAll", query = "SELECT c FROM Category c"),
#NamedQuery(name = "Category.findById", query = "SELECT c FROM Category c WHERE c.id = :id"),
#NamedQuery(name = "Category.findByCatName", query = "SELECT c FROM Category c WHERE c.catName = :catName")})
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "ID")
private Long id;
#Basic(optional = false)
#Column(name = "CAT_NAME")
private String catName;
public Category() {
}
public Category(Long id) {
this.id = id;
}
public Category(Long id, String catName) {
this.id = id;
this.catName = catName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCatName() {
return catName;
}
public void setCatName(String catName) {
this.catName = catName;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Category)) {
return false;
}
Category other = (Category) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "MainPack.Entities.Category[ id=" + id + " ]";
}
}
so can you help me please ?

ContactsContract.Contacts issue, duplicates

I've been doing research on this but I can't figure it out. My contacts in my phone in a sample app I downloaded are often duplicated, like so:
I'm quite sure it has something to do with ContactsContract.Contacts. I've read up on it but don't know how to implement it in my code. Could someone help (or indeed if there's another way of doing it). I just want each contact be listed once, not multiple time.
According to http://developer.android.com/reference/android/provider/ContactsContract.Contacts.html :
ContactsContract.Contacts
Constants for the contacts table, which contains a record per aggregate of raw contacts representing the same person.
I have 3 java files in my project, MainActivity, SelectUser and SelectUserAdapter, but I believe MainActivity is the one pertaining to this problem. Probably specifically this line :
phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
If you need more code just let me know.
Here's my MainActivity.java :
package com.example.chris.contactlistcustomlistview;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
// ArrayList
ArrayList<SelectUser> selectUsers;
List<SelectUser> temp;
// Contact List
ListView listView;
// Cursor to load contacts list
Cursor phones, email;
// Pop up
ContentResolver resolver;
SearchView search;
SelectUserAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectUsers = new ArrayList<SelectUser>();
resolver = this.getContentResolver();
listView = (ListView) findViewById(R.id.contacts_list);
phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
// retrieves contact information
LoadContact loadContact = new LoadContact();
loadContact.execute();
// let's set up our search box,
search = (SearchView) findViewById(R.id.searchView);
//*** setOnQueryTextListener ***
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// when the text in searchView changes, call the filter function
adapter.filter(newText);
return false;
}
});
}
// Load data on background
class LoadContact extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
// Get Contact list from Phone
if (phones != null) {
Log.e("count", "" + phones.getCount());
if (phones.getCount() == 0) {
Toast.makeText(MainActivity.this, "No contacts in your contact list.", Toast.LENGTH_LONG).show();
}
while (phones.moveToNext()) {
Bitmap bit_thumb = null;
String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String EmailAddr = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA2));
String image_thumb = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI));
try {
if (image_thumb != null) {
bit_thumb = MediaStore.Images.Media.getBitmap(resolver, Uri.parse(image_thumb));
} else {
Log.e("No Image Thumb", "--------------");
}
} catch (IOException e) {
e.printStackTrace();
}
//what's happening here? For every user in the phonebook, show an image, the name, number, an id and maybe a checkbox?
SelectUser selectUser = new SelectUser();
selectUser.setThumb(bit_thumb);
selectUser.setName(name);
selectUser.setPhone(phoneNumber);
selectUser.setEmail(id);
selectUser.setCheckedBox(false);
selectUsers.add(selectUser);
}
} else {
Log.e("Cursor close 1", "----------------");
}
//phones.close();
return null;
}
#Override
// when DoInBackground is finished, when we have our phone number, name etc... display the results in our listview.
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter = new SelectUserAdapter(selectUsers, MainActivity.this);
listView.setAdapter(adapter);
// Select item on listclick
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.e("search", "here---------------- listener");
SelectUser data = selectUsers.get(i);
}
});
listView.setFastScrollEnabled(true);
}
}
#Override
protected void onStop() {
super.onStop();
phones.close();
}
}
public class MainActivity extends Activity {
Cursor cursor;
ListView mainListView;
ArrayList hashMapsArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (cursor != null) {
cursor.moveToFirst();}
try {
cursor = getApplicationContext().getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
int Idx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
int nameIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int phoneNumberIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int photoIdIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI);
cursor.moveToFirst();
Set<String> ids = new HashSet<>();
do {
System.out.println("=====>in while");
String contactid=cursor.getString(Idx);
if (!ids.contains(contactid)) {
ids.add(contactid);
HashMap<String, String> hashMap = new HashMap<String, String>();
String name = cursor.getString(nameIdx);
String phoneNumber = cursor.getString(phoneNumberIdx);
String image = cursor.getString(photoIdIdx);
System.out.println("Id--->"+contactid+"Name--->"+name);
System.out.println("Id--->"+contactid+"Name--->"+name);
System.out.println("Id--->"+contactid+"Number--->"+phoneNumber);
if (!phoneNumber.contains("*")) {
hashMap.put("contactid", "" + contactid);
hashMap.put("name", "" + name);
hashMap.put("phoneNumber", "" + phoneNumber);
hashMap.put("image", "" + image);
// hashMap.put("email", ""+email);
if (hashMapsArrayList != null) {
hashMapsArrayList.add(hashMap);}
// hashMapsArrayList.add(hashMap);
}
}
} while (cursor.moveToNext());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}

Login validation from database error Android [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have created a database table where I have id, username, password and email as columns. My xml has 3 elements, Username, password edittexts and a signin button.
Method validateLogin in DatabaseActivity.java does the validation.
Error
The method getWritableDatabase() is undefined for the type DbHelper
in line ----- SQLiteDatabase db = mydb.getWritableDatabase();----
This is my DatabaseActivity.java file
package com.login.recscores;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
#SuppressLint("Registered")
public class DatabaseActivity extends Activity implements OnClickListener {
Button mLogin;
Button mNewUser;
Button mShowAll;
EditText mUsername;
EditText mPassword;
DbHelper mydb = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mNewUser = (Button)findViewById(R.id.sign_in_button);
mNewUser.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()){
case R.id.sign_in_button:
mUsername = (EditText)findViewById(R.id.email);
mPassword = (EditText)findViewById(R.id.password);
String uname = mUsername.getText().toString();
String pass = mPassword.getText().toString();
if(uname.equals("") || uname == null){
Toast.makeText(getApplicationContext(), "email Empty", Toast.LENGTH_SHORT).show();
}else if(pass.equals("") || pass == null){
Toast.makeText(getApplicationContext(), "Password Empty", Toast.LENGTH_SHORT).show();
}else{
boolean validLogin = validateLogin(uname, pass, DatabaseActivity.this);
if(validLogin){
System.out.println("In Valid");
Intent i = new Intent(DatabaseActivity.this, UserHome.class);
startActivity(i);
finish();
}
}
break;
}
}
// #SuppressWarnings("deprecation")
public boolean validateLogin(String uname, String pass, Context context) {
mydb = new DbHelper(this);
SQLiteDatabase db = mydb.getWritableDatabase();
//SELECT
String[] columns = {"_id"};
//WHERE clause
String selection = "username=? AND password=?";
//WHERE clause arguments
String[] selectionArgs = {uname,pass};
Cursor cursor = null;
try{
//SELECT _id FROM login WHERE username=uname AND password=pass
cursor = db.query(DbHelper.RECSCORES_TABLE_NAME, columns, selection, selectionArgs, null, null, null);
// startManagingCursor(cursor);
}catch(Exception e){
e.printStackTrace();
}
int numberOfRows = cursor.getCount();
if(numberOfRows <= 0){
Toast.makeText(getApplicationContext(), "Wha Failed..\nTry Again", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
public void onDestroy(){
super.onDestroy();
mydb.close();
}
}
The DbHelper.java is
package com.login.recscores;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DbHelper {
private static final String DATABASE_NAME = "recscores.db";
public static final String KEY_ROWID = "_id";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_EMAIL = "email";
private static final String TAG = "DbHelper";
private static final int DATABASE_VERSION = 1;
public static final String RECSCORES_TABLE_NAME = "users";
private static final String RECSCORES_TABLE_CREATE =
"CREATE TABLE " + RECSCORES_TABLE_NAME + "(" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"+
"username VARCHAR NOT NULL, password VARCHAR NOT NULL, email VARCHAR NOT NULL);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DbHelper(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);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(RECSCORES_TABLE_CREATE);
}
#Override
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 titles");
onCreate(db);
}
}
//---opens the database---
public DbHelper open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a title into the database---
public long insertTitle(String Id, String username, String password, String email)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ROWID, Id);
initialValues.put(KEY_USERNAME, username);
initialValues.put(KEY_PASSWORD, password);
initialValues.put(KEY_EMAIL, email);
return db.insert(RECSCORES_TABLE_NAME, null, initialValues);
}
//---deletes a particular title---
public boolean deleteTitle(long rowId)
{
return db.delete(RECSCORES_TABLE_NAME, KEY_ROWID +
"=" + rowId, null) > 0;
}
//---retrieves all the titles---
public Cursor getAllTitles()
{
return db.query(RECSCORES_TABLE_NAME, new String[] {
KEY_ROWID,
KEY_USERNAME,
KEY_PASSWORD,
KEY_EMAIL},
null,null,null,null,null);
}
//---retrieves a particular title---
public Cursor getTitle(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, RECSCORES_TABLE_NAME, new String[] {
KEY_ROWID,
KEY_USERNAME,
KEY_PASSWORD,
KEY_EMAIL
},
KEY_ROWID + "=" + rowId,
null,null,null,null,null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
//---updates a title---
public boolean updateTitle(long rowId, String isbn,
String title, String publisher)
{
ContentValues args = new ContentValues();
args.put(KEY_USERNAME, isbn);
args.put(KEY_PASSWORD, title);
args.put(KEY_EMAIL, publisher);
return db.update(RECSCORES_TABLE_NAME, args,
KEY_ROWID + "=" + rowId, null) > 0;
}
}
getWritableDatabase is a method on DatabaseHelper, not DbHelper. For example:
In your DbHelper.java, you use get getWritableDatabase as follows:
db = DBHelper.getWritableDatabase();
where you are declaring:
private DatabaseHelper DBHelper;
So you are calling getWritableDatabase on an instance of DatabaseHelper
However on the problem line you have this:
mydb = new DbHelper(this);
SQLiteDatabase db = mydb.getWritableDatabase();
This is attempting to call getWritableDatabase on an instance of DbHelper, which you haven't declared.
Note that you're use of a DBHelper variable within your declaration of a class called DbHelper is confusing in the extreme, and likely is the cause of the misunderstanding.

03-23 01:34:35.861: E/AndroidRuntime(613): Caused by: android.database.sqlite.SQLiteException: near "in": syntax error: , while compiling:

Im just starting to learn how to create and use a database.
Here is the error I get:03-23 01:34:35.861: E/AndroidRuntime(613): Caused by: android.database.sqlite.SQLiteException: near "in": syntax error: , while compiling: create table payouts(_id integer primary key autoincrement, date text not null, casino text not null, game text not null, in text not null, out text not null, gain text not null);
I have gone over it, and I cant seem to figure out why it will not work.
Any help would be much appreciated.
package kris.databasetester;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter
{
public static final String KEY_ROWID = "_id";
public static final String KEY_DATE = "date";
public static final String KEY_CASINO = "casino";
public static final String KEY_GAME = "game";
public static final String KEY_IN = "in";
public static final String KEY_OUT = "out";
public static final String KEY_GAIN = "gain";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "casinodb";
private static final String DATABASE_TABLE = "payouts";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "create table payouts(_id integer primary key autoincrement, " + "date text not null, casino text not null, " + "game text not null, in text not null, out text not null, gain text not null);";
// private static final String date = null;
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
} //DBAdapter Closer
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
} //onCreate Closer
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destory all old data");
db.execSQL("DROP TABLE IF EXISTS payouts");
onCreate(db);
} //onUpgrade Closer
} //DatabaseHelper Closer
//Opens the Database
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}//DBAdapter Open Closer
//Closes the Database
public void close()
{
DBHelper.close();
} //DBAdapter Close Closer
//Insert a GamePlay into Database
public long insertTitle(String date, String casino, String game, String in, String out, String gain)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_DATE, date);
initialValues.put(KEY_CASINO, casino);
initialValues.put(KEY_GAME, game);
initialValues.put(KEY_IN, in);
initialValues.put(KEY_OUT, out);
initialValues.put(KEY_GAIN, gain);
return db.insert(DATABASE_NAME, null, initialValues);
} //Insert Title Closer
// Deletes a particular title
public boolean deleteTitle(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
} //Delete Title Closer
//Retrieves all titles
public Cursor getAllTitles()
{
return db.query(DATABASE_TABLE, new String[]
{
KEY_ROWID, KEY_DATE, KEY_CASINO, KEY_GAME, KEY_IN, KEY_OUT, KEY_GAIN
},null, null, null, null, null);
} //Gets all titles closer
//Retrieves a particular Title
public Cursor getTitle(long rowId) throws SQLException
{
Cursor mCursor = db.query(true, DATABASE_TABLE, new String[]
{KEY_ROWID, KEY_DATE, KEY_CASINO, KEY_GAME, KEY_IN, KEY_OUT, KEY_GAIN},
KEY_ROWID + "=" + rowId, null, null, null, null, null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
} //getTitle Closer
//Updates a title
// public boolean updateTitle(long rowId, String KEY_DATE, String KEY_CASINO, String KEY_GAME, String KEY_IN, String KEY_OUT, String KEY_GAIN)
// {
// ContentValues args = new ContentValues();
// args.put(KEY_DATE, date);
// args.put(KEY_CASINO, casino);
// args.put(KEY_GAME, game);
// args.put(KEY_IN, in);
// args.put(KEY_OUT, out);
// args.put(KEY_GAIN, gain);
// return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
// } //Update Title Closer
} //Class Closer
-----------------------------
package kris.databasetester;
import android.app.Activity;
import android.os.Bundle;
public class DatabaseTesterActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
#SuppressWarnings("unused")
DBAdapter db = new DBAdapter(this);
//---add 2 titles---
db.open();
// long id;
// id = db.insertTitle("09/08/2012","The Sands","BlackJack", "400", "500", "100");
// db.close();
}
}
-------------------------------
it's telling you that in is not an allowable name for a column, which is because it's reserved for other uses in the SQL language.

Resources