I have a column ShopName, and another column called LocationCode, if the LocationCode equals to "SKP", the corresponding ShopName will be added to an array, my question is, how can I do that?
I got something like this:
public List<String> getQuotes() {
String WhiteFarm = "WhiteFarm";
List<String> list = new ArrayList<>();
Cursor cursor = database.rawQuery("SELECT * FROM WhereToEat WHERE 'LocationCode' = " + WhiteFarm, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
return list;
}
And another class like this:
public class DatabaseGrabber extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.selection_main);
final TextView Shop_name = (TextView)findViewById(R.id.ShopName);
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this);
databaseAccess.open();
final List<String> ShopName = databaseAccess.getQuotes();
databaseAccess.close();
Button StartDraw = (Button)findViewById(R.id.draw_start);
StartDraw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Collections.shuffle(ShopName);
String random = ShopName.get(0);
Shop_name.setText(random);
}
});
}
}
If your LocationCode contains a String (or TEXT for SQLite) type of data then your value should be enclosed in a single quote as shown in the code below:
Cursor cursor = database.rawQuery("SELECT * FROM WhereToEat WHERE LocationCode = " + "'" + WhiteFarm "'", null);
Related
I want to Show all database contents in a List View in Android Studio, I expect to see 3 rows that each row contains "name, family and ID" , but I see a comlex of package name and some other characters as follws:
com.google.www.hmdbtest01.Person#529e71b4
com.google.www.hmdbtest01.Person#529e7238
com.google.www.hmdbtest01.Person#529e7298
if I have more rows in my database, I will see more lines like above in the output.
my codes are as follow:
public class ListOfData extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_data);
ListView list = findViewById(R.id.list1);
HmDbManager01 db= new HmDbManager01(this);
ArrayList personList = db.getAll();
ArrayAdapter<ArrayList> arrayList = new ArrayAdapter<ArrayList>(this,
android.R.layout.simple_list_item_1, personList);
list.setAdapter(arrayList);
}
}
db.getAll() is as follows:
public ArrayList<Person> getAll(){
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor= sqLiteDatabase.rawQuery("SELECT * FROM tbl_person", null);
cursor.moveToFirst();
ArrayList<Person> allData = new ArrayList<>();
if(cursor.getCount() > 0){
while (!cursor.isAfterLast()){
Person p1 = new Person();
p1.pID=cursor.getString(0);
p1.pName=cursor.getString(1);
p1.pFamily=cursor.getString(2);
allData.add(p1);
cursor.moveToNext();
}
}
cursor.close();
sqLiteDatabase.close();
return allData;
}
and, this is Person:
package com.google.www.hmdbtest01;
public class Person {
public String pID;
public String pName;
public String pFamily;
}
Let me know your comments on this problem.
arrayListAdapter will convert your personList to list of string
change like it:
ArrayList<String> persons = new ArrayList<String>();
personList.forEach(personModel -> {
persons.add(personModel.name + " " + personModel.lastName + " " + personModel.id);
});
ArrayAdapter<ArrayList> arrayList = new ArrayAdapter<ArrayList>(this,
android.R.layout.simple_list_item_1, persons);
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 read out data from a database into a String. Now i want to put this String into a textview to show my data in list. I execute the read method and want to show the return string mit the data. Problem is: Android studio cannot resolve the "symbol" aka dbString.
Databasetostring:
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
//Every Column and row
String query = "SELECT * FROM " + TABLE_TODO + " WHERE 1";
//Cursor points to a location in your results
//First row point here, second row point here
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()){
//Extracts first name and adds to string
if(c.getString(c.getColumnIndex("firstName"))!=null){
dbString += c.getString(c.getColumnIndex("firstName"));
c.moveToNext();
/*
* Displaying all other columns
*/
}
}
db.close();
return dbString;
MainActivity:
Button refresh_list;
ToDoDB showDb;
TextView datalist;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datalist = (TextView)findViewById(R.id.showallData);
refresh_list = (Button)findViewById(R.id. refresh_list);
refresh_list.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View view) {
datalist.setText(dbString);
}
});
}
i have a listview .item in listview come from database . the problem is that the item have not arrange in alphabetically order.help me to solve my problem.this is my listview activity code
this is the code of datalist activity.
public class DataListActivity extends Activity {
ListView listView;
SQLiteDatabase sqLiteDatabase;
FoodDbHelper foodDbHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
private Button button1;
ListDataAdapter dataAdapter = null;
Button button;
DataProvider dataProvider;
ArrayList<HashMap<String, String>> namessList;
EditText inputSearch;
String search_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.data_list_layout);
listView = (ListView) findViewById(R.id.list_View);
listDataAdapter = new ListDataAdapter(getApplicationContext(),
R.layout.row_layout) {
#Override
protected void showCheckedButton(int position, boolean value) {
// TODO Auto-generated method stub
DataProvider item = (DataProvider) listDataAdapter
.getItem(position);
Log.i("", "");
item.setSelected(value);
Button myButton = (Button) findViewById(R.id.findSelected);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
responseText
.append("The following dishes were selected...\n");
ArrayList<DataProvider> list = listDataAdapter
.getSelectedIndexes();
int sum = 0;
for (int i = 0; i < list.size(); i++) {
DataProvider dataProvider = list.get(i);
sum = sum + dataProvider.getCalorie();
responseText.append("\n" + dataProvider.getName()
+ " : " + dataProvider.getCalorie()
+ " kcal"
);
}
Toast.makeText(getApplicationContext(), ""+responseText+"\n"+"................................."
+"\n"+"Total Calories In Your Menu Is : " +sum,
Toast.LENGTH_LONG).show();
}
});
}
};
listView.setAdapter(listDataAdapter);
foodDbHelper = new FoodDbHelper(getApplicationContext());
sqLiteDatabase = foodDbHelper.getReadableDatabase();
cursor = foodDbHelper.getInformations(sqLiteDatabase);
if (cursor.moveToFirst()) {
do {
String name, quantity, fat, protein, sugar, vitamins;
boolean selected = false;
String names = null;
Integer calorie;
name = cursor.getString(0);
quantity = cursor.getString(1);
calorie = Integer.valueOf(cursor.getString(2));
fat = cursor.getString(3);
protein = cursor.getString(4);
sugar = cursor.getString(5);
vitamins = cursor.getString(6);
DataProvider dataProvider = new DataProvider(name, quantity,
calorie, fat, protein, sugar, vitamins, names, selected);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
this is dbhelper class
public Cursor getInformations(SQLiteDatabase db){
Cursor cursor;
String[] projections = {Food.NewDishInfo.DISH_NAME,Food.NewDishInfo.DISH_QUANTITY,
Food.NewDishInfo.DISH_CALORIE,Food.NewDishInfo.DISH_FAT,Food.NewDishInfo.DISH_PROTEIN,
Food.NewDishInfo.DISH_SUGAR, Food.NewDishInfo.DISH_VITAMINS};
cursor= db.query(Food.NewDishInfo.TABLE_NAME,projections,null,null,null,null,null);
return cursor;
}
public Cursor getFood(String dish_name,SQLiteDatabase sqLiteDatabase)
{
String[] projections = { Food.NewDishInfo.DISH_QUANTITY, Food.NewDishInfo.DISH_CALORIE, Food.NewDishInfo.DISH_FAT,
Food.NewDishInfo.DISH_PROTEIN, Food.NewDishInfo.DISH_SUGAR, Food.NewDishInfo.DISH_VITAMINS};
String selection = Food.NewDishInfo.DISH_NAME+" LIKE ?";
String[] selection_args = {dish_name};
Cursor cursor = sqLiteDatabase.query(Food.NewDishInfo.TABLE_NAME,projections,selection,selection_args,null,null,null);
return cursor;
}
You have to add order by to your query:
public Cursor getInformations(SQLiteDatabase db){
Cursor cursor;
String[] projections = {Food.NewDishInfo.DISH_NAME,Food.NewDishInfo.DISH_QUANTITY,
Food.NewDishInfo.DISH_CALORIE,Food.NewDishInfo.DISH_FAT,Food.NewDishInfo.DISH_PROTEIN,
Food.NewDishInfo.DISH_SUGAR, Food.NewDishInfo.DISH_VITAMINS};
cursor= db.query(Food.NewDishInfo.TABLE_NAME,projections,null,null,null,null, "column_name ASC");
return cursor;
}
public Cursor getFood(String dish_name,SQLiteDatabase sqLiteDatabase)
{
String[] projections = { Food.NewDishInfo.DISH_QUANTITY, Food.NewDishInfo.DISH_CALORIE, Food.NewDishInfo.DISH_FAT,
Food.NewDishInfo.DISH_PROTEIN, Food.NewDishInfo.DISH_SUGAR, Food.NewDishInfo.DISH_VITAMINS};
String selection = Food.NewDishInfo.DISH_NAME+" LIKE ?";
String[] selection_args = {dish_name};
Cursor cursor = sqLiteDatabase.query(Food.NewDishInfo.TABLE_NAME,projections,selection,selection_args,null,null, "column_name ASC");
return cursor;
}
ASC means ascending and DESC means descending.
I am trying to find the max number in a column of one of the tables in my database.
I thought I had this one sorted (I posted similar question previously), however after some testing I have realised my code isn't working as I thought.
The database consists of a table with the following columns:
_id, inspection_link, area_number, area_reference
I have created the following code in my database helper class:
public static final String AREAS_TABLE = "areas";
public static final String AREA_ID = "_id";
public static final String AREA_NUMBER = "area_number";
public static final String AREA_REF = "area_reference";
public static final String AREA_LINK = "area_link";
public static final String INSPECTION_LINK = "inspection_link";
public Cursor selectMaxAreaNumber (long inspectionId) {
String inspectionIdString = String.valueOf(inspectionId);
String[] tableColumns = new String[] {
AREA_NUMBER,
"(SELECT max(" + AREA_NUMBER + ") FROM " + AREAS_TABLE + ") AS max"
};
String whereClause = INSPECTION_LINK + " = ?";
String[] whereArgs = new String[] {
inspectionIdString
};
Cursor c = rmDb.query(AREAS_TABLE, tableColumns, whereClause, whereArgs,
null, null, null);
if (c != null) {
c.moveToFirst();
}
c.close();
return c;
}
Then in the activity where I want to query the database I have written the following:
public class AreaEdit extends Activity {
private EditText AreaNumber;
private EditText AreaReference;
private Button saveButton;
private Button cancelButton;
protected boolean changesMade;
private AlertDialog unsavedChangesDialog;
private RMDbAdapter rmDbHelper;
private long inspectionId;
private long areaId;
private int nextAreaNumber = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rmDbHelper = new RMDbAdapter(this);
rmDbHelper.open();
Intent i = getIntent();
inspectionId = i.getLongExtra("Intent_InspectionID", -1);
areaId = i.getLongExtra("Intent_AreaID", -1);
if (areaId == -1) {
Cursor c = rmDbHelper.selectMaxAreaNumber(inspectionId);
startManagingCursor(c);
c.moveToFirst();
nextAreaNumber = c.getInt(c.getColumnIndex("max")) + 1;
}
setContentView(R.layout.edit_area);
setUpViews();
populateFields();
setTextChangedListeners();
}
private void setUpViews() {
AreaNumber =(EditText)findViewById(R.id.area_number);
AreaReference =(EditText)findViewById(R.id.area_reference);
saveButton = (Button)findViewById(R.id.area_save_button);
cancelButton = (Button)findViewById(R.id.area_cancel_button);
}
private void populateFields() {
if (areaId > 0) {
Cursor c = rmDbHelper.fetchArea(areaId);
startManagingCursor(c);
c.moveToFirst();
AreaNumber.setText(c.getString(
c.getColumnIndexOrThrow(RMDbAdapter.AREA_NUMBER)));
AreaReference.setText(c.getString(
c.getColumnIndexOrThrow(RMDbAdapter.AREA_REF)));
c.close();
}
else {
AreaNumber.setText(String.valueOf(nextAreaNumber));
}
}
However, when it returns the wrong number - it seems to pick up the maximum number from the whole table which includes data from other inspections.
I guess this may be down to the conversion between Strings and Longs etc maybe, but I have a brickwall with this?
Any help much appreciated.
You can simply try below:
String sql = "SELECT MAX(ColumnNameHere) AS MaxValue FROM myTable WHERE AnotherColumn = 'SomValue'";
Cursor c = db.rawQuery(sql, null);
c.moveToFirst();
c.getInt(c.getColumnIndex("MaxValue"));
Detailed solution to this question found here:
Solution to this detailed in the following post: SELECT statement not returning MAX number
Basically, it was an issue with the query as thought and how I used the cursor.