here my coding:-
DatabaseHelper.java
public Cursor getinnformationUser(SQLiteDatabase db) {
String a1="f1";
Cursor cursor;
String[] projections = {Menu.NewMenuInfo.MENU_ID, Menu.NewMenuInfo.MENU_NAME, Menu.NewMenuInfo.MENU_PRICE};
String selection = Menu.NewMenuInfo.MENU_ID + "=" + a1;
cursor=db.query(Menu.NewMenuInfo.TABLE_NAME,projections,selection,null,null,null,null);
return cursor;
}
Menu1.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menuset1);
s_id = (TextView) findViewById(R.id.idSet1);
s_name = (TextView) findViewById(R.id.nameSet1);
s_drink = (TextView) findViewById(R.id.drinkSet1);
s_price = (TextView) findViewById(R.id.priceSet1);
set1 = (Button) findViewById(R.id.buttonOrderSet);
userDbHelper = new UserDbHelper(getApplicationContext());
sqLiteDatabase = userDbHelper.getReadableDatabase();
cursor = userDbHelper.getinnformationSet1(sqLiteDatabase);
if (cursor != null){
cursor.moveToFirst();
String id = cursor.getString(0);
String name = cursor.getString(1);
String drink = cursor.getString(2);
String price = cursor.getString(3);
s_id.setText(id);
s_name.setText(name);
s_drink.setText(drink);
s_price.setText(price);
}
}
}
basically i want to display id,name,drink,price according to id="f1".
example: if id="f1" then display all the information without using any searching or click button.
when i run this coding the application has stopped
You need to pass the selection arguments as an array, but in the selection string you should put ? mark. Change your getinnformationUser method like this:
public Cursor getinnformationUser(SQLiteDatabase db) {
String a1="f1";
Cursor cursor;
String[] projections = {Menu.NewMenuInfo.MENU_ID, Menu.NewMenuInfo.MENU_NAME, Menu.NewMenuInfo.MENU_PRICE};
String selection = Menu.NewMenuInfo.MENU_ID + "= ?";
String[] selectionArgs = new String[] {a1};
cursor=db.query(Menu.NewMenuInfo.TABLE_NAME,projections,selection,selectionArgs,null,null,null,null);
return cursor;
}
You can read more about the query method here.
basically your select query is wrong....its like below
public Cursor getinnformationUser(SQLiteDatabase db) {
String a1="f1";
Cursor cursor;
String[] projections = {Menu.NewMenuInfo.MENU_ID, Menu.NewMenuInfo.MENU_NAME, Menu.NewMenuInfo.MENU_PRICE};
String whereclause = Menu.NewMenuInfo.MENU_ID + "= ?";
String where_args[] = {a1};
cursor=db.query(Menu.NewMenuInfo.TABLE_NAME,projections,whereclause,where_args,null,null,null);
return cursor;
}
Will work perfectly...
Use orderBy. In orderBy pass any value for order the rows for example if you want to order by id then pass id and add limit 1
i.e
cursor=db.query(Menu.NewMenuInfo.TABLE_NAME,projections,selection,null,null,null,"id limit 1");
This will select only one row.
Correction
You can use query() (link provided by Eric B.) also for passing limit as parameter
Related
So, in my app you have to add eletrical equipment to every room in the house so it can measure how much energy you spend and etc.
What I want is when I click the button to remove a specific equipment, that equipment will be deleted from the database where it was stored, and this would be with only the name of the equipment as entry.
I have a code but when I hit the remove button the app kinda crashes and goes back to the home activity.
Can someone help pls?
That's the button:
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
button2.setVisibility(View.GONE);
tableLayout1.setVisibility(View.GONE);
imageView1.setVisibility(View.GONE);
textView12.setVisibility(View.GONE);
DatabaseOperations DOP;
String equipamento;
equipamento = textView12.getText().toString();
DOP = new DatabaseOperations(CTX);
Cursor CR = DOP.getUserInfo(DOP, equipamento);
CR.moveToFirst();
DOP.deleteEquip(DOP, equipamento);
Toast.makeText(getBaseContext(),"O equipamento foi removido com sucesso.", Toast.LENGTH_LONG).show();
}
});
And this is the class:
public Cursor getUserInfo (DatabaseOperations DOP, String equipamento){
SQLiteDatabase SQ = DOP.getReadableDatabase();
String selection = TableData.TableInfo.EQUIPAMENTO +" LIKE ?";
String coloumns[] = {TableData.TableInfo.POTENCIA, TableData.TableInfo.QUANT, TableData.TableInfo.HORAS, TableData.TableInfo.SIMULT};
String args [] = {equipamento};
Cursor CR = SQ.query(TableData.TableInfo.TABLE_NAME, coloumns, selection, args, null, null, null);
return CR;
}
public void deleteEquip(DatabaseOperations DOP, String equipamento){
String selection = TableData.TableInfo.EQUIPAMENTO;
String args[] = {equipamento};
SQLiteDatabase SQ = DOP.getWritableDatabase();
SQ.delete(TableData.TableInfo.TABLE_NAME, selection, args);
}
#EngWatt this code is in the DBHelper Class you will need to change the rowid to reflect the name of the item you want to delete. I assume that is equipamento
We hope you have a MVP design to make all this easy
/* Delete a record from database table named "TABLE_INFO" */
/* based on the selected records id in Col_ID*/
public void deleteDBRow(String rowid){
db = this.getWritableDatabase();
db.delete(TABLE_INFO, Col_ID + " = ?", new String[] { rowid });
db.close();
return;
}
I tried inputting data into a Sqlite database then getting it out to use when I input the data into textViews but when I press the button action it crashes. And I tried looking at where it when wrong in the Onclick and it said "Caused by: java.lang.IllegalArgumentException: column 'Colour' does not exist" but I'm not sure what's wrong.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDbHelper = new CarsDbHelper(this);
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CarsEntry.COLUMN_NAME,current_car_name);
values.put(CarsEntry.COLUMN_COLOUR,current_car_colour);
values.put(CarsEntry.COLUMN_AGE,current_car_age);
long newRowId = db.insert(CarsEntry.TABLE_NAME, null, values);
}
public void button (View view) {
mDbHelper = new CarsDbHelper(this);
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = {
CarsEntry.COLUMN_NAME,
CarsEntry.COLUMN_AGE,
CarsEntry.COLUMN_AGE
};
// Filter results WHERE "title" = 'My Title'
String selection = CarsEntry.COLUMN_NAME + " = ?";
String[] selectionArgs = { current_car_name };
// How you want the results sorted in the resulting Cursor
Cursor cursor = db.query(
CarsEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
);
while(cursor.moveToNext()) {
//Name
current_car_name = cursor.getString(cursor.getColumnIndexOrThrow(CarsEntry.COLUMN_NAME));
//Colour
current_car_colour = cursor.getString(cursor.getColumnIndexOrThrow(CarsEntry.COLUMN_COLOUR));
//Age
current_car_age = cursor.getInt(cursor.getColumnIndexOrThrow(CarsEntry.COLUMN_AGE));
}
cursor.close();
TextView car_name = (TextView) findViewById(R.id.name);
car_name.setText(current_car_name);
TextView car_colour = (TextView) findViewById(R.id.colour);
car_colour.setText(current_car_colour);
TextView car_age = (TextView) findViewById(R.id.age);
car_age.setText(String.valueOf(current_car_age));
}
In projection you have two times COLUMN_AGE and you make select with this column so you don't have on result COLUMN_COLOUR
String[] projection = {
CarsEntry.COLUMN_NAME,
CarsEntry.COLUMN_AGE,
CarsEntry.COLUMN_AGE
};
I wrote a code in which i can retrieve the data from the database but when i run it and try to search something. The application crashes as soon as i press Submit
public class search extends AppCompatActivity {
Button SearchButton;
EditText SearchText;
TextView SearchResult;
SQLiteDatabase db;
String builder;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
SearchButton=(Button)findViewById(R.id.searchbutton);
SearchText=(EditText)findViewById(R.id.Searchtext);
SearchResult=(TextView)findViewById(R.id.SearchCourse);
db=this.openOrCreateDatabase("Courses", Context.MODE_PRIVATE,null);
SearchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int GetID = Integer.valueOf(SearchText.getText().toString());
Cursor TuplePointer = db.rawQuery("Select from Course where ID="+GetID+"",null);
TuplePointer.moveToFirst();
String Course = TuplePointer.getString(TuplePointer.getColumnIndex("Course"));
SearchResult.setText(Course);
}
});
}
}
Replace this line
Cursor TuplePointer = db.rawQuery("Select from Course where ID=" + GetID + "", null);
with
Cursor TuplePointer = db.rawQuery("Select Course from Course where ID=" + GetID + "", null);
Where Course is your column name
Write your code within try catch first. Afterthat try to catch exact exception. you will be clear what are you doing wrong.
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS + " Where " + KEY_APP_BOOKINGID + " = " + id;
Cursor cursor = db.rawQuery(selectQuery, null);
Please Try this
SQLiteDatabase db = this.getReadableDatabase();
String GetID = SearchText.getText().toString();
Cursor cursor = db.rawQuery("SELECT * FROM Course WHERE ID = ?", new String[]{String.valueOf(GetID)}, null);
if (cursor.moveToFirst()) {
do {
String Course = cursor.getString(cursor.getColumnIndex("Course"));
SearchResult.setText(Course);
} while (cursor.moveToNext());
}
Thank You everyone I figured out what i was doing wrong on the get Column index i targeted course but what i didnt realize is that there was no such field as course :)
Keep practice like below code you will debug proper
public void getFirstName(String id) {
String sql = "select first_name from basic_info WHERE contact_id="+ id;
Cursor c = fetchData(sql);
if (c != null) {
while (c.moveToNext()) {
String FirstName = c.getString(c.getColumnIndex("first_name"));
Log.e("Result =>",FirstName);
}
c.close();
}
return data;
}
public Cursor fetchData(String sql) {
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery(sql, null);
}
I have created two string variables, 'questionString' and 'answerSetId' - the first of which I have assigned to a textview - the second of which I would like to pass to my db helper class:
public void showNextRandomQuestion3() {
SQLDatabaseHelper db = new SQLDatabaseHelper(this);
//get the data from the database
List<List<String>> listList = db.getAllAnswersByQuestion1();
//Get the question/text/answer Strings
List<String> questionStrings = listList.get(0); //question Strings
List<String> answerSetIds = listList.get(4);
//Generate random index
Random r = new Random();
int rand = Math.abs((r.nextInt() % questionStrings.size()));
//get answer description for randomly selected question
String questionString = questionStrings.get(rand);
String answerSetId = answerSetIds.get(rand);
questionView.setText(questionString);
}
In my db helper class, I want to use this string variable as pat of my query:
public List<List<String>> getAnswers() {
List<String> array1 = new ArrayList<String>();
List<String> array2 = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_ANSWERS + "WHERE " + ASID
+ " = " + ??answerSetId??;
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
do {
String textdescr = c.getString(c.getColumnIndex(TDESCR));
String answersdescr = c.getString(c.getColumnIndex(ADESCR));
array1.add(textdescr);
array2.add(answersdescr);;
} while (c.moveToNext());
}
List< List<String> > listArray2 = new ArrayList< List<String> >();
listArray2.add(array1);
listArray2.add(array2);
return listArray2;
}
What would be the best way to achieve this?
In order to perform a SELECT, you can use this method
query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
instead of raw query. In your case:
String selection = ASID+"=?";
String selectionArgs[] = new String[]{String.valueOf(answerSetId)};
Cursor c = db.query(TABLE_ANSWERS, null, selection, selectionArgs, null, null, null);
You can also select some specific columns, passing a list of columns name as second parameter (insted of null). Also, you can replace the last three null value in the example for adding the GROUP BY, HAVING and ORDER BY clauses.
For example, in your query you are interested only in the two columns TDESCR and ADESCR. So you could use this query:
String[] columns = new String[]{TDESCR, ADESCR};
String selection = ASID+"=?";
String[] selectionArgs = new String[]{String.valueOf(answerSetId)};
Cursor c = db.query(TABLE_ANSWERS, columns, selection, selectionArgs, null, null, null);
There are a lot of others override methods query. Take a look at the documentation here
However, if you prefer you can perform a raw query in this way:
String queryString = "SELECT * FROM " + TABLE_ANSWERS +
" WHERE "+ASID+"=?";
String[] selectionArgs = new String[]{String.valueOf(answerSetId)};
sqLiteDatabase.rawQuery(queryString, selectionArgs);
I have a page which can retrieve user data from database
but after whole day of trying, I am only able to get the table column name but not the value inside.
this is my code to create database
public static final String LASTLOGIN = "lastuser";
public static final String USER_ID = "suser_id";
public static final String USER_NAME = "suser_name";
public static final String USER_PASSWORD = "spassword";
public static final String PRIME_ID = "id";
private static final String TABLE_USER =
"create table "+ LASTLOGIN+" ("
+PRIME_ID+" integer primary key autoincrement, "
+ USER_ID + " text, "
+ USER_NAME +" text, "
+USER_PASSWORD+" text); ";
and here is the function implemented to get user data
public Cursor getuser()
{
String[] columns = new String[]{PRIME_ID, USER_NAME, USER_PASSWORD};
Cursor cursor = sqLiteDatabase.query(
LASTLOGIN, columns, null, null, null, null, PRIME_ID +" DESC");
Log.d("TAG", columns[1]);
return cursor;
}
and here is my code to display the result
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
cursor = mySQLiteAdapter.getuser();
String[] resultvalue = new String{
SQLiteAdapter.PRIME_ID,SQLiteAdapter.USER_NAME, SQLiteAdapter.USER_PASSWORD};
Toast.makeText(this, resultvalue[0]+resultvalue[1], Toast.LENGTH_LONG).show();
and the toast result only show the column name but not the value inside, is there any mistake i made? and I want to set limit to 1, but where to set it?
Thanks for helping me
the way you try reading the values is completly wrong.
you create an array
String[] resultvalue = new String[]{
SQLiteAdapter.PRIME_ID,
SQLiteAdapter.USER_NAME,
SQLiteAdapter.USER_PASSWORD};
after that you read the values 0 and 1 from this array.
Your toast works absolutly correctly becouse inside this array you define the column names!
If you want to show the values from your query do it this way:
while(cursor.moveToNext()){
Integer str1 = str 1 + cursor.getInteger(1);
String str2 =str2 + cursor.getString(2);
Toast.makeText(this, str1 + str2, Toast.LENGTH_LONG).show();
}
or a better way receiving the correct index:
cursor.getInteger( cursor.getColumnIndex(SQLiteAdapter.PRIME_ID) );
cursor.getString( cursor.getColumnIndex(SQLiteAdapter.USER_NAME) );
Please note when retrieving data from a database, you store it in a Cursor in the memory and hence can only access it using that particular Cursor object, which you have used in the following line of code.
Cursor cursor = mySQLiteAdapter.getuser();
The Following line retrieves the column names and not the values.
String[] resultvalue = new String[]{SQLiteAdapter.PRIME_ID,SQLiteAdapter.USER_NAME, SQLiteAdapter.USER_PASSWORD};
So the following is doing what you have asked it to do, retrieve column names not values
Toast.makeText(this, resultvalue[0]+resultvalue[1], Toast.LENGTH_LONG).show();
You need something like following:
if(cursor.getCount() != 0)
{
while(cursor.moveToNext())
{
resultvalue [0] = csr.getString(0);
resultvalue [1] = csr.getString(1);
//....
}
}
Hope this helps
here is my solution:
final String TABLE_NAME = "table_name";
String selectQuery = "SELECT Column FROM "+TABLE_NAME+" WHERE column='"+some_value+"'";
SQLiteDatabase db = this.openDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] data = new String[cursor.getCount()];;
int i = 0;
if (cursor.moveToFirst()) {
do {
i=Integer.parseInt(cursor.getString(cursor.getColumnIndex("value")));
} while (cursor.moveToNext());
}
cursor.close();