I am retrieving data from sqlite to base adapter by cursor.
main.java
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c=db.rawQuery("select * from budget",null);
while (c.moveToNext()) {
String tes0 = Integer.toString(c.getInt(c.getColumnIndex("_id")));
String tes1 = Double.toString(c.getDouble(c.getColumnIndex("material_actual")));
tes2 = c.getString(c.getColumnIndex("start_date"));
tes3 = c.getString(c.getColumnIndex("end_date"));
String[] v0 = new String[] { tes0 };
String[] v01 = new String[] { tes1 };
String[] v02 = new String[] { tes2 };
String[] v03 = new String[] { tes3 };
Adapter_ListView adapter = new Adapter_ListView(getBaseContext(),
v01, v02 , v03, theTotal); //string[]
TaskList.setAdapter(adapter);
}
Then, Adapter_listView.java
public class Adapter_ListView extends BaseAdapter {
private int count;
private Context context;
private String[] string1;
private String[] string2;
private String[] string3;
private String con1;
private String con2;
private String con3;
public Adapter_ListView(Context baseContext, String[] v01, String[] v02, String[] v03, int theTotal) {
this.count = theTotal;
this.context = baseContext;
this.string1 = v01;
this.string2 = v02;
this.string3 = v03;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return count;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View contentView, ViewGroup arg2) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
contentView = inflater.inflate(R.layout.layout_inflate_list2, null);
TextView title = (TextView)contentView.findViewById(R.id.inflate_title);
TextView body = (TextView)contentView.findViewById(R.id.inflate_body);
TextView sub = (TextView)contentView.findViewById(R.id.inflate_sub);
title.setText(string1[position]);
body.setText(string2[position]);
sub.setText(string3[position]);
return contentView;
}
}
from this code always error --> ArrayOuOfBound if execute this code
title.setText(string1[position]);
how i can solve it?
You need to open your database in the activity you retrieve or insert data into your SQLite database. Also make sure you close it when your finished.
final DatabaseHelper m = new DatabaseHelper(this);
m.open();
In your onDestroy or pause. Call
m.close();
This may be the issue, because i dont see where you open your database in the code.
EDIT :
In your DatabaseHelper class. Create a method.
public void open(){
db.open();
}
public void close(){
db.close()
}
Then you will have the method to close and open the database in your activities where you need to insert and retrieve information.
To retrive data from cursor, first you must go to first row data in cursor.
Some code like this:
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c=db.rawQuery("select * from budget",null);
if (c!=null) c.moveToFirst();
while (c.moveToNext()) {
...
}
good luck!! :D
It seems you want to load resultset into list, if so please change your code to set adapter outside of loop:
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c=db.rawQuery("select * from budget",null);
int theTotal=c.getCount();
String[] v0 = new String[theTotal];
String[] v01 = new String[theTotal];
String[] v02 = new String[theTotal];
String[] v03 = new String[theTotal];
int i=0;
if (c!=null) c.moveToFirst();
while (c.moveToNext()) {
String tes0 = Integer.toString(c.getInt(c.getColumnIndex("_id")));
String tes1 = Double.toString(c.getDouble(c.getColumnIndex("material_actual")));
tes2 = c.getString(c.getColumnIndex("start_date"));
tes3 = c.getString(c.getColumnIndex("end_date"));
v0[i] =tes0 ;
v01[i] = tes1 ;
v02[i] = tes2 ;
v03[i] = tes3 ;
}
Adapter_ListView adapter = new Adapter_ListView(getBaseContext(),
v01, v02 , v03, theTotal); //string[]
TaskList.setAdapter(adapter);
Try this:
main.java
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c=db.rawQuery("select * from budget",null);
if(c.getCount()>0)
{
int i=0;
int clength=c.getCount();
String[] v0=new String[clength];
String[] v1=new String[clength];
String[] v2=new String[clength];
String[] v3=new String[clength];
while (c.moveToNext())
{
String tes0 = Integer.toString(c.getInt(c.getColumnIndex("_id")));
String tes1 = Double.toString(c.getDouble(c.getColumnIndex("material_actual")));
tes2 = c.getString(c.getColumnIndex("start_date"));
tes3 = c.getString(c.getColumnIndex("end_date"));
v0[i]=tes0;
v01[i]=tes1;
v01[i]=tes2;
v01[i]=tes3;
i++;
}
Adapter_ListView adapter = new Adapter_ListView(getBaseContext(),v01, v02 , v03, theTotal); //string[]
TaskList.setAdapter(adapter);
}
Related
I have created custom autocompletetextview component.In that I have also created a populateList method for autocompletetext data.
final com.example.admin.ctronhot.autocomleteclass autocomplete=(com.example.admin.ctronhot.autocomleteclass)findViewById(R.id.abc);
final String sql="select * from g101 where desc LIKE '%" + autocomplete.getText().toString() + "%'";
final String[] mfieldsa=new String[]{"desc"};
final int[] mobjectsa=new int[]{R.id.desc};
autocomplete.populateList(R.layout.brow_g101_layout, sql, "desc", aa, mfieldsa, mobjectsa, order.this);
It is showing drop down data but it is not filtering data as per typed in autocomplete.getText.toString()
Here is my function populateList
public void populateList(Integer _layoutfile, final String sqlaa, String mfieldget, com.example.admin.ctronhot.autocomleteclass mauto,
String[] mfields, int[] mobjects, Context mcontext) {
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(co.mcurd_data_path_, null);
Cursor cursor = db.rawQuery(sqlaa null);
int layoutResourceId = 0;
final SimpleCursorAdapter adapter = new SimpeCursorAdapter(
mcontext, // Context
_layoutfile, // Row layout template
cursor, // cursor (set of DB records to map)
mfields, // DB Column names
mobjects // View IDs to put information in
, layoutResourceId
);
adapter.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {
#Override
public CharSequence convertToString(Cursor cursor) {
final int colIndex = cursor.getColumnIndexOrThrow("desc");
return cursor.getString(colIndex);
}
});
adapter.setFilterQueryProvider(new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence description) {
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(co.mcurd_data_path_, null);
Cursor managedCursor = db.rawQuery(sqlaa, null);
return managedCursor;
}
});
mauto.setThreshold(1);
mauto.setAdapter(adapter);
}
Please help Me.
Thanks in advance.
i need your help, i did display data in a list view but the problem is that i
want the data to be according to a specific value, that means if the id = 1, only the rows
concerned will be displayed, if you have any suggestions i would be very thankful :
here the code of :
public class MainActivity extends ListActivity {
private static final int FLAG_REGISTER_CONTENT_OBSERVER = 2;
private Cursor cursor;
SimpleCursorAdapter adapter = null;
Cursor c;
DBAdapter db = new DBAdapter(this);
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db.open();
populateListViewFromDB();
} catch (Exception e) {
Log.e("ERROR", "Error occured: " + e.toString());
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
private void populateListViewFromDB() {
Cursor cursor = db.getAllRecords();
startManagingCursor(cursor);
String[] databaseColumnNames = new String[] { DBAdapter.col_region, };
int[] toViewIDs = new int[] { R.id.text };
SimpleCursorAdapter myCursordapter = new SimpleCursorAdapter(this,R.layout.activity_main, cursor, databaseColumnNames, toViewIDs,FLAG_REGISTER_CONTENT_OBSERVER);
ListView list = (ListView) findViewById(android.R.id.list);
And my DBAdapter is :
private static final String MENAGE = "table_MENAGE";
public static final String _id = "Num_du_Questionnaire";
public Cursor getAllRecords() {
return db.query(MENAGE, new String[] { _id, col_region,
}, null, null, null,
null, null);
}
list.setAdapter(myCursordapter);
} }
As you may check in query documentation, function accepts a selection and selectionArgs parameters, corresponding to SQL WHERE clause.
So, to make a query limited to a specific id, just use:
db.query(MENAGE, new String[] { _id, col_region}, "id = ?", new String[] {_id}, null, null, null);
I will show data which is in sqlite db to spinner. Showing is easy but I can't retrieve the datas that I added to db.Here is my codes;
public class MainActivity extends Activity {
private Spinner spinner;
private SQLiteDBOlustur sqlnesne;
private SQLiteDatabase db;
private ContentValues cv;
private Cursor cursor;
private ArrayList<String> arr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinnerIller);
arr = new ArrayList<String>();
veriEkle();
db = sqlnesne.getReadableDatabase();
cursor = db.rawQuery("select * from iller", null);
if (cursor.moveToFirst()) {
do {
arr.add(cursor.getString(cursor.getColumnIndex("adsoyad")));
} while (cursor.moveToPrevious());
}
for (int i = 0; i < arr.size(); i++) {
System.out.println(arr.get(i));
}
}
Only I can see the last added data.So how to get all of data in my sqlite db?
Also these are adding data method.
private void veriEkle() {
sqlnesne = new SQLiteDBOlustur(getApplicationContext());
db = sqlnesne.getWritableDatabase();
cv = new ContentValues();
cv.put("il_adi", "Yalova");
cv.put("il_adi", "Karabük");
cv.put("il_adi", "Kilis");
cv.put("il_adi", "Osmaniye");
cv.put("il_adi", "Düzce");
try {
db.insert("iller", null, cv);
Toast.makeText(getApplicationContext(), "Veriler eklendi!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
Try replacing cursor.moveToPrevious() with cursor.moveToNext() so that you step forward through the cursor rather than back.
if (cursor != null && cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
arr.add(cursor.getString(cursor.getColumnIndex("adsoyad")));
cursor.moveToNext();
}
}
cursor.close();
Try this way!!
Try this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinnerIller);
arr = new ArrayList<String>();
veriEkle();
String Table_Name="name of table";
String selectQuery = "SELECT * FROM " + Table_Name;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] data = null;
if (cursor.moveToFirst()) {
do {
// get the data into array,or class variable
// process your data here.
} while (cursor.moveToNext());
}
}
Hope it will help you.
I have retrieved data and successfully shown it in text view.
What do I have to modify in my code to make it look like a list view?
And also how do modify my listview programatically(adding size and padding)?
Here is a part of my DBclass in selecting the items that I've displayed
getFAData() {
// TODO Auto-generated method stub
String [] columns = new String[]{Row_Name};
Cursor c = ourDB.query(db_Table, columns, null, null, null, null, null);
String res = "";
int iRow = c.getColumnIndex(Row_Name);
//int iDesc = c.getColumnIndex(Row_Desc);
//int iID = c.getColumnIndex(Row_id);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
{
res = res + c.getString(iRow) + "\n";
}
return res;
}
And here is the class file:
public class FirstAid extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.firstaid);
displayresult();
}
public void displayresult (){
TextView tvFa = (TextView) findViewById(R.id.tvFA);
tvFa.setMovementMethod(new ScrollingMovementMethod());
DbHelper tblFa = new DbHelper(this);
tblFa.open();
String result = tblFa.getFAData();
tblFa.close();
tvFa.setText(result);
}
}
Create ArrayList int the get data function of database
public ArrayList<String> getFAData() {
ArrayList<String> comments = new ArrayList<String>();
Cursor c = ourDB.query(db_Table, columns, null, null, null, null, null);
int iRow = c.getColumnIndex(Row_Name);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
comments.add(c.getString(iRow ));
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return comments;
}
in your activity retrieve data like this.
ArrayList<String> array = new ArrayList<String>();
array = tblFa.getFAData();
you need to implement a method in your dbhelper class like this
public List<String> selectAll_data() {
List<String> list = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME_2, new String[] { "str" },
null , null, null, null, null);
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
Now in your activity
List<String> events = dh.selectAll_data();
String[] arr = new String[events.size()];
arr = events.toArray(arr);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
If you want to see a real time example check this url
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.