how to overcome android sqlite where clause problem? - android

I am trying to read data from students table where semester column is equal to an item which is selected from spinner. listener is spinner.setOnItemSelectedListener. the problem is it stops the activity when I select the spinner item.
It runs okay when I remove the WHERE CLAUSE. but I have to use WHERE CLAUSE.
Please Help.
public ArrayList<HashMap<String, String>> GetAllStudents(){
ArrayList<HashMap<String, String>> userList = new ArrayList<>();
try{
SQLiteDatabase db = MyDB.getInstance(this).getReadableDatabase();
String query = "SELECT * FROM Students WHERE semester="+selected;
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()) {
while (cursor.moveToNext()) {
HashMap<String, String> user = new HashMap<>();
user.put("name", cursor.getString(0));
user.put("roll", cursor.getString(1));
user.put("semester", cursor.getString(2));
user.put("pass", cursor.getString(3));
userList.add(user);
}
}
}
catch (Exception e){
Toast.makeText(this, "Error "+selected, Toast.LENGTH_SHORT).show();
}
return userList;
}
EDIT
(code taken from comments to show where selected is comming from)
String selected;
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selected=parent.getItemAtPosition(position).toString();
loadStudents();
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
loadStudents();

I have solved this problem , I just missed ' ' around the selected variable
This is the solution
String query = "SELECT * FROM Students WHERE semester='"+selected+"'";

Related

listview-SQLite updating the wrong row

When I update the selected row it updates the wrong row for example if I select second row, it will update the first row.
Here is my code inside db controller
Public boolean updateContact (String id, String category, String code, String description, String unit, String quantity) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FeedReaderContract.FeedEntry.Col_2 , category);
values.put(FeedReaderContract.FeedEntry.Col_3 , code);
values.put(FeedReaderContract.FeedEntry.Col_4 , description);
values.put(FeedReaderContract.FeedEntry.Col_5 , unit);
values.put(FeedReaderContract.FeedEntry.Col_6 , quantity);
// updating row
database.update(TABLE_NAME ,values , FeedReaderContract.FeedEntry.Col_1 + " = ?" , new String[]{id} );
return true;
}
public ArrayList<HashMap<String, String>> getAllProducts() {
ArrayList<HashMap<String, String>> proList;
proList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM Countsheet";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor != null && cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("Category", cursor.getString(1));
map.put("Code", cursor.getString(2));
map.put("Description", cursor.getString(3));
map.put("Unit", cursor.getString(4));
map.put("Quantity", cursor.getString(5));
proList.add(map);
} while (cursor.moveToNext());
cursor.close();
}
return proList;
}
Here is my button onclick to update the listview:
Public void adddata(){
btnadddata.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v) {
boolean i = myDb.updateContact(passid , passedVar , passcode, passdesc, passunit , quantitys.getText().toString());
if (i == true)
Toast.makeText(Main2Activity.this , "Data Inserted" , Toast.LENGTH_SHORT).show();
else
Toast.makeText(Main2Activity.this , "Data Not Inserted" , Toast.LENGTH_SHORT).show();
}
}
);
}
I think you are missing 'passid' .
put 'passid' in your HashMap while fetching from database and then retrieve.
HEY GUYSSSS THANK YOU FOR ANSWERING I APPRECIATE YOU ALL , I JUST SUDDENLY GOT THE ANSWER WICH IS I JUST ADD 1 TO THE STRING.VALUEOF(ID) AND IT JUST WORKED OUT THANKS YOU GUYSSS!
//here is my code
intent.putExtra(ID_EXTRA1 , String.valueOf(id + 1));
startActivity(intent);

How to set selection in spinner with SimpleAdapter?

