This is my query in my DatabaseHelper
public List<String> getallstatus(){
List<String> list = new ArrayList<>();
String query = "select * from ref_status";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query,null);
try{
if(cursor.moveToFirst()){
do{
list.add(cursor.getString(0));
list.add(cursor.getString(1));
}while(cursor.moveToNext());
}
cursor.close();
db.close();
}catch(Exception e){
Log.e("onins" , e.getMessage(),e);
}
return list;
}
This is my dataProvider class
public class DataProvider {
private String regcode, regname;
public DataProvider(String regcode, String regname){
this.regcode =regcode;
this.regname = regname;
}
public String getRegcode(){ return regcode; }
public void setRegCode(){ this.regcode = regcode; }
public String getRegname(){ return regname; }
public void setRegname() { this.regname = regname; }
#Override
public String toString(){
return regname;
}
#Override
public boolean equals(Object obj) {
if(obj instanceof DataProvider){
DataProvider c = (DataProvider ) obj;
if(c.getRegname().equals(regname) && c.getRegcode()==regcode )
return true;
}
return false;
}
}
and this is my onCreate in my main activity
db = new DatabaseHelper(getApplicationContext());
List<String> result = db.getallstatus();
//spinner elements
ArrayList<DataProvider> datalist = new ArrayList<>();
ArrayAdapter<DataProvider> adapter = new ArrayAdapter<DataProvider>(this,android.R.layout.simple_spinner_dropdown_item,datalist);
// Drop down layout style - list view with radio button
// adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//attaching adapter to spinner
valueofspin.setAdapter(adapter);
// valueofspin.setSelection(adapter.getPosition(myItem));
I just wanna pass the result of this List result to my array adapter. I'm new in android studio hope somebody can help me. Thanks in advance.
Do this Create a constructor in your Arrayadapter
public class ArrayAdapter extends....{
ArrayList<DataProvider> dataList;
List<String> list;
ArrayAdapter(Context context,resources id,ArrayList<DataProvider>
dataList,List<String> list){
this.context=context;
this.dataList = datalist;
this.list = list
}
}
On your Activity...Do this
ArrayAdapter<DataProvider> adapter = new ArrayAdapter<DataProvider>(this,android.R.layout.simple_spinner_dropdown_item,datalist,result);
Pass result through constructor..
Related
Hello I build a dictionary app in androidstudio
by searching "word" it should show "def" and "desc"
but it does not show the desc value because of HashMap only put one value how can I put two values and show desc value?
my DictObjectModel is
public class DictObjectModel {
String word, def,desc;
public DictObjectModel(String word, String def,String desc){
this.word=word;
this.def = def;
this.desc = desc;
}
public String getWord()
{
return word;
}
public String getDef()
{
return def;
}
public String getDesc() {
return desc;
}
}
And my search Activity is
private static RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;
public static ArrayList<DictObjectModel> data;
DatabaseHelper db ;
ArrayList<String> wordcombimelist;
ArrayList<String> defcombimelist;
ArrayList<String> desccombimelist;
LinkedHashMap<String,String> namelist;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_activity );
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
recyclerView.setHasFixedSize(true);
db= new DatabaseHelper(this);
searchView = (SearchView) findViewById(R.id.searchView);
searchView.setQueryHint("Search Here");
searchView.setQueryRefinementEnabled(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
data = new ArrayList<DictObjectModel>();
fetchData();
searchView.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
searchView.setIconified( false );
}
} );
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {return false; }
#Override
public boolean onQueryTextChange(String newText) {
newText = newText.toLowerCase();
final ArrayList<DictObjectModel> filteredList = new ArrayList<DictObjectModel>();
for (int i = 0; i < wordcombimelist.size(); i++) {
final String text = wordcombimelist.get(i).toLowerCase();
if (text.contains(newText)) {
filteredList.add(new DictObjectModel(wordcombimelist.get(i),defcombimelist.get(i),desccombimelist.get( i )));
}
}
adapter = new CustomAdapter(filteredList);
recyclerView.setAdapter(adapter);
return true;
}
});
}
public void fetchData()
{
db =new DatabaseHelper(this);
try {
db.createDataBase();
db.openDataBase();
}
catch (Exception e)
{
e.printStackTrace();
}
namelist=new LinkedHashMap<>();
int ii;
SQLiteDatabase sd = db.getReadableDatabase();
Cursor cursor = sd.query("content" ,null, null, null, null, null, null);
ii=cursor.getColumnIndex("word");
wordcombimelist=new ArrayList<String>();
defcombimelist= new ArrayList<String>();
desccombimelist= new ArrayList<String>();
while (cursor.moveToNext()){
namelist.put(cursor.getString(ii), cursor.getString(cursor.getColumnIndex("def")));
}
Iterator entries = namelist.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry thisEntry = (Map.Entry) entries.next();
wordcombimelist.add(String.valueOf(thisEntry.getKey()));
defcombimelist.add("- "+String.valueOf(thisEntry.getValue()));
desccombimelist.add("- "+String.valueOf(thisEntry.getValue()));
}
for (int i = 0; i < wordcombimelist.size(); i++) {
data.add(new DictObjectModel(wordcombimelist.get(i), defcombimelist.get(i),desccombimelist.get(i)));
}
adapter = new CustomAdapter(data);
recyclerView.setAdapter(adapter);
}
}
Can anyone suggest how can I fix that?
You need to change the type of namelist from LinkedHashMap<String,String> to LinkedHashMap<String,DictObjectModel>. When you load your data from your database you need to go through each item in cursor, build a DictObjectModel object from it and put the DictObjectModel object in your LinkedHashMap something like namelist.put(cursor.getString(ii), myDictObjectModel). And you'll probably want to rename namelist to dictionary. Hope this helps!
What is the best way to save data read from SQLiteDatabase Android, and access them using row number or column name?
Hi Below is my code that I am using to fetch the data but I want to store the rows in some kind of dataset so that i can fetch the data using column number or name . I want to dynamically show these data in a grid in android.
MyDatabaseSQLHelper myDatabaseSQLHelper = new MyDatabaseSQLHelper(this);
SQLiteDatabase mySQLiteDatabase = myDatabaseSQLHelper.getReadableDatabase();
String[] projection = {
Items._ID,
Items.COL_ITEM_NAME,
Items.COL_ITEM_PRICE,
Items.COL_ITEM_QUANTITY,
Items.COL_ITEM_AMOUNT
};
Cursor cursor = mySQLiteDatabase.query(Items.TABLE_NAME,projection,null,null,null,null,null);
To store all rows fetch from database you can store it in Array list of type modal class. for you your modal class could be like this
ItemBeen.java
public class ItemBeen {
String id,itemName,itemPrice,itemQty,itemAmount;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemPrice() {
return itemPrice;
}
public void setItemPrice(String itemPrice) {
this.itemPrice = itemPrice;
}
public String getItemQty() {
return itemQty;
}
public void setItemQty(String itemQty) {
this.itemQty = itemQty;
}
public String getItemAmount() {
return itemAmount;
}
public void setItemAmount(String itemAmount) {
this.itemAmount = itemAmount;
}
}
then now in your class make method for get data from database and it store all record to array list and return that array list , like this.
public ArrayList<ItemBeen> getItemList() {
Cursor cur;
ArrayList<itemBeen> itemList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
cur = db.query(Items.TABLE_NAME.TBL_ITEM, projection, null, null, null, null, null);
if (cur != null) {
if (cur.moveToFirst()) {
do {
ItemBeen bean = new ItemBeen();
bean.setId(cur.getString(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ID)));
bean.setItemName(cur.getString(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ITEM_NAME)));
bean.setItemPrice(cur.getBlob(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ITEM_PRICE)));
bean.setItemQty(cur.getString(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ITEM_TQY)));
bean.setItemAmount(cur.getInt(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ITEM_AMT)));
itemList.add(bean);
} while (cur.moveToNext());
}
}
return itemList;
}
Now in that class in which you want all item list in that class call this method.declare array list and fetch data.
ArrayList<ItemBeen> itemList = new ArrayList<ItemBeen>();
itemList = DBConstant.dbHelper.getItemList();
and this way in itemList contains all records.
I am making small app. It has 2 listview on MainActivity.
DB is SQLLite and has tree cloumns id(int), person(text), status(text).
Firt listview will be show informations from DB with this query
select * from DB where status=B
And next ListView will show information where status=A.
lv1.status=b | lv2.status=a
Person 1 | Person 2
Person 3 | Person 4
When i click lv2 on item, value of clicked lv2 field 'status' must change to 'b'.
But I can not write right query for db.
public void changeUser(){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STATUS, "B");
db.update(TABLE_ORDER, values, null, null);
db.close();
}
Thanks
Here is my code
lvB = (ListView)findViewById(R.id.lvB);
listClientB();
lvA = (ListView)findViewById(R.id.lvA);
listClientA();
lvA.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
User user = (User)adapterView.getAdapter().getItem(i);
int id = user.get_id();
if (user.getStatus().contains("A")){
dbHelper.changeUser();
}
Toast.makeText(getApplicationContext(), id + "-NUMBER id", Toast.LENGTH_LONG).show();
Log.d(String.valueOf(user.get_id()), "-NUMBER id");
listClientA();
Log.d(user.getStatus(), "Pressed");
}
});
}
private void listClientA(){
list = dbHelper.allUsersA();
klientStatusAdapter = new KlientStatusAdapter(MainActivity.this, list);
lvA.setAdapter(klientStatusAdapter);
lvA.setTextFilterEnabled(true);
}
private void listClientB(){
list = dbHelper.allUsersB();
klientStatusAdapter = new KlientStatusAdapter(MainActivity.this, list);
lvB.setAdapter(klientStatusAdapter);
lvB.setTextFilterEnabled(true);
}
Here is from DB
public List<User> allUsersA(){
db = this.getReadableDatabase();
List<User> users = new ArrayList<User>();
String s = "select * from " + TABLE_ORDER + " where status = 'A'";
Cursor cursor = db.rawQuery(s, null);
if (cursor.moveToFirst()){
do {
User user = new User();
user.set_id(Integer.parseInt(cursor.getString(0)));
user.setClientName(cursor.getString(1));
user.setCleintOrderedFood(cursor.getString(2));
user.setStatus(cursor.getString(3));
users.add(user);
}while (cursor.moveToNext());
}
db.close();
return users;
}
public List<User> allUsersB(){
db = this.getReadableDatabase();
List<User> users = new ArrayList<User>();
String s = "select * from " + TABLE_ORDER + " where status = 'B'";
Cursor cursor = db.rawQuery(s, null);
if (cursor.moveToFirst()){
do {
User user = new User();
user.set_id(Integer.parseInt(cursor.getString(0)));
user.setClientName(cursor.getString(1));
user.setCleintOrderedFood(cursor.getString(2));
user.setStatus(cursor.getString(3));
users.add(user);
}while (cursor.moveToNext());
}
db.close();
return users;
}
public void changeUser(){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STATUS, "B");
db.update(TABLE_ORDER, values, null, null);
db.close();
}
Here is adapter
public class ClientStatusAdapter extends BaseAdapter{
LayoutInflater inflater;
Context context;
List<User> wordsList;
DbHelper dbHelper;
public ClientStatusAdapter(Context context1, List<User> wordsList) {
this.context = context1;
this.wordsList = wordsList;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
dbHelper = new DbHelper(context);
}
#Override
public int getCount() {
return wordsList.size();
}
#Override
public Object getItem(int i) {
return wordsList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null){
view = inflater.inflate(R.layout.kliyent_status_adapter, null);
}
TextView txtIsmAdapter = (TextView)view.findViewById(R.id.txtIsmAdapter);
TextView txtOvqatAdapter = (TextView)view.findViewById(R.id.txtOvqatAdapter);
final User user = wordsList.get(i);
TextView txtCliyentNames = (TextView)view.findViewById(R.id.txtCliyentNames);
txtCliyentNames.setText(user.getClientName());
TextView txtCliyentOrderedFoood = (TextView)view.findViewById(R.id.txtCliyentOrderedFoood);
txtCliyentOrderedFoood.setText(user.getCleintOrderedFood());
TextView txtStatusAdapter = (TextView)view.findViewById(R.id.txtStatusAdapter);
txtStatusAdapter.setText(user.getStatus());
notifyDataSetChanged();
ImageView imgOn = (ImageView) view.findViewById(R.id.imgOn);
return view;
}
}
Here is entity User
public class User {
private int _id;
private String clientName;
private String cleintOrderedFood;
private String status = "A";
public User() {
}
public User(int _id, String clientName, String cleintOrderedFood) {
this._id = _id;
this.clientName = clientName;
this.cleintOrderedFood = cleintOrderedFood;
}
public User(int _id, String clientName, String cleintOrderedFood, String status) {
this._id = _id;
this.clientName = clientName;
this.cleintOrderedFood = cleintOrderedFood;
this.status = status;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getCleintOrderedFood() {
return cleintOrderedFood;
}
public void setCleintOrderedFood(String cleintOrderedFood) {
this.cleintOrderedFood = cleintOrderedFood;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
If you look closely at the SQLiteDatabase.update() method, you will see it is declared as
int update (String table,
ContentValues values,
String whereClause,
String[] whereArgs)
Note the last two parameters. These are how you select which rows to update. For example, you can specify to only update rows with a given id:
public void changeUser(int userId){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STATUS, "B");
String whereClause = "_id = ?";
String where = new String[] {Integer.toString(userId)};
db.update(TABLE_ORDER, values, whereClause, where);
db.close();
}
Here I am assuming you use the conventional column name _id. Of course, you can change this to suit your needs if you have a different column name.
Note that you will now need to pass a parameter to changeUser(). However, you have not shown how nor where you currently call it, so I am unable to provide any advice how to change this.
I did some changes in my code and it runs but I didn't get appropriate output. I create a method.
public void fetchData() {
dbHandler = new CourseDbHandler(this,null,null,1);
List<CreateCourse> course_data = dbHandler.getdata();
String[] data = new String[course_data.size()];
int i=0;
for(CreateCourse co : course_data)
{
data[i] = co.getCourseSelected();
i++;
}
courseList = (ListView) findViewById(R.id.CourselistView);
courseAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
courseList.setAdapter(courseAdapter);
courseAdapter.notifyDataSetChanged();
}
in this method i used dbHandler.getdata method, which is as follows
public List<CreateCourse> getdata() throws NullPointerException {
String dbString = "";
String course;
String sec;
List<CreateCourse> list = new ArrayList<>();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_COURSE +";";
Cursor c = db.rawQuery(query,null);
c.moveToFirst();
if(c.equals(null)){
System.out.println("NO DATA");
return null;
}
else {
do {
course = c.getString(1);
sec = c.getString(2);
dbString = course+" "+sec;
CreateCourse co = new CreateCourse();
co.setCourseSelected(dbString);
list.add(new CreateCourse(c.getString(1), c.getString(2)));
}while (c.moveToNext());
}
db.close();
return list;
}
These are the getter and setter method
public void setCourseSelected(String courSelected) {
courseSelected = courSelected;
}
public String getCourseSelected() {
System.out.println(courseSelected);
return courseSelected;
}
It gives an error unfortunately app has stopped.
Create a class with your data:
public class Course {
public String id;
public String course;
public String sec;
public Course (String id, String course, String sec) {
this.id = id;
this.course = course;
this.sec = sec;
}
Then modify your method to return List of your data:
public List<Course> getdata() throws NullPointerException {
List<Course> list = new ArrayList<>();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_COURSE +";";
Cursor c = db.rawQuery(query,null);
c.moveToFirst();
if(c.equals(null)){
System.out.println("NO DATA");
return null;
}
else {
do {
list.add(new Course(c.getString(0), c.getString(1), c.getString(2)));
}while (c.moveToNext());
}
db.close();
return list;
}
Then you can use this List with ArrayAdapter to show your data in ListView.
I changed all the code and solve my problem in above code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_course);
dbHandler = new CourseDbHandler(this, null, null, 1);
Cursor c = dbHandler.getData();
c.moveToFirst();
// System.out.println("Select");
if(c.equals(null)){
System.out.println("NO DATA");
}
else {
if(c.moveToFirst()) {
do {
dbString=null;
course = c.getString(1);
sec = c.getString(2);
dbString = course + " " + sec;
courseItem.add(dbString);
} while (c.moveToNext());
}
}
courseList = (ListView) findViewById(R.id.CourselistView);
courseAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, courseItem);
courseList.setAdapter(courseAdapter);
courseAdapter.notifyDataSetChanged();
}
Thank you for your help..
I am newbie in Android, so I can not estimate how do I save data in database(SQLite) that were got from httprequest through Json.
Here is my code:
final ArrayList<HashMap<String, String>> mylist4 = new ArrayList<HashMap<String, String>>();
try{
JSONObject jObj = new JSONObject(rfiItems);
JSONArray data4 = jObj.getJSONArray("data");
//data4 = json4.getJSONArray("data");
//Toast.makeText(getApplicationContext(), data4.toString(), Toast.LENGTH_LONG).show();
for(int i=0;i<data4.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = data4.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("rfi_data1", "" + e.getString("item_type"));
map.put("rfi_data2", "" + e.getString("change_number"));
map.put("rfi_data3", "" + e.getString("to_vendor"));
map.put("rfi_data4", "" + e.getString("status"));
map.put("rfi_data5", "" + e.getString("title"));
map.put("rfi_data6", "" + e.getString("change_date"));
map.put("rfi_data7", "" + e.getString("responded_date"));
mylist4.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter4 = new SimpleAdapter(this, mylist4 , R.layout.item_list4,
new String[] { "rfi_data1", "rfi_data2","rfi_data3", "rfi_data4","rfi_data5","rfi_data6","rfi_data7"},
new int[] { R.id.rfi_item_type, R.id.rfi_change_no,R.id.rfi_to_vendor,R.id.rfi_status,R.id.rfi_title,R.id.rfi_change_date,R.id.rfi_responded_date });
setListAdapter(adapter4);
Any help will really be appreciated. THANKS
DataBean.java class create for getter and setter method
public class DataBean {
private String item_type = null;
private String change_number = null;
public String getItem_type() {
return item_type;
}
public void setItem_type(String itemType) {
item_type = itemType;
}
public String getChange_number() {
return change_number;
}
public void setChange_number(String changeNumber) {
change_number = changeNumber;
}
}
in your Activity class..set value in object and insert into database
private DatabaseHelper mDbHelper;
DataBean dataBean;
private Cursor mNotesCursor;
private NewsCursorAdapter adapter = null;
mDbHelper = new DatabaseHelper(this);
ArrayList<DataBean> liststck = new ArrayList<DataBean>();
for(int i=0;i<data4.length();i++){
JSONObject e = data4.getJSONObject(i);
dataBean = new DataBean();
dataBean.setChange_number(e.getString("eqid"));
dataBean.setItem_type(e.getString("magnitude"));
liststck.add(dataBean);
}
mDbHelper.deleteRecords();
for (DataBean dataBean : liststck) {
mDbHelper.insertdata(dataBean);
}
mNotesCursor = mDbHelper.retrievedata();
startManagingCursor(mNotesCursor);
adapter.changeCursor(mNotesCursor);
adapter.notifyDataSetChanged();
you must create NCursorAdapter class for dispay result(like custom listview).
here data.xml file is your custom layout. which content two textview.... "key_no" and "key_item" your database table column name...
public class NCursorAdapter extends CursorAdapter {
private Cursor mCursor;
private Context mContext;
private final LayoutInflater mInflater;
public NCursorAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
mInflater = LayoutInflater.from(context);
mContext = context;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// TODO Auto-generated method stub
TextView title = (TextView) view.findViewById(R.id.title);
title.setText(cursor.getString(cursor.getColumnIndex("key_no")));
TextView date = (TextView) view.findViewById(R.id.date);
date.setText(cursor.getString(cursor.getColumnIndex("key_item")));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
final View view = mInflater.inflate(R.layout.data, parent, false);
return view;
}
}
in your database class insert data and retrieve data
public Long insertdata(DataBean dataBean) {
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_NO, dataBean.getChange_number());
contentValues.put(KEY_ITEM, dataBean.getItem_type());
return sqliteDatabase.insert(DATABASE_TABLE, null, contentValues);
}
public Cursor retrievedata() {
return sqliteDatabase.query(DATABASE_TABLE, new String[] { KEY_ROWID,KEY_NO, KEY_ITEM }, null,null);
}
I hope it is useful for your application.