How can I solve this problem would in android ?
07-07 14:44:58.122: E/CursorWindow(12281): Could not allocate CursorWindow '/storage/emulated/0/Android/data/com.example.mytestlistview/Mafatih/Mafatih.db' of size 2097152 due to error -12.
I create a SearchBox on a DB that it is 10MB .That show the results of search on ListView but get me this error.
My StructNote.java :
public class StructNote {
public String Title;
public String Comment;
public StructNote(String Title,String Comment)
{
super();
this.Title = Title;
this.Comment = Comment;
}
public String getTitle()
{
return Title;
}
public String getComment()
{
return Comment;
}
}
My MainActivity.java :
public class MainActivity extends ActionBarActivity {
public static final String DIR_SDCARD = Environment
.getExternalStorageDirectory().getAbsolutePath();
public static final String DIR_DATABASE = DIR_SDCARD + "/Android/data/";
public ArrayList<StructNote> notes = new ArrayList<StructNote>();
public ArrayAdapter adapter;
public String Titel_Drawer;
public Integer titleID;
public Cursor cursorid;
public ArrayList<String> array;
public static String PACKAGE_NAME;
EditText editText;
DB db = new DB(MainActivity.this);
public Cursor cursor;
public SQLiteDatabase sql;
public ListView lstContent;
int selectedId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PACKAGE_NAME = getApplicationContext().getPackageName();
File file = new File(DIR_DATABASE + PACKAGE_NAME + "/Mafatih");
file.mkdirs();
db.GetPackageName(PACKAGE_NAME);
db.CreateFile();
try {
db.CreateandOpenDataBase();
} catch (IOException e) {
e.printStackTrace();
}
sql = db.openDataBase();
final ListView lstContent = (ListView) findViewById(R.id.lstContent);
adapter = new AdapterNote(notes);
lstContent.setAdapter(adapter);
editText = (EditText) findViewById(R.id.search);
editText.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
if (editText.getText().length() < 2) {
Toast.makeText(MainActivity.this, "Please enter more text !", Toast.LENGTH_SHORT).show();
return true;
}
else
{
populateListView(editText.getText());
return true;
}
}
else if(keyCode == KeyEvent.KEYCODE_DEL) {
adapter.clear();
return false;
}
return false;
}
});
final RadioGroup radioGroup = (RadioGroup) findViewById(R.id.Language);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
selectedId = radioGroup.getCheckedRadioButtonId();
Log.i("xxx", String.valueOf(selectedId));
}
});
}
public void populateListView(Editable editable) {
if(selectedId == 2131034177)
{
try {
cursor = sql.rawQuery(
"SELECT * FROM WebSite_MetaDataDBBack WHERE Comment LIKE '"
+"%"+ editable + "%'", null);
array = new ArrayList<String>();
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
StructNote note = new StructNote(Titel_Drawer, Titel_Drawer);
note.Comment = cursor.getString(cursor
.getColumnIndex("Comment"));
titleID = cursor.getInt(cursor
.getColumnIndex("CategoryID"));
cursorid = sql.rawQuery(
"SELECT Title FROM WebSite_CategoryBack WHERE CategoryID ="
+ titleID, null);
if (cursorid != null) {
do {
cursorid.moveToFirst();
note.Title = cursorid.getString(cursorid
.getColumnIndex("Title"));
} while (cursorid.moveToNext());
}
notes.add(note);
} while (cursor.moveToNext());
}
adapter.notifyDataSetChanged();
cursor.close();
}
} catch (Exception e) {
Log.i("xxx", "You have an error");
}
}
else if(selectedId == 2131034176)
{
try {
cursor = sql.rawQuery(
"SELECT Tafsir,CategoryID FROM WebSite_MetaDataDBBack WHERE Tafsir LIKE '"
+"%"+ editable + "%'", null);
array = new ArrayList<String>();
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
StructNote note = new StructNote(Titel_Drawer, Titel_Drawer);
note.Comment = cursor.getString(cursor
.getColumnIndex("Tafsir"));
titleID = cursor.getInt(cursor
.getColumnIndex("CategoryID"));
cursorid = sql.rawQuery(
"SELECT Title FROM WebSite_CategoryBack WHERE CategoryID ="
+ titleID, null);
if (cursorid != null) {
do {
cursorid.moveToFirst();
note.Title = cursorid.getString(cursorid
.getColumnIndex("Title"));
} while (cursorid.moveToNext());
}
notes.add(note);
} while (cursor.moveToNext());
}
adapter.notifyDataSetChanged();
cursor.close();
}
} catch (Exception e) {
Log.i("xxx", "You have an error");
}
}
}
}
My AdapterNote.java :
public class AdapterNote extends ArrayAdapter<StructNote> {
public AdapterNote(ArrayList<StructNote> array) {
super(G.context, R.layout.dapter_notes, array);
}
public static class ViewHolder {
public TextView txtTitle;
public TextView txtDescription;
public ViewHolder(View view) {
txtTitle = (TextView) view.findViewById(R.id.txtTitle);
txtDescription = (TextView) view.findViewById(R.id.txtDescription);
}
public void fill(ArrayAdapter<StructNote> adapter, StructNote item,
int position) {
txtTitle.setText(item.Title);
txtDescription.setText(item.Comment);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
StructNote item = getItem(position);
if (convertView == null) {
convertView = G.inflater.inflate(R.layout.dapter_notes, parent,
false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.fill(this, item, position);
return convertView;
}
}
My G.java :
public class G extends Application{
public static Context context;
public static LayoutInflater inflater;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
}
And this is my Db.java for DB :
public class DB extends SQLiteOpenHelper{
public static final String DIR_SDCARD =Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String DIR_DATABASE = DIR_SDCARD +"/Android/data/";
private static String DB_NAME = "Mafatih.db";
private final Context myContext;
public static String PACKAGE_NAME;
public boolean flag = false;
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DIR_DATABASE +PACKAGE_NAME+"/Mafatih/"+ DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
try{
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
}
catch (IOException e) {
Log.e("Copy", e.toString());
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
checkDB = SQLiteDatabase.openDatabase(DIR_DATABASE +PACKAGE_NAME+ "/Mafatih/" + DB_NAME, null, 0);
}catch(SQLiteException e){
Log.e("asdf", "checkDataBase-->"+e.toString());
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
#Override
public synchronized SQLiteDatabase getReadableDatabase() {
return super.getReadableDatabase();
}
public DB(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
public void CreateandOpenDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
}
else
{
try {
copyDataBase();
}
catch (IOException e) {
throw new Error("Error copying database --> "+e.toString());
}
}
}
public SQLiteDatabase openDataBase() throws SQLException{
return SQLiteDatabase.openOrCreateDatabase(DIR_DATABASE +PACKAGE_NAME+ "/Mafatih/" +DB_NAME, null);
}
public boolean CreateFile(){
if(flag == false)
{
File file= new File(DIR_DATABASE);
file.mkdirs();
return true;
}
else
{
return true;
}
}
public void GetPackageName(String res){
PACKAGE_NAME = res;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Problem : Could not allocate CursorWindow '.....' of size 2097152 due to error -12.
Reason: Most of the times this issue arises due to non-closure of cursors. You must close all the cursors after using them.
In your code if any exception occurs in try block, the cursor will not be closed as control will be passed to catch block. Hence modify your code as follows:
try {....}
catch{
}
finally {
cursor.close();
}
It is always a good practice to close the cursor in finally block.
You are not closing cursorid too. Make sure you close cursorid too.
UPDATE 1:
Why and when does this exception occur?
For processing an SQLite statement, a memory area is created by SQLite, known as context area, which contains all information needed for processing the statement, for example, number of rows processed, etc.
A cursor is a pointer to this context area. SQLite controls the context area through a cursor. A cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds is referred to as the active set.
Cursor.close() closes the Cursor, releasing all of its resources and making it completely invalid.
So if you do not close the cursor, the resources most importantly the memory pointed by cursor is not released and it causes leak which in turn causes allocation issues.
Hope it helps.
Related
I have a textview that gets data from sqlite database but when I delete a row,or change it ,I also want to change what the textview has,the data the textview contains is basically the sum of all rows specific column,so how can I update the textview when updating sqlite data?
here is my main code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logged_in);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
tinyDB = new TinyDB(getApplicationContext());
listView = findViewById(R.id.listt);
pharmacynme = findViewById(R.id.pharmacynme);
constraintLayout = findViewById(R.id.thelayout);
mBottomSheetDialog2 = new Dialog(LoggedIn.this, R.style.MaterialDialogSheet);
inflater2 = (LayoutInflater) LoggedIn.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mBottomSheetDialog = new Dialog(LoggedIn.this, R.style.MaterialDialogSheet);
content = inflater2.inflate(R.layout.activity_main2, null);
content2 = inflater2.inflate(R.layout.smalldialog, null);
total = (TextView) content2.findViewById(R.id.totalpriceofsmalldialog);
pharmacydescrr = findViewById(R.id.pharmacydiscribtion);
String nme = getIntent().getStringExtra("pharmacy_name");
String diskr = getIntent().getStringExtra("pharmacy_disk");
pharmacydescrr.setText(diskr);
pharmacynme.setText(nme);
//Listview Declaration
connectionClass = new ConnectionClass();
itemArrayList = new ArrayList<ClassListItems>();// Connection Class Initialization
etSearch = findViewById(R.id.etsearch);
etSearch.setSingleLine(true);
chat = findViewById(R.id.chat);
mDatabaseHelper = new DatabaseHelper(this);
mBottomSheetDialog2.setContentView(content2);
mBottomSheetDialog2.setCancelable(false);
mBottomSheetDialog2.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mBottomSheetDialog2.getWindow().setGravity(Gravity.BOTTOM);
mBottomSheetDialog2.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mBottomSheetDialog2.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
System.out.println("IDKSDKASDJKAS"+mDatabaseHelper.ifExists());
if (mDatabaseHelper.ifExists()){
mBottomSheetDialog2.show();
total.setText(mDatabaseHelper.getPriceSum());
}else {
}
chat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nameid = getIntent().getStringExtra("nameid");
Intent intent = new Intent(LoggedIn.this,ChatActivity.class);
intent.putExtra("nameid",nameid);
startActivity(intent);
}
});
etSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
String text = etSearch.getText().toString().toLowerCase(Locale.getDefault());
// myAppAdapter.filter(text);
}
});
SyncData orderData = new SyncData();
orderData.execute("");
}
public void AddData(String newEntry,String price,String amount){
boolean insertData = mDatabaseHelper.addData(newEntry,price,amount);
if (insertData){
toastMessage("Data Successfully inserted!");
}else {
toastMessage("Al anta 4abebto da ya youssef >:(");
}
}
private void toastMessage(String message){
Toast.makeText(this,message,Toast.LENGTH_LONG).show();
}
private class SyncData extends AsyncTask<String, String, String> {
String msg;
ProgressDialog progress;
#Override
protected void onPreExecute() //Starts the progress dailog
{
progress = ProgressDialog.show(LoggedIn.this, "Loading...",
"Please Wait...", true);
}
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
runOnUiThread(new Runnable() {
public void run() {
try {
Connection conn = connectionClass.CONN(); //Connection Object
if (conn == null) {
success = false;
msg = "Sorry something went wrong,Please check your internet connection";
} else {
// Change below query according to your own database.
String nme = getIntent().getStringExtra("pharmacy_name");
System.out.println(nme);
String query = "Select StoreArabicName,StoreEnglishName,StoreSpecialty,StoreCountry,StoreLatitude,StoreLongitude,Store_description,ProductData.ProductArabicName,ProductData.ProductImage,ProductData.ProductEnglishName,ProductData.ProductDescription,ProductData.ProductPrice FROM StoresData INNER JOIN ProductData ON StoresData.StoreID = ProductData.StoreID WHERE StoreEnglishName = '"+nme+"'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next()) {
try {
itemArrayList.add(new ClassListItems(rs.getString("ProductEnglishName"), rs.getString("ProductDescription"), rs.getString("ProductPrice"),rs.getString("ProductImage")));
System.out.println(rs.getString("ProductImage"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
Log.d("Error", writer.toString());
success = false;
}
}
});
return msg;
}
#Override
protected void onPostExecute(String msg) // disimissing progress dialoge, showing error and setting up my listview
{
progress.dismiss();
if (msg!=null){
Toast.makeText(LoggedIn.this, msg + "", Toast.LENGTH_LONG).show();
}
if (!success) {
} else {
try {
myAppAdapter = new MyAppAdapter(itemArrayList, LoggedIn.this);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(myAppAdapter);
} catch (Exception ex) {
}
}
}
}
public class MyAppAdapter extends BaseAdapter//has a class viewholder which holds
{
private ArrayList<ClassListItems> mOriginalValues; // Original Values
private ArrayList<ClassListItems> mDisplayedValues;
public class ViewHolder {
TextView textName;
TextView textData;
TextView textImage;
ImageView producticon;
}
public List<ClassListItems> parkingList;
public Context context;
ArrayList<ClassListItems> arraylist;
private MyAppAdapter(List<ClassListItems> apps, Context context) {
this.parkingList = apps;
this.context = context;
arraylist = new ArrayList<ClassListItems>();
arraylist.addAll(parkingList);
}
#Override
public int getCount() {
return parkingList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) // inflating the layout and initializing widgets
{
View rowView = convertView;
ViewHolder viewHolder = null;
if (rowView == null) {
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.listcontent, parent, false);
viewHolder = new ViewHolder();
viewHolder.textName = rowView.findViewById(R.id.name);
viewHolder.textData = rowView.findViewById(R.id.details);
viewHolder.textImage = rowView.findViewById(R.id.sdadprice);
viewHolder.producticon = rowView.findViewById(R.id.producticon);
rowView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// here setting up names and images
viewHolder.textName.setText(parkingList.get(position).getProname() + "");
viewHolder.textData.setText(parkingList.get(position).getData());
viewHolder.textImage.setText(parkingList.get(position).getImage());
Picasso.with(context).load(parkingList.get(position).getProducticon()).into(viewHolder.producticon);
mBottomSheetDialog.setCancelable(true);
mBottomSheetDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mBottomSheetDialog.getWindow().setGravity(Gravity.BOTTOM);
mBottomSheetDialog.setContentView(content);
total.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoggedIn.this,Listitemsbought.class);
startActivity(intent);
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
//What happens when you click on a place!
// Intent intent = new Intent(LoggedIn.this,MapsActivity.class);
// startActivity(intent);
final int count = 0;
final Float allitemscount = Float.parseFloat(parkingList.get(position).getImage());
TextView textView = (TextView) content.findViewById(R.id.mebuyss);
final TextView itemcount = (TextView) content.findViewById(R.id.itemcount);
Button plus = (Button) content.findViewById(R.id.plus);
Button minus = (Button) content.findViewById(R.id.minus);
Button finish = (Button) content.findViewById(R.id.finishgettingitem);
textView.setText(parkingList.get(position).getProname());
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter = counter + 1;
itemcount.setText(String.valueOf(counter));
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter --;
if(counter<0){
counter=0;
}
itemcount.setText(String.valueOf(counter));
}
});
finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String get = itemcount.getText().toString();
Float last = Float.parseFloat(get) * Float.parseFloat(parkingList.get(position).getImage());
mBottomSheetDialog.dismiss();
AddData(parkingList.get(position).getProname(),String.valueOf(last),String.valueOf(counter));
total.setText(mDatabaseHelper.getPriceSum());
mBottomSheetDialog2.show();
doneonce = true;
}
});
// if (doneonce = true){
// Float priceofitem = parseFloat(parkingList.get(position).getImage());
// Float currentprice = parseFloat(total.getText().toString());
// Float finalfloat = priceofitem * currentprice;
// total.setText(String.valueOf(finalfloat));
//
// }
if (!mBottomSheetDialog.isShowing()){
counter = 1;
}
//
mBottomSheetDialog.show();
// if (tinyDB.getString("selecteditem").equals("English")){
// Toast.makeText(LoggedIn.this,"Sorry this ability isn't here yet",Toast.LENGTH_LONG).show();
// }else {
// Toast.makeText(LoggedIn.this,"عفوا هذه الخاصية ليست متوفرة حاليا",Toast.LENGTH_LONG).show();
// }
}
});
return rowView;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
itemArrayList.clear();
if (charText.length() == 0) {
itemArrayList.addAll(arraylist);
} else {
for (ClassListItems st : arraylist) {
if (st.getProname().toLowerCase(Locale.getDefault()).contains(charText)) {
itemArrayList.add(st);
}
}
}
notifyDataSetChanged();
}
}
private Float parseFloat(String s){
if(s == null || s.isEmpty())
return 0.0f;
else
return Float.parseFloat(s);
}
And here is my DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "DatabaseHelper";
private static final String NAME = "Name";
private static final String PRICE = "Price";
private static final String AMOUNT = "Amount";
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null , 4);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " ("+PRICE+" TEXT, "+ NAME + " TEXT,"+ AMOUNT +" TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
onCreate(db);
}
public boolean addData(String item, String Price,String amount){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(PRICE,Price);
contentValues.put(NAME, item);
contentValues.put(AMOUNT, amount);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long insert = db.insert(TABLE_NAME,null,contentValues);
if (insert == -1){
return false;
}else {
return true;
}
}
public Cursor getDataOfTable(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT Name,Amount FROM " + TABLE_NAME ;
Cursor data = db.rawQuery(query, null);
return data;
}
public String getPriceSum(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT COALESCE(SUM(Price), 0) FROM " + TABLE_NAME;
Cursor price = db.rawQuery(query, null);
String result = "" + price.getString(0);
price.close();
db.close();
return result;
}
public boolean ifExists()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = null;
String checkQuery = "SELECT * FROM " + TABLE_NAME + " LIMIT 1";
cursor= db.rawQuery(checkQuery,null);
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
public void delete(String nameofrow) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+TABLE_NAME+" where "+NAME+"='"+nameofrow+"'");
}
}
Any help?!
The method getPriceSum() should return the sum and not a Cursor:
public String getPriceSum(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT COALESCE(SUM(Price), 0) FROM " + TABLE_NAME;
Cursor c = db.rawQuery(query, null);
String result = "";
if (c.moveToFirst()) result = "" + c.getString(0);
c.close();
db.close();
return result;
}
I don't think that you need the if block:
if (mDatabaseHelper.ifExists()) {
.......................
}
All you need to do is:
total.setText(mDatabaseHelper.getPriceSum());
I am using an external SQlite database in my project and a Listview with simple adapter, in fact it works fine but i wanna show images in Listview using glide library. i stored images url in database but i don't know how can I pass it to glide , it's possible or not?
thanks in advance.
public class DatabaseHandler extends SQLiteOpenHelper {
private Context main_context;
private static String DB_PATH;
private static String DB_NAME = "ebook_db.db";
private static int DB_VERSION = 1;
private static String DB_TBL_BOOKS = "books";
private static String DB_TBL_SETTINGS = "settings";
private SQLiteDatabase db;
public DatabaseHandler(Context con) {
super(con, DB_NAME, null, DB_VERSION);
main_context = con;
DB_PATH = con.getCacheDir().getPath() + "/" + DB_NAME;
}
#Override
public void onCreate(SQLiteDatabase db) {
/* do nothing */
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
/* do nothing */
}
private boolean dbExists() {
File f = new File(DB_PATH);
if (f.exists())
return true;
else
return false;
}
private boolean copyDB() {
try {
FileOutputStream out = new FileOutputStream(DB_PATH);
InputStream in = main_context.getAssets().open(DB_NAME);
byte[] buffer = new byte[1024];
int ch;
while ((ch = in.read(buffer)) > 0) {
out.write(buffer, 0, ch);
}
out.flush();
out.close();
in.close();
return true;
} catch (Exception e) {
/* do nothing */
return false;
}
}
public void open() {
if (dbExists()) {
try {
File temp = new File(DB_PATH);
db = SQLiteDatabase.openDatabase(
temp.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE
);
} catch (Exception e) {
/* do nothing */
}
} else {
if (copyDB())
open();
}
}
#Override
public synchronized void close() {
db.close();
}
public List<HashMap<String,Object>> getTableOfContent(String id) {
Cursor result = db.rawQuery("SELECT * FROM " + DB_TBL_BOOKS + " WHERE author = '" + id + "'", null);
List<HashMap<String, Object>> all_data = new ArrayList<>();
while (result.moveToNext()) {
HashMap<String,Object> temp = new HashMap<>();
temp.put("id", result.getString(0));
temp.put("title", result.getString(1));
temp.put("author", result.getString(3));
temp.put("image", result.getString(8));
if (result.getString(9).equals("1")) {
temp.put("fav_flag", R.drawable.is_favorite);
} else {
temp.put("fav_flag", R.drawable.not_favorite);
}
if (result.getString(10).equals("1")) {
temp.put("see_flag", R.drawable.see);
} else {
temp.put("see_flag", R.drawable.not_see);
}
all_data.add(temp);
}
return all_data;
}
tblOfContent.java
public class tblOfContent extends AppCompatActivity {
private ListView contentListView;
private List<HashMap<String, Object>> books_list;
private DatabaseHandler db;
public String my_key_number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tbl_of_content);
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
Bundle extras = getIntent().getExtras();
if (extras != null) {
my_key_number = extras.getString("number_of_keys");
Toast.makeText(this, my_key_number, Toast.LENGTH_LONG).show();
}
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
//actionBar.setTitle(R.string.doctors_title);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
contentListView = findViewById(R.id.tblOfContentListView);
db = new DatabaseHandler(getBaseContext());
db.open();
books_list = db.getTableOfContent(my_key_number);
String[] from = {"title", "image", "fav_flag", "see_flag"};
int[] to = {R.id.txtTitle, R.id.url, R.id.setFav, R.id.setSee};
SimpleAdapter adb = new SimpleAdapter(
getBaseContext(), books_list, R.layout.foods_row_item, from, to
);
contentListView.setAdapter(adb);
db.close();
contentListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(getBaseContext(), book_content.class);
String my_id = books_list.get(position).get("id").toString();
i.putExtra("id", my_id);
startActivity(i);
}
}
);
}
}
Try this:
String[] from = {"title", "fav_flag", "see_flag"};
int[] to = {R.id.txtTitle, R.id.setFav, R.id.setSee};
SimpleAdapter adb = new SimpleAdapter(getBaseContext(), books_list, R.layout.foods_row_item, from, to){
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = super.getView(position, convertView, parent);
String url = (String)((HashMap<String, Object>)getItem(position)).get("image");
ImageView imageView = (ImageView)itemView.findViewById(R.id.url);
Glide.with(this)
.load(url)
.into(imageView);
return itemView;
}
};
Hope it helps!
I have navigation drawer with menu nav items. Now I define for one item, for when clicking on it, open a new activity.Inside this activity, I design layout for start flag game quiz.When clicking on play game Button, the game started so fast without waiting for click user, and finish. Inside "PlayGame" layout, I define one imageView for flags and 4 buttons for answers. Flags name and answers come from the External database. When I debug the app, countDownTimer realise null amount, Everything is correct, Just Timer doesn't wait for use, and playing Quiz is so quickly.
this is my database.
WorldCountryDatabase
public class WorldCountryDatabase extends SQLiteOpenHelper {
private static final String TAG = "databaseHelper";
private static final String DB_NAME = "worldCountries.db";
private static final int DB_VERSION = 1;
private static final String TABLE_NAME = "country";
private static String DB_PATH = "";
private Context mContext;
private SQLiteDatabase database;
public WorldCountryDatabase(Context context) {
super(context, DB_NAME, null, DB_VERSION);
DB_PATH = context.getDatabasePath(DB_NAME).getPath();
File file = new File(DB_PATH + "worldCountries.db");
if (file.exists())
openDataBase();
this.mContext = context;
}
public void createDatabase() {
boolean dbExist = checkDatabase();
if (dbExist) {
Log.d("MIN1", "Database already Exist");
} else {
this.getReadableDatabase();
}
try {
copyDataBase();
} catch (IOException e) {
e.printStackTrace();
Log.i("MIN2", e.getMessage());
}
}
private boolean checkDatabase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
} catch (SQLiteException e) {
e.printStackTrace();
Log.d("MIN3", e.getMessage());
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null;
}
public synchronized void close() {
if (database != null) {
database.close();
SQLiteDatabase.releaseMemory();
}
super.close();
}
private void copyDataBase() throws IOException {
try {
InputStream in = mContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream out = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
out.flush();
out.close();
in.close();
Log.d("MIN4", "Database copy");
} catch (SQLiteException e) {
Log.d("MIN5", e.getMessage());
}
}
public Cursor QueryData(String query) {
return database.rawQuery(query, null);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d("MIN6", "onCreate");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
Log.v("LOG_TAG", "Upgrading Database from version" + oldVersion + "To" + newVersion +
"Which will destroy all oldest data");
if (newVersion > oldVersion) {
try {
copyDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void openDataBase() {
String myPath = DB_PATH + DB_NAME;
database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
Log.d("MIN7", "Opened database");
}
// CRUD Table
public List<Questions> getAllQuestions() {
List<Questions> questionsList = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c;
try {
c = db.rawQuery("SELECT * FROM country ORDER BY Random()", null);
if (c == null) return null;
c.moveToFirst();
do {
int Id = c.getInt(c.getColumnIndex("id"));
String Image = c.getString(c.getColumnIndex("Image"));
String AnswerA = c.getString(c.getColumnIndex("AnswerA"));
String AnswerB = c.getString(c.getColumnIndex("AnswerB"));
String AnswerC = c.getString(c.getColumnIndex("AnswerC"));
String AnswerD = c.getString(c.getColumnIndex("AnswerD"));
String CorrectAnswer = c.getString(c.getColumnIndex("CorrectAnswer"));
Questions question = new Questions(Id, Image, AnswerA, AnswerB, AnswerC, AnswerD, CorrectAnswer);
questionsList.add(question);
} while (c.moveToNext());
c.close();
} catch (Exception e) {
e.printStackTrace();
}
database.close();
return questionsList;
}
// Insert Score to Ranking table.
public void insertScore(double score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues content = new ContentValues();
content.put("Score", score);
db.insert("Ranking", null, content);
}
// Get score and sort Ranking.
public List<Ranking> getRanking() {
List<Ranking> rankingList = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c;
try {
c = db.rawQuery("SELECT * FROM country ORDER BY Score DESC;", null);
if (c == null) return null;
c.moveToFirst();
do {
int ID = c.getInt(c.getColumnIndex("id"));
int Score = c.getInt(c.getColumnIndex("Score"));
Ranking ranking = new Ranking(ID, Score);
rankingList.add(ranking);
} while (c.moveToNext());
c.close();
} catch (Exception e) {
e.printStackTrace();
}
db.close();
return rankingList;
}
public int getPlayCount(int level)
{
int result = 0;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c;
try{
c = db.rawQuery("SELECT PlayCount FROM UserPlayCount WHERE Level="+level+";",null);
if(c == null) return 0;
c.moveToNext();
do{
result = c.getInt(c.getColumnIndex("PlayCount"));
}while(c.moveToNext());
c.close();
}catch (Exception ex)
{
ex.printStackTrace();
}
return result;
}
public void updatePlayCount(int level,int playCount)
{
String query = String.format("UPDATE UserPlayCount Set PlayCount = %d WHERE Level = %d",playCount,level);
database.execSQL(query);
}
this is my ChoicGame class.
ChoiceGame
public class ChoiceGame extends AppCompatActivity {
TextView modeText;
SeekBar seekBarMode;
Button playGame, scoreGame;
WorldCountryDatabase worldCountryDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_flag);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
modeText = (TextView) findViewById(R.id.modeText);
seekBarMode = (SeekBar) findViewById(R.id.seekBarMode);
playGame = (Button) findViewById(R.id.playGame);
scoreGame = (Button) findViewById(R.id.scoreGame);
worldCountryDatabase = new WorldCountryDatabase(this);
try {
worldCountryDatabase.createDatabase();
} catch (Exception e) {
e.printStackTrace();
}
//Event
seekBarMode.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (progress == 0)
modeText.setText(Common.MODE.EASY.toString());
else if (progress == 1)
modeText.setText(Common.MODE.MEDIUM.toString());
else if (progress == 2)
modeText.setText(Common.MODE.HARD.toString());
else if (progress == 3)
modeText.setText(Common.MODE.HARDEST.toString());
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
playGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), PlayGameCountry.class);
intent.putExtra("Mode", getPlayMode()); // Send Mode to Playing page
startActivity(intent);
finish();
}
});
scoreGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), ScoreGame.class);
startActivity(intent);
finish();
}
});
}
private String getPlayMode() {
if (seekBarMode.getProgress() == 0)
return Common.MODE.EASY.toString();
else if (seekBarMode.getProgress() == 1)
return Common.MODE.MEDIUM.toString();
else if (seekBarMode.getProgress() == 2)
return Common.MODE.HARD.toString();
else
return Common.MODE.HARDEST.toString();
}
}
and at last this is my PlayingGame class.
PlayingGmae
public class PlayGameCountry extends AppCompatActivity implements View.OnClickListener {
final static long INTERVAL = 1; // 1 second
final static long TIMEOUT = 7; // 1 second
CountDownTimer countDownTimer;
int progressValue = 0;
int score = 0, index = 0, thisQuestion = 0, correctAnswer, totalQuestions;
List<Questions> questionsList = new ArrayList<>();
String mode;
ProgressBar progressBar;
ImageView flagCountry;
TextView scoreText, numberQuestion;
Button answerA, answerB, answerC, answerD;
WorldCountryDatabase worldCountryDatabase;
ChoiceGame choiceGame;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_game_country);
// Get data from ChoiceGame
Bundle bundle = getIntent().getExtras();
if (bundle != null)
mode = bundle.getString("Mode");
worldCountryDatabase = new WorldCountryDatabase(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
flagCountry = (ImageView) findViewById(R.id.flagQuiz);
scoreText = (TextView) findViewById(R.id.scoreText);
numberQuestion = (TextView) findViewById(R.id.trueAnswer);
answerA = (Button) findViewById(R.id.firstAnswer);
answerB = (Button) findViewById(R.id.secondAnswer);
answerC = (Button) findViewById(R.id.thirthAnswer);
answerD = (Button) findViewById(R.id.forthAnswer);
progressBar = (ProgressBar) findViewById(R.id.progressUser);
answerA.setOnClickListener(this);
answerB.setOnClickListener(this);
answerC.setOnClickListener(this);
answerD.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
questionsList = this.getQuestionMode(mode);
assert questionsList != null;
totalQuestions = questionsList.size();
countDownTimer = new CountDownTimer(INTERVAL, TIMEOUT) {
#Override
public void onTick(long millisUntilFinished) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
countDownTimer.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
private void showQuestion(int index) {
if (index < totalQuestions) {
thisQuestion++;
numberQuestion.setText(String.format("%d/%d", thisQuestion, totalQuestions));
progressBar.setProgress(0);
progressValue = 0;
int ImageId = this.getResources().getIdentifier(questionsList.get(index).getImage().toLowerCase(), "drawable", getPackageName());
flagCountry.setBackgroundResource(ImageId);
answerA.setText(questionsList.get(index).getAnswerA());
answerB.setText(questionsList.get(index).getAnswerB());
answerC.setText(questionsList.get(index).getAnswerC());
answerD.setText(questionsList.get(index).getAnswerD());
countDownTimer.start();
} else {
Intent scoreIntent = new Intent(getApplicationContext(), Done.class);
Bundle bundle = new Bundle();
bundle.putInt("SCORE", score);
bundle.putInt("TOTAL", totalQuestions);
bundle.putInt("CORRECT", correctAnswer);
scoreIntent.putExtras(bundle);
startActivity(scoreIntent);
finish();
}
}
#Override
public void onClick(View v) {
countDownTimer.cancel();
if (index < totalQuestions) {
Button clickedButton = (Button) v;
if (clickedButton.getText().equals(questionsList.get(index).getCorrectAnswer()))
{
score += 10; // increase score
correctAnswer++; //increase correct answer
showQuestion(++index);
} else
showQuestion(++index); // If choose right , just go to next question
scoreText.setText(String.format("%d", score));
}
}
private List<Questions> getQuestionMode(String mode) {
List<Questions> questionList = new ArrayList<>();
worldCountryDatabase = new WorldCountryDatabase(this);
try {
worldCountryDatabase.createDatabase();
worldCountryDatabase.openDataBase();
} catch (Exception e) {
e.printStackTrace();
}
int limit = 0;
if (mode.equals(Common.MODE.EASY.toString()))
limit = 30;
else if (mode.equals(Common.MODE.MEDIUM.toString()))
limit = 50;
else if (mode.equals(Common.MODE.HARD.toString()))
limit = 100;
else if (mode.equals(Common.MODE.HARDEST.toString()))
limit = 200;
try {
Cursor cursor = worldCountryDatabase.QueryData(String.format("SELECT * FROM country ORDER BY Random() LIMIT %d", limit));
if (cursor == null) return null;
if (cursor.moveToNext()) {
do {
int Id = cursor.getInt(cursor.getColumnIndex("id"));
String Image = cursor.getString(cursor.getColumnIndex("Image"));
String AnswerA = cursor.getString(cursor.getColumnIndex("AnswerA"));
String AnswerB = cursor.getString(cursor.getColumnIndex("AnswerB"));
String AnswerC = cursor.getString(cursor.getColumnIndex("AnswerC"));
String AnswerD = cursor.getString(cursor.getColumnIndex("AnswerD"));
String CorrectAnswer = cursor.getString(cursor.getColumnIndex("CorrectAnswer"));
Questions question = new Questions(Id, Image, AnswerA, AnswerB, AnswerC, AnswerD, CorrectAnswer);
questionList.add(question);
} while (cursor.moveToNext());
worldCountryDatabase.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return questionList;
}
}
At the first, I defining "getQuestionMode" method inside WorldCountryDatabase, but the app doesn't go to the PlayingCountryGame layout and open ScoreGame class. After I define "getQuestionMode" method inside PlayingCountryGame class. I hope to tell clear my problem.
Please help me, good friends. Thanks to all of you.
I think that you problem is the constructor and values.
https://developer.android.com/reference/android/os/CountDownTimer.html#CountDownTimer(long, long)
The constructor need the time on milliseconds and not seconds. Y ou need convert 1 second to 1000 ms.
final static long INTERVAL = 1000; // 1 second -> 1000 milliseconds
final static long TIMEOUT = 7000; // 7 seconds -> 7000 milliseconds
And the order of the params.
If you want wait 7 second the constructor is:
countDownTimer = new CountDownTimer(TIMEOUT, INTERVAL){ ... }
!Database consists of multiple tables and multiple columns as shown & i have pasted this law.sqlite in assets folder.
Database consists of multiple tables and multiple columns as shown & i have pasted this law.sqlite in assets folder.
Suppose i want to access all the elements of column AS_name as shown . So how should i code for it?
Try this:
Cursor cursor = db.rawQuery("SELECT DISTINCT AS_name FROM Articles",null);
// If you want in order then add "ORDER BY AS_name AESC" in sql query.
cursor.moveToFirst();
while(cursor.moveToNext()) {
// do Something
}
I tried and now the problem is solved :
For anyone facing similar type of problem can try my implementation :
Step 1:
Make a GetterSetter class (named GS here) & generate the Getter-Setters of variables used.
Like in my case:
public class GS {
String AS_name;
public String getAS_name() {
return AS_name;
}
public void setAS_name(String aS_name) {
AS_name = aS_name;
}
}
Step 2:
Make a DBAdapter class which extends SQLiteOpenHelper & in that assign the your name of the file with extension .sqlite !
Rest you need only to copy my DBAdapter.java code & take care to implement the method getData() in which the data from database is fetched !
public class DBAdapter extends SQLiteOpenHelper
{
CustomAdapter adapter;
static String name = "law.sqlite"; //--Replace it with ur sqlite name
static String path = "";
static ArrayList<GS> gs;
static SQLiteDatabase sdb;
#Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
}
private DBAdapter(Context v)
{
super(v, name, null, 1);
path = "/data/data/" + v.getApplicationContext().getPackageName() + "/databases";
}
public boolean checkDatabase()
{
SQLiteDatabase db = null;
try
{
db = SQLiteDatabase.openDatabase(path + "/" + name, null, SQLiteDatabase.OPEN_READONLY);
} catch (Exception e)
{
e.printStackTrace();
}
if (db == null)
{
return false;
}
else
{
db.close();
return true;
}
}
public static synchronized DBAdapter getDBAdapter(Context v)
{
return (new DBAdapter(v));
}
public void createDatabase(Context v)
{
this.getReadableDatabase();
try
{
InputStream myInput = v.getAssets().open(name);
// Path to the just created empty db
String outFileName = path +"/"+ name;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0)
{
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
} catch (IOException e)
{
System.out.println(e);
}
}
public void openDatabase()
{
try
{
sdb = SQLiteDatabase.openDatabase(path + "/" + name, null,
SQLiteDatabase.OPEN_READWRITE);
} catch (Exception e)
{
System.out.println(e);
}
}
public ArrayList<GS> getData()
{
try{
Cursor c1 = sdb.rawQuery("SELECT DISTINCT * FROM Articles", null);
gs = new ArrayList<GS>();
while (c1.moveToNext())
{
GS q1 = new GS();
q1.setAS_name(c1.getString(3)); //--- here 3 represents column no.
Log.v("AS_name",q1.AS_name+"");
gs.add(q1);
}
}
catch (Exception e) {
e.printStackTrace();
}
return gs;
}
}
Step 3:
The class MainActivity.java :
public class MainActivity extends Activity {
ArrayList<GS> q = new ArrayList<GS>();
CustomAdapter adapter;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get ListView object from xml
lv = (ListView) findViewById(R.id.listView1);
DBAdapter db = DBAdapter.getDBAdapter(getApplicationContext());
if (!db.checkDatabase())
{
db.createDatabase(getApplicationContext());
}
db.openDatabase();
q = db.getData();
for(int i=0;i<q.size();i++)
{
Log.i("outside",""+q.get(i).getAS_name());
}
lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(new CustomAdapter(MainActivity.this,q));
//lv.setAdapter(adapter);
}
class CustomAdapter extends ArrayAdapter<GS>
{
ArrayList<GS> list;
LayoutInflater mInfalter;
public CustomAdapter(Context context, ArrayList<GS> list)
{
super(context,R.layout.customlayout,list);
this.list= list;
mInfalter = LayoutInflater.from(context);
for(int i=0;i<list.size();i++)
{
Log.i("................",""+list.get(i).getAS_name());
}
}
// public int getCount(){
// return list.size();
// }
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
Log.i("..........","Hello in getView");
if(convertView==null)
{
convertView = mInfalter.inflate(R.layout.customlayout,parent,false);//--customlayout.xml must have a textView
holder = new ViewHolder();
holder.tv1 = (TextView)convertView.findViewById(R.id.textView1);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.tv1.setText(list.get(position).getAS_name());
return convertView;
}
}
static class ViewHolder
{
TextView tv1;
}
}
Run this code & finally the list in the listview will be displayed ! :)
Cursor c = db.query(
TABLE_NAME, // The table to query
projection, // The columns to return
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
Specify the table name in TABLE_NAME field. Then access the elements using
c.moveToFirst();
for(int i=0;i<c.getCount();i++)
{
//access elements of column here
long itemId = c.getLong(c.getColumnIndexOrThrow(Column_Name)); //Example with long, corresponding function for string etc also exists.
c.moveToNext();
}
c.close();
Specify the column name in Column_name.
NOTE: If this column is in multiple tables, just put both these code snippets in a loop and iterate through it. May be you can store the table names in an arraylist and access each table in each iteration of the outermost loop. Hope this helps you!!!
I need to display data from 4 different database tables in android. Previously for testing I used single table to display data. For that I have created three files.
1)DBAdapter.java
2)UserBO.java
3)Test.java
DBAdapter.java
public class DBAdapter extends SQLiteOpenHelper {
private static String DB_PATH = "";
private static final String DB_NAME = "mydb.sqlite";
private SQLiteDatabase myDataBase1;
private final Context myContext1;
private static DBAdapter mDBConnection;
private DBAdapter(Context context) {
super(context, DB_NAME, null, 1);
this.myContext1 = context;
DB_PATH = "/data/data/"
+ context.getApplicationContext().getPackageName()
+ "/databases/";
}
public static synchronized DBAdapter getDBAdapterInstance(Context context) {
if (mDBConnection == null) {
mDBConnection = new DBAdapter(context);
}
return mDBConnection;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
// By calling following method
// 1) an empty database will be created into the default system path of your application
// 2) than we overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext1.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
myDataBase1 = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
#Override
public synchronized void close() {
if (myDataBase1 != null)
myDataBase1.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public Cursor selectRecordsFromDB(String tableName, String[] tableColumns,
String whereClase, String whereArgs[], String groupBy,
String having, String orderBy) {
return myDataBase1.query(tableName, tableColumns, whereClase, whereArgs,
groupBy, having, orderBy);
}
public ArrayList<ArrayList<String>> selectRecordsFromDBList(String tableName, String[] tableColumns,
String whereClase, String whereArgs[], String groupBy,
String having, String orderBy) {
ArrayList<ArrayList<String>> retList = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
Cursor cursor = myDataBase1.query(tableName, tableColumns, whereClase, whereArgs,
groupBy, having, orderBy);
if (cursor.moveToFirst()) {
do {
list = new ArrayList<String>();
for(int i=0; i<cursor.getColumnCount(); i++){
list.add( cursor.getString(i) );
}
retList.add(list);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return retList;
}
public Cursor selectRecordsFromDB(String query, String[] selectionArgs) {
return myDataBase1.rawQuery(query, selectionArgs);
}
public ArrayList<ArrayList<String>> selectRecordsFromDBList(String query, String[] selectionArgs) {
ArrayList<ArrayList<String>> retList = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
Cursor cursor = myDataBase1.rawQuery(query, selectionArgs);
if (cursor.moveToFirst()) {
do {
list = new ArrayList<String>();
for(int i=0; i<cursor.getColumnCount(); i++){
list.add( cursor.getString(i) );
}
retList.add(list);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return retList;
}
}
**UserBO.java**
public class UserBO {
int sid;
String sname;
public int getsid() {
return sid;
}
public void setsid(int sid) {
this.sid = sid;
}
public String getsname() {
return sname;
}
public void setsname(String sname) {
this.sname= sname;
}
}
Test.java
public class Select extends Activity {
private Header header;
private ListView lvUsers;
private ArrayList<UserBO> mListUsers;
private SharedPreferences mPreferences1;
private SharedPreferences mPreferences2;
String myString1,query;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("before k select "+k);
setContentView(R.layout.select);
header = (Header) findViewById(R.id.layoutHeader);
mListUsers = getUsers();
lvUsers = (ListView) findViewById(R.id.lv_user);
lvUsers.setAdapter(new ListAdapter(this, R.id.lv_user, mListUsers));
}
public ArrayList<UserBO> getUsers(){
DBAdapter dbAdapter=DBAdapter.getDBAdapterInstance(this);
try {
dbAdapter.createDataBase();
} catch (IOException e) {
Log.i("*** select ",e.getMessage());
}
mPreferences1 = getSharedPreferences("CurrentUser1", 0);
myString1 = mPreferences1.getString("student id",sid);
dbAdapter.openDataBase();
**query="SELECT tabel1.*, tabel2.* FROM tabel1, tabel2 WHERE tabel1.PK=tabel2.FK;";**
ArrayList<ArrayList<String>> stringList = dbAdapter.selectRecordsFromDBList(query, null);
dbAdapter.close();
ArrayList<UserBO> usersList = new ArrayList<UserBO>();
for (int i = 0; i < stringList.size(); i++) {
ArrayList<String> list = stringList.get(i);
UserBO user = new UserBO();
AppConstants.alConductedQuestions.add(user);
System.out.println("mListUsers");
System.out.println(user);
try {
user.sid = Integer.parseInt(list.get(0));
user.sname = list.get(1);
}
catch (Exception e) {
Log.i("***" + Test.class.toString(), e.getMessage());
}
usersList.add(user);
}
return usersList;
}
// ***ListAdapter***
private class ListAdapter extends ArrayAdapter<UserBO> { // --CloneChangeRequired
private ArrayList<UserBO> mList; // --CloneChangeRequired
private Context mContext;
public ListAdapter(Context context, int textViewResourceId,ArrayList<UserBO> list) { // --CloneChangeRequired
super(context, textViewResourceId, list);
//System.out.println(list);
this.mList = list;
this.mContext = context;
}
public View getView(int position, View convertView, ViewGroup parent){
View view = convertView;
try{
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.list_item, null);
// --CloneChangeRequired(list_item)
}
final UserBO listItem = mList.get(position); // --CloneChangeRequired
if (listItem != null) {
// setting list_item views
( (TextView) view.findViewById(R.id.casedescription) ).setText( listItem.getsid()+"");
( (TextView) view.findViewById(R.id.tv_question) ).setText( listItem.getsname()+"");
ArrayList<UserBO> mList1;
}
}
catch(Exception e){
String err = (e.getMessage()==null)?"hii":e.getMessage();
Log.e("sdcard-err2:",err);
}
return view;
}
}
}
In test.java I am writing the query. In UserBO I am writing the setter and getter methods. In DBAdapter file I am mentioning the database name. So here my question is I have 4 tables in my database. So I need to display data using those tables. Shall I write the setter and getter methods of the column names of all the tables in one single UserBO file?
Also I am getting the values of each column of single table by giving
user.sid = Integer.parseInt(list.get(0));
user.sname = list.get(1);
*How do I get the column names of all the tables?* I mean shall I need to get all the columns of all the tables in Test.java file?
Please help me regarding this....I am it confused with this different tables.....
Thanks in Advance
you have one database & three tables or all three tables are in different databsaes ?