I am populating spinner from below code and its working perfect. When user select any value from spinner then I am saving stateCodeId in sqlite. Now what I want that when user come again then I want to show the seleted value from ID which already saved in sqlite. How can I show value selected in spinner ?
public void fillStateData() {
try {
State_data = new ArrayList<Map<String, String>>();
State_data.clear();
Cursor cursor_State = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nCtgId = 6", null);
int i = 0;
if (cursor_State.moveToFirst()) {
do {
Map<String, String> datanum = new HashMap<String, String>();
if (i == 0) {
datanum.put("nStateID", "0");
datanum.put("cStateName", "Select State");
State_data.add(datanum);
datanum = new HashMap<String, String>();
datanum.put("nStateID", cursor_State.getString(0));
datanum.put("cStateName", cursor_State.getString(1));
State_data.add(datanum);
} else {
datanum.put("nStateID", cursor_State.getString(0));
datanum.put("cStateName", cursor_State.getString(1));
State_data.add(datanum);
}
i += 1;
} while (cursor_State.moveToNext());
}
String[] fromwhere = {"nStateID", "cStateName"};
int[] viewswhere = {R.id.txtnStateID, R.id.txtcStateName};
StateAdapter = new SimpleAdapter(getActivity(), State_data, R.layout.state_list_template, fromwhere, viewswhere);
spnState.setAdapter(StateAdapter);
cursor_State.close();
spnState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TextView stateId = (TextView) view.findViewById(R.id.txtnStateID);
stateCodeId = stateId.getText().toString();
fillDistrictData(stateCodeId);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
Like this I am getting ID from sqlite.
Cursor c = db.rawQuery("SELECT nStateId from MemberMaster where nCustID ="+SesPMbrID+"", null);
c.moveToFirst();
String state = c.getString(0);
Use
spinner.setSelection(position);

get id of selected spinner data based from database android

hi i have this spinner dropdown that displays data from my database. In my database, i have this table named area and it has this fields, aid its primary key and location which is a varchar. so far i am successful in displaying the data im my spinner. in my DBHelper this is the code that gets the data from DB
public Set<String> getAllData()
{
Set<String> set = new HashSet<String>();
String selectQuery = "SELECT * FROM " + TABLE_AREA;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
set.add(cursor.getString(1));
} while (cursor.moveToNext());
}
db.close();
return set;
}
then in my addLocation.java here is how i use it to display the data on my spinner
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.addplace);
Spinner spn = (Spinner)findViewById(R.id.areas);
Set<String> aset = db.getAllData();
List<String> aData = new ArrayList<>(aset);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,
aData);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn.setAdapter(spinnerAdapter);
spn.setOnItemSelectedListener(new SpinnerInfo());
}
private class SpinnerInfo implements AdapterView.OnItemSelectedListener {
private boolean isFirst = true;
String selected;
#Override
public void onItemSelected(AdapterView<?> spinner, View selectedView, int selectedIndex, long id)
{
if (isFirst)
{
isFirst = false;
}
else
{
String selection = spinner.getItemAtPosition(selectedIndex).toString();
selected = selection;
}
Toast tempMessage =
Toast.makeText(addLocation.this,
selected,
Toast.LENGTH_SHORT);
tempMessage.show();
}
#Override
public void onNothingSelected(AdapterView<?> spinner) {
// Won’t be invoked unless you programmatically remove entries
}
}
the thing is i needed to get the id of the selected location not the index in the spinner but it's database id. any idea on how i can do this? thanks so much in advance!
i needed to get the id of the selected location not the index in the
spinner but it's database id. any idea on how i can do this?
Do it as using HashMap:
1. Use HashMap instead of Set with location as a key and location id as value. change getAllData() :
public Map<String, Integer> getAllData()
{
Map<String, Integer> hashMap = new HashMap<String, Integer>();
...
if (cursor.moveToFirst()) {
do {
hashMap.put(cursor.getString(1),cursor.getString(0));
} while (cursor.moveToNext());
}
db.close();
return hashMap;
}
2. Pass all keys to Spinner :
Map<String, Integer> hashMap = db.getAllData();
List<String> allLocations = new ArrayList<String>(hashMap.keySet());
3. Now In onItemSelected use selected String to get id of Selected item:
int location_id=hashMap.get(selected);

array adapter is showing field value, not data values from database in android

I am trying to show a listview of data from database in fragments. For that reason I've added a table in database. Now I'm trying to create data adapter. Here is my code:
list=(ListView)rootView.findViewById(R.id.listView1);
try{
DatabaseHandler db = new DatabaseHandler(getActivity());
List<Label> allLabel = db.getAllLabels();
for (Label label : allLabel) {
ArrayAdapter<Label> dataadapter= new ArrayAdapter<Label>(getActivity(),android.R.layout.simple_list_item_1,allLabel);
list.setAdapter(dataadapter);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,View v, int position,long id)
{
Toast.makeText(getActivity(), ((TextView)v).getText(), Toast.LENGTH_LONG).show();
}
});
}
}
catch (Exception e)
{
e.printStackTrace();
}
this is my output of containing field value not data value:
com.qcash.atmlocator.Label#52852d88
com.qcash.atmlocator.Label#52852dd8
com.qcash.atmlocator.Label#52852e08
com.qcash.atmlocator.Label#52852e38
this is the getAllLabels() function used in my code:
public List<Label> getAllLabels(){
List<Label> labels = new ArrayList<Label>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Label label = new Label();
label.setId(cursor.getInt(0));
label.setName(cursor.getString(1));
label.setLatitude(cursor.getDouble(2));
label.setLongitude(cursor.getDouble(3));
labels.add(label);
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
How can I get the database value? please help me out.
Adding cursor data to a string and adding that string to the calling function fragment solved that. Here is the code:
String name=cursor.getString(0)+"\n"+cursor.getString(1)+"\n"+cursor.getString(2)+"\n"+cursor.getString(3);
FindPeopleFragment.ArrayofName.add(name);
Finally showing that array to adapter completes that:
ArrayAdapter<String> dataadapter= new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,ArrayofName);
Override the toString() method in Label class. I am assuming that you class has a variable 'name'.
class Label{
// other variables.
#Override
public String toString() {
return name;
}
}
Update:
Change the onItemclick listener
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,View v, int position,long id)
{
Label label = (Label)parent.getItemAtPosition(position);
Toast.makeText(getActivity(), "" + label.toString(), Toast.LENGTH_LONG).show();
}
});

getting the rowId of an item in the listView from sqlite database

hope you could help me with this problem. i want to get the rowId of a selected item in a listview from sqlite so that i can pass the value to another activity.
i already fed the listview with info from my sqlite table and use onClickedItem in the listview and use pos + 1 to get the id, but i dont want this solution because whenever i delete an item from the listview i wont be able to get the correct rowId from the database itself... this is my code :
in my DBhelper:
public List<String> getSYAList() {
List<String> List = new ArrayList<String>();
try {
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_SYA ;
Cursor c = ourDatabase.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
List.add((c.getString(0)) + " " +(c.getString(1)) + " "+ (c.getString(2)));
} while (c.moveToNext());
}
} catch (Exception e) {
Toast.makeText(ourContext, "Error encountered.",
Toast.LENGTH_LONG).show();
}
return List;
}
in my activity:
private void loadSYA() {
// TODO Auto-generated method stub
final DBhelper entry = new DBhelper(this);
entry.open();
final List<String> sya = entry.getSYAList();
if(sya.size()>0) // check if list contains items.
{
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(SYA.this,android.R.layout.simple_dropdown_item_1line, sya);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
sqlSYA.setAdapter(arrayAdapter);
sqlSYA.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(SYA.this,SYAInfo.class);
Bundle b = new Bundle();
b.putInt("id", (int)position + 1);
i.putExtras(b);
startActivity(i);
}
}); }
else
{
Toast.makeText(SYA.this,"No items to display",1000).show();
}
entry.close();
}
i really hope you anyone could help me to find a solution for this one. thanks in advance guys !!!

Categories

Resources