I have a problem in adding values to my String[] array from another class. What I wanted to do is to add values to my MainScreenEntered.java class from database through my MyDatabaseAdapter.java class.
PLease help.
THis is my code.
MainScreenentered.java
public class MainScreenEntered extends Activity implements OnItemClickListener{
#SuppressLint("NewApi")
ListView lv;
List<RowItem> rowItems;
MyDatabaseAdapter mh;
String username;
ListView listViewSMS;
Cursor cursor;
Context context;
public static String[] names = new String[] {};
public static String[] descriptions = new String[] {};
public static String[] pics = new String[] {};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen_entered);
mh = new MyDatabaseAdapter(this);
Bundle bundle = this.getIntent().getExtras();
username = bundle.getString("username");
Message.message(this, username);
try
{
mh.getDataToDatabase();
rowItems = new ArrayList<RowItem>();
for(int i =0; i< names.length; i++)
{
RowItem item = new RowItem(pics[i], names[i], descriptions[i]);
rowItems.add(item);
}
lv = (ListView)findViewById(R.id.lvEntries);
CustomListViewAdapter adapter = new CustomListViewAdapter(this, R.layout.list_layout,rowItems);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
}
catch(Exception e)
{
Message.message(this, ""+e);
}
}
}
MyDatabaseAdapter.java
public class MyDatabaseAdapter {
MyHelper helper;
public MyDatabaseAdapter (Context context)
{
helper = new MyHelper(context);
}
public void getDataToDatabase()
{
MainScreenEntered ms = new MainScreenEntered();
SQLiteDatabase db = helper.getWritableDatabase();
String columns[] = {MyHelper.ENTRY_FULLNAME,MyHelper.ENTRY_DESCRIPTION,MyHelper.ENTRY_IMAGE};
Cursor c=db.query(MyHelper.TABLE_ENTRIES, columns, null, null, null, null, null);
int i=0;
while(c.moveToNext())
{
String name = c.getString(0);
String desc = c.getString(1);
String pic = c.getString(2);
ms.names[i] = name;
ms.descriptions[i] = desc;
ms.pics[i] = pic;
i++;
}
db.close();
}
}
you can do like this
in onCreate
mh = new MyDatabaseAdapter(this,this);
now
public class MyDatabaseAdapter {
MyHelper helper;
MainScreenEntered ms;
public MyDatabaseAdapter (Context context, MainScreenEntered ms)
{
helper = new MyHelper(context);
this.ms = ms;
}
public void getDataToDatabase()
{
SQLiteDatabase db = helper.getWritableDatabase();
String columns[] = {MyHelper.ENTRY_FULLNAME,MyHelper.ENTRY_DESCRIPTION,MyHelper.ENTRY_IMAGE};
Cursor c=db.query(MyHelper.TABLE_ENTRIES, columns, null, null, null, null, null);
int i=0;
while(c.moveToNext())
{
String name = c.getString(0);
String desc = c.getString(1);
String pic = c.getString(2);
ms.names[i] = name;
ms.descriptions[i] = desc;
ms.pics[i] = pic;
i++;
}
db.close();
}
}
Try this..
In your MainScreenEntered.java
public static ArrayList<String> names = new ArrayList<String>();
public static ArrayList<String> descriptions = new ArrayList<String>();
public static ArrayList<String> pics = new ArrayList<String>();
and MyDatabaseAdapter
while(c.moveToNext())
{
String name = c.getString(0);
String desc = c.getString(1);
String pic = c.getString(2);
MainScreenEntered.names.add(name);
MainScreenEntered.descriptions.add(desc);
MainScreenEntered.pics.add(pic);
}
then
rowItems = new ArrayList<RowItem>();
for(int i =0; i<names.length; i++)
{
RowItem item = new RowItem(pics.get(i), names.get(i), descriptions.get(i));
rowItems.add(item);
}
use c.movetoFirst() before while loop and for static array u doesn't have to create object of it u can directly call it ClassName.variable_name ... it will be a better if you use arraylist of string rather than string array.
Be careful by doing DB operation on the UI thread you will might have some ANR.
Related
here's the structure
I have an app that makes the users' all his/her favorites placed on one place. So that he/she will not go through all the data. All I want is to have a recyclerview with multiple list that the "ListTitle" dynamically created, and when the "ListTitle" is already in it, only the child will appear. If not, create again another cardview. Thanks in advance.
My Code:
LoadsFavoriteAdapter.java
public class LoadFavoritesAdapter extends RecyclerView.Adapter<LoadFavoritesAdapter.LoadFavoritesViewHolder> {
private ArrayList<LoadFavorites> loadFavorites;
private Context context;
private ArrayList<LoadFavorites> mloadFavorites;
final String loadParent = "";
public LoadFavoritesAdapter(ArrayList<LoadFavorites> loadFavorites, Context context){
this.loadFavorites = loadFavorites;
this.context = context;
this.mloadFavorites = loadFavorites;
}
public class LoadFavoritesViewHolder extends RecyclerView.ViewHolder{
TextView txtLoadNameTest, txtLoadAmountTest;
public LoadFavoritesViewHolder(View view){
super(view);
txtLoadAmountTest = view.findViewById(R.id.txtLoadAmountTest);
txtLoadNameTest = view.findViewById(R.id.txtLoadNameTest);
}
}
public LoadFavoritesViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.favorite_item, parent, false);
return new LoadFavoritesViewHolder(itemView);
}
public void onBindViewHolder(final LoadFavoritesViewHolder holder, int position){
holder.txtLoadNameTest.setText(loadFavorites.get(position).getLoadName());
holder.txtLoadAmountTest.setText(loadFavorites.get(position).getLoadAmount());
}
public int getItemCount(){
return mloadFavorites.size();
}}
Favorites.java
public class Favorites extends AppCompatActivity {
Database localDb;
Context CTX = this;
private RecyclerView recyclerView;
private ArrayList<LoadFavorites> loadFavorites;
private LoadFavoritesAdapter loadFavoritesAdapter;
private Database database;
private ArrayList<LoadFavorites> mloadFavorites;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorites);
localDb = new Database(this);
recyclerView = findViewById(R.id.recycler_favorites);
loadFavorites = new ArrayList<>();
loadFavoritesAdapter = new LoadFavoritesAdapter(loadFavorites, this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(loadFavoritesAdapter);
database = new Database(this);
getDataFromSQLite();
}
private void getDataFromSQLite(){
new AsyncTask<Void, Void, Void>(){
protected Void doInBackground(Void... params){
loadFavorites.clear();
loadFavorites.addAll(database.getFavorites());
return null;
}
protected void onPostExecute(Void aVoid){
super.onPostExecute(aVoid);
}
}.execute();
}}
Database.java
public class Database extends SQLiteAssetHelper {
private static final String DB_NAME="Favorites.db";
private static final int DB_VER=1;
public Database(Context context) {
super(context, DB_NAME, null, DB_VER);
try{
String myPath = context.getFilesDir().getAbsolutePath(); // also check the extension of you db file
File dbfile = new File(myPath);
if(dbfile.exists()){
Toast.makeText(context, "database exists", Toast.LENGTH_LONG).show();
Toast.makeText(context, ""+myPath, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "cant find database", Toast.LENGTH_LONG).show();
Toast.makeText(context, ""+myPath, Toast.LENGTH_SHORT).show();
}
}
catch(SQLiteException e){
System.out.println("Database doesn't exist");
}
}
public void addToFavorites(String loadId, String loadName, String loadDetail, String loadNumber, String loadDuration, String loadAmount, String loadParent){
SQLiteDatabase db = getReadableDatabase();
String query = String.format("INSERT INTO Favorites(LoadId, LoadName, LoadDetail, LoadNumber, LoadDuration, LoadAmount, LoadParent) VALUES('%s','%s','%s','%s','%s','%s','%s');", loadId, loadName, loadDetail, loadNumber, loadDuration, loadAmount, loadParent);
db.execSQL(query);
}
public void removeFromFavorites(String loadId){
SQLiteDatabase db = getReadableDatabase();
String query = String.format("DELETE FROM Favorites WHERE LoadId='%s';", loadId);
db.execSQL(query);
}
public boolean isFavorite(String loadId){
SQLiteDatabase db = getReadableDatabase();
String query = String.format("SELECT * FROM Favorites WHERE LoadId='%s';", loadId);
Cursor cursor = db.rawQuery(query,null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
public Cursor getInformation(Database database){
SQLiteDatabase db = database.getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] columns = {"LoadId", "LoadParent"};
String sqlTable = "Favorites";
qb.setTables(sqlTable);
Cursor CR = qb.query(db,columns,null,null,null,null,null);
return CR;
}
public List<LoadFavorites> getFavorites(){
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = {"LoadId", "LoadName", "LoadDetail", "LoadNumber", "LoadDuration", "LoadAmount", "LoadParent"};
String sqlTable = "Favorites";
qb.setTables(sqlTable);
Cursor c = qb.query(db,sqlSelect,null,null,null,null,null);
final List<LoadFavorites> result = new ArrayList<>();
if(c.moveToFirst()){
do{
result.add(new LoadFavorites(c.getString(c.getColumnIndex("LoadId")),
c.getString(c.getColumnIndex("LoadName")),
c.getString(c.getColumnIndex("LoadDetail")),
c.getString(c.getColumnIndex("LoadNumber")),
c.getString(c.getColumnIndex("LoadDuration")),
c.getString(c.getColumnIndex("LoadAmount")),
c.getString(c.getColumnIndex("LoadParent"))
));
}while(c.moveToNext());
}
return result;
}}
I want to make a custom listView with some data and one section header for each day.
In this section header want to put date and total for each day.
I'm in trouble to calculate the total for each section header.
My data source is a database.
this look like this:
My Adapter:
public class CursorSectionAdapter extends CursorAdapter {
public static final String TAG = "debug_adapter";
public static final String BABY_BOTTLE_TAG = "baby_bottle";
int i = 0;
private LayoutInflater cursorInflater;
private LinkedHashMap<String, Integer> mSections;
private LinkedHashMap<String, Integer> mSectionsDate;
private ArrayList mSectionIndex;
BaseAdapter baseAdapter;
private Cursor mCursor;
private static final int STATE_UNKNOWN = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_ITEM = 2;
public CursorSectionAdapter(Context context, Cursor c, boolean autoRequery) {
super(context, c, autoRequery);
this.mSections = new LinkedHashMap<String, Integer>();
this.mSectionsDate = new LinkedHashMap<String, Integer>();
this.mSectionIndex = new ArrayList();
mCursor = c;
findSection();
cursorInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public void changeCursor(Cursor cursor) {
mCursor = cursor;
// int i = cursor.getCount();
findSection();
super.changeCursor(cursor);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return cursorInflater.inflate(R.layout.baby_bottle_item_layout, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
i++;
TextView dateTimeTv = (TextView) view.findViewById(R.id.BabyBottleItemDateTimeTextView);
String dateTime[] = cursor.getString(cursor.getColumnIndex(BiberonDataBaseContract.BabyBottleTable.COLUMN_DATETIME)).split(" ");
dateTimeTv.setText(dateTime[1]);
//Todo test dateTime not null
TextView quantityTv = (TextView) view.findViewById(R.id.BabyBottleItemQuantityTextView);
String quantity = cursor.getString(cursor.getColumnIndex(BiberonDataBaseContract.BabyBottleTable.COLUMN_QUANTITY));
quantityTv.setText(quantity + "ml");
TextView otherTv = (TextView) view.findViewById(R.id.BabyBottleItemOtherTextView);
TextView separator = (TextView) view.findViewById(R.id.separatorTextView);
int cursorPos = mCursor.getPosition();
switch (getItemViewType(cursorPos)) {
case TYPE_ITEM:
Log.d(TAG, "TYPE_ITEM");
separator.setVisibility(View.GONE);
break;
case TYPE_SEPARATOR:
String result = Utils.DateFromDataBaseToLocal(dateTime[0]); //Get date to european format
//String result = String.format("%s-%s-%s",day,month,year);
separator.setText(result + " Total : " ); // How get total....
separator.setVisibility(View.VISIBLE);
Log.d(TAG, "TYPE_SEPARATOR");
break;
}
int vitamine = cursor.getInt(cursor.getColumnIndex(BiberonDataBaseContract.BabyBottleTable.COLUMN_VITAMIN));
int iron = cursor.getInt(cursor.getColumnIndex(BiberonDataBaseContract.BabyBottleTable.COLUMN_IRON));
int saddle = cursor.getInt(cursor.getColumnIndex(BiberonDataBaseContract.BabyBottleTable.COLUMN_SADDLE));
int urin = cursor.getInt(cursor.getColumnIndex(BiberonDataBaseContract.BabyBottleTable.COLUMN_URIN));
boolean bVit = (vitamine != 0);
boolean bIron = (iron != 0);
boolean bSaddle = (saddle != 0);
boolean bUrin = (urin != 0);
String other = "";
StringBuilder sb = new StringBuilder(other);
if (bVit) sb.append("Vitamine-");
if (bIron) sb.append("Fer-");
if (bUrin) sb.append("Urine-");
if (bSaddle) sb.append("Selle-");
int lio = sb.lastIndexOf("-");
int l = (sb.length() - 1);
if (lio == l && lio > 0) sb.deleteCharAt(lio);
otherTv.setText(sb.toString());
}
#Override
public int getItemViewType(int position) {
return mSectionsDate.containsValue(position) ? TYPE_SEPARATOR : TYPE_ITEM;
}
private void findSection() {
if (mCursor != null) {
int nSection = 0;
int i = 0;
int total = 0;
mSections.clear();
Log.d(BABY_BOTTLE_TAG, "find section : count : " + mCursor.getCount());
int index = mCursor.getColumnIndex(BiberonDataBaseContract.BabyBottleTable.COLUMN_DATETIME);
mCursor.moveToFirst();
while (mCursor.isAfterLast() == false) {
String sectionName = mCursor.getString(index).split(" ")[0];
String[] sectionName2 = mCursor.getString(index).split(" ");
if (!mSections.containsKey(sectionName)) {
mSections.put(sectionName, i + nSection);
mSectionsDate.put(sectionName2[0], i);
mSectionIndex.add(i);
nSection++;
}
i++;
// mCursor.getString(2);
mCursor.moveToNext();
}
Log.d(TAG, "Found " + mSections.toString() + " section");
/// ;
}
}
}
Here is my loader request in my activity:
#Override
public Loader onCreateLoader(int id, Bundle args) {
String[] PROJECTION = new String[] {
BiberonDataBaseContract.BabyBottleTable._ID, // 0
BiberonDataBaseContract.BabyBottleTable.COLUMN_QUANTITY, // 1
BiberonDataBaseContract.BabyBottleTable.COLUMN_DATETIME, //2
BiberonDataBaseContract.BabyBottleTable.COLUMN_URIN,//3
BiberonDataBaseContract.BabyBottleTable.COLUMN_IRON,//4
BiberonDataBaseContract.BabyBottleTable.COLUMN_SADDLE,//5
BiberonDataBaseContract.BabyBottleTable.COLUMN_VITAMIN//6
};
// Filter results WHERE "_id" = 'babyId'
String selection = BiberonDataBaseContract.BabyBottleTable.COLUMN_BABY_ID + " = ?";
String[] selectionArgs = { String.valueOf(babyId) };
Uri testUri =BiberonDataBaseContract.BabyBottleTable.CONTENT_URI;
return new CursorLoader(this.getBaseContext(),testUri,PROJECTION,selection,selectionArgs,null);
}
In my database COLUMN_DATETIME is stored in "YYYY-MM-DD HH:MM:SS" format and quantity is an intger.
Have you got some idea please?
thanks
First make a dynamic arraylist which can contatin Integer, name it as date
List<Integer> date_20161216=new ArrayList<Integer>();
Now add all values to it by converting it to intger, i.e.,
//suppose you want to add 225ml and 255ml,then
String value=255ml;
date_20161216.add(Integer.parseInt(value.value.indexOf("m")));
Then when you want to add them
int total=0;
for(int i=0;i<date_20161216;i++){
total=total+date_20161216.get(i));
}
use Total to paste value in header
I want to display images from column 'images' in 'penyakit' table from sqlite database. That image display through TabGambar.java.
My friend told me than I can put address of image in database and save that image in drawable. But I don't understand how it works. I have tried to use string uri drawable but it can only display one image for all.
Previously, I had been looking for references on google and find so many tutorials. But I still don't get which part should I add or change. Can somebody help my problem?
This is my works.
TabGambar.java
public class TabGambar extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.tabgambar, container, false);
configureTextView(view);
return view;
}
private void configureTextView(View view) {
// TODO Auto-generated method stub
TextView namapenyakit = (TextView) view.findViewById(R.id.namapenyakit);
ImageView gambarpenyakit = (ImageView) view.findViewById(R.id.gambarpenyakit);
Bundle b = getActivity().getIntent().getExtras();
if (b != null)
{
namapenyakit.setText(b.getString("nama_penyakit"));
String uri = "#drawable/ayam1";
int imageResource = getResources().getIdentifier(uri, null, getActivity().getPackageName());
Drawable res = getResources().getDrawable(imageResource);
gambarpenyakit.setImageDrawable(res);
}
}
}
DBAdapter.java
public class DBAdapter extends SQLiteAssetHelper {
//nama database, versi, dan nama tabel yang akan dibuat.
private static final String DATABASE_NAME = "pakarayam";
private static final int DATABASE_VERSION = 1;
private static final String tabel_gejala = "gejala";
public static final String kd_gejala = "kode_gejala";
public static final String nm_gejala = "nama_gejala";
private static final String tabel_penyakit = "penyakit";
public static final String kd_penyakit = "kode_penyakit";
public static final String nm_penyakit = "nama_penyakit";
public static final String deskripsi = "deskripsi";
public static final String solusi = "solusi";
public static final String gambar = "gambar";
private static final String tabel_rule = "rule";
public static final String kd_rule = "kode_rule";
public static final String ko_gejala = "kode_gejala";
public static final String ko_penyakit = "kode_penyakit";
public static final String nilai_mb = "nilai_mb";
public static final String nilai_md = "nilai_md";
private static DBAdapter dbInstance;
private static SQLiteDatabase db;
private DBAdapter(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static DBAdapter getInstance(Context context)
{
if (dbInstance == null)
{
dbInstance = new DBAdapter(context);
db = dbInstance.getWritableDatabase();
}
return dbInstance;
}
#Override
public synchronized void close()
{
super.close();
if (dbInstance != null)
{
dbInstance.close();
}
}
public ArrayList<Gejala> getAllGejala()
{
ArrayList<Gejala> listGejala = new ArrayList<Gejala>();
Cursor cursor = db.query(tabel_gejala, new String[] {kd_gejala, nm_gejala
}, null, null, null, null, nm_gejala);
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
Gejala gejala = new Gejala();
gejala.setNama_gejala(cursor.getString(cursor
.getColumnIndexOrThrow(nm_gejala)));
gejala.setKode_gejala(cursor.getString(cursor
.getColumnIndexOrThrow(kd_gejala)));
listGejala.add(gejala);
} while (cursor.moveToNext());
}
return listGejala;
}
public List<Gejala> Search(String Nama_gejala)
{
List<Gejala> listGejala = new ArrayList<Gejala>();
Cursor cursor = db.query(tabel_gejala, new String[] {
kd_gejala,
nm_gejala },
nm_gejala + " like ?", new String[] {"%"+ Nama_gejala +"%"}, null, null, null, null);
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
Gejala gejala = new Gejala();
gejala.setNama_gejala(cursor.getString(cursor
.getColumnIndexOrThrow(nm_gejala)));
listGejala.add(gejala);
} while (cursor.moveToNext());
}
return listGejala;
}
public List<Penyakit> getAllPenyakit()
{
List<Penyakit> listPenyakit = new ArrayList<Penyakit>();
Cursor cursor = db.query(tabel_penyakit, new String[] {kd_penyakit, nm_penyakit, deskripsi, solusi, gambar
}, null, null, null, null, nm_penyakit);
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
Penyakit penyakit = new Penyakit();
penyakit.setNama_penyakit(cursor.getString(cursor
.getColumnIndexOrThrow(nm_penyakit)));
penyakit.setDeskripsi(cursor.getString(cursor
.getColumnIndexOrThrow(deskripsi)));
penyakit.setSolusi(cursor.getString(cursor
.getColumnIndexOrThrow(solusi)));
penyakit.setGambar(cursor.getString(cursor
.getColumnIndexOrThrow(gambar)));
listPenyakit.add(penyakit);
} while (cursor.moveToNext());
}
return listPenyakit;
}
public List<Penyakit> Searching (String Nama_penyakit)
{
List<Penyakit> listPenyakit = new ArrayList<Penyakit>();
Cursor cursor = db.query(tabel_penyakit, new String[] {
kd_penyakit,
nm_penyakit,
deskripsi,
solusi,
gambar},
nm_penyakit + " like ?", new String[] {"%"+ Nama_penyakit +"%"}, null, null, null, null);
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
Penyakit penyakit = new Penyakit();
penyakit.setNama_penyakit(cursor.getString(cursor
.getColumnIndexOrThrow(nm_penyakit)));
penyakit.setDeskripsi(cursor.getString(cursor
.getColumnIndexOrThrow(deskripsi)));
penyakit.setSolusi(cursor.getString(cursor
.getColumnIndexOrThrow(solusi)));
penyakit.setGambar(cursor.getString(cursor
.getColumnIndexOrThrow(gambar)));
listPenyakit.add(penyakit);
} while (cursor.moveToNext());
}
return listPenyakit;
}
public double getMB(/*int kode_rule,*/ String kode_gejala)
{
/*
Cursor cursor = db.query(tabel_rule, new String[]
{kd_rule, ko_gejala, ko_penyakit, nilai_mb, nilai_md
}, ko_gejala + " like ?", new String[] {"%"+ kode_gejala +"%"},
null, null, null, null);
double mb = 0;
cursor.moveToFirst();
mb = cursor.getDouble(cursor.getColumnIndexOrThrow(nilai_mb));
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
mb = cursor.getDouble(cursor.getColumnIndexOrThrow(nilai_mb));
} while (cursor.moveToNext());
}
*/
Cursor cursor = db.query(tabel_rule, new String[] {
kd_rule,
ko_gejala,
ko_penyakit,
nilai_mb,
nilai_md
}, ko_gejala + " = '"+kode_gejala+"'", null, null, null, null, null);
double mb = 0;
if(cursor != null){
cursor.moveToFirst();
while(!cursor.isAfterLast()){
mb = cursor.getDouble(3);
}
}
return mb;
}
public double getMD(/*int kode_rule,*/ String kode_gejala)
{
Cursor cursor = db.query(tabel_rule, new String[] {
kd_rule,
ko_gejala,
ko_penyakit,
nilai_mb,
nilai_md
}, ko_gejala + " = '"+kode_gejala+"'", null, null, null, null, null);
double md = 0;
// cursor.moveToFirst();
// md = cursor.getDouble(cursor.getColumnIndexOrThrow(nilai_md));
/*
if (cursor.getCount() >= 1)
{
cursor.moveToFirst();
do
{
md = cursor.getDouble(cursor.getColumnIndexOrThrow(nilai_md));
} while (cursor.moveToNext());
}
*/
if(cursor != null){
cursor.moveToFirst();
md = cursor.getDouble(cursor.getColumnIndexOrThrow(nilai_md));
System.out.print(nilai_md);
}
return md;
}
}
I'm not sure of the exact details here but basically, if you want to store images in your database you must store the information as a 'blob' of bytes.
You'll need to convert between bytes and Bitmap when you read from the DB and Bitmap and bytes when you want to write to the DB.
A URI is usually used for a file coming from your device storage or somewhere on a server/website etc.
If this is what you're looking for and you'd like more detailed help just let me know and I can provide more info.
I am fairly new to android programming and ran to a small problem. I have an activity that lets users select names from a muli-select listview. I can store it in an ArrayList fine but how do I pass that ArrayList as a bundle to be retrieved from the fragment? Thank you for any future answers.
MainActivity.java:
public class MainActivity extends Activity {
ListView myListView;
Button getResult;
ConnectionClass connectionClass;
private ArrayList<String> emp_names_list = new ArrayList<String>();
public ArrayList<Integer> emp_id_list = new ArrayList<Integer>();
MyArrayAdapter myArrayAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectionClass = new ConnectionClass();
emp_names_list.add("LOL");
//PAGKUHA NG RESULTS SA DB
try {
Connection con = connectionClass.CONN();
if (con == null) {
Toast.makeText(getApplicationContext(), "CONNECTION FAIL", Toast.LENGTH_LONG).show();
} else {
String query = "select * from users WHERE user_type=3";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
ArrayList<String> data1 = new ArrayList<String>();
while (rs.next()) {
String fname =rs.getString("user_fname");
String lname =rs.getString("user_lname");
String name = String.valueOf(fname)+" "+String.valueOf(lname);
emp_names_list.add(fname);
}
Toast.makeText(getApplicationContext(), "FETCH SUCCESS", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "FETCH FAIL", Toast.LENGTH_LONG).show();
Log.e("MYAPP", "exception", ex);
}
myListView = (ListView)findViewById(R.id.list);
//PARA SA LAYOUT
myArrayAdapter = new MyArrayAdapter(
this,
R.layout.row,
android.R.id.text1,
emp_names_list
);
myListView.setAdapter(myArrayAdapter);
myListView.setOnItemClickListener(myOnItemClickListener);
getResult = (Button)findViewById(R.id.getresult);
getResult.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String result = "";
/*
//getCheckedItemPositions
List<Integer> resultList = myArrayAdapter.getCheckedItemPositions();
for(int i = 0; i < resultList.size(); i++){
result += String.valueOf(resultList.get(i)) + " ";
}
*/
//getCheckedItems
List<String> resultList = myArrayAdapter.getCheckedItems();
for(int i = 0; i < resultList.size(); i++){
result += String.valueOf(resultList.get(i)) + "\n";
}
myArrayAdapter.getCheckedItemPositions().toString();
//Toast.makeText(getApplicationContext(),result, Toast.LENGTH_LONG).show();
try {
Connection con = connectionClass.CONN();
if (con == null) {
Toast.makeText(getApplicationContext(), "CONNECTION FAIL", Toast.LENGTH_LONG).show();
} else {
//FOR INSERTION ITO USING ARRAYLIST
String samp = "";
String names = "";
samp = myArrayAdapter.getCheckedItems().toString();
List<String> data1 = new ArrayList<String>(Arrays.asList(samp.replace("[","").replace("]","").split(",")));
//data1.add(samp);
for(String name : data1)
{
names = name;
String query = "INSERT INTO AUTOINC(PersonName)"+"VALUES('"+names+"')";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();
}
Toast.makeText(getApplicationContext(), "INSERT SUCCESS", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "INSERT FAILED", Toast.LENGTH_LONG).show();
Log.e("MYAPP", "exception", ex);
}
}});
}
OnItemClickListener myOnItemClickListener = new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
myArrayAdapter.toggleChecked(position);
}};
private class MyArrayAdapter extends ArrayAdapter<String>{
private HashMap<Integer, Boolean> myChecked = new HashMap<Integer, Boolean>();
public MyArrayAdapter(Context context, int resource,
int textViewResourceId, List<String> objects) {
super(context, resource, textViewResourceId, objects);
for(int i = 0; i < objects.size(); i++){
myChecked.put(i, false);
}
}
public void toggleChecked(int position){
if(myChecked.get(position)){
myChecked.put(position, false);
}else{
myChecked.put(position, true);
}
notifyDataSetChanged();
}
public List<Integer> getCheckedItemPositions(){
List<Integer> checkedItemPositions = new ArrayList<Integer>();
for(int i = 0; i < myChecked.size(); i++){
if (myChecked.get(i)){
(checkedItemPositions).add(i);
}
}
return checkedItemPositions;
}
public List<String> getCheckedItems(){
List<String> checkedItems = new ArrayList<String>();
for(int i = 0; i < myChecked.size(); i++){
if (myChecked.get(i)){
(checkedItems).add(emp_names_list.get(i));
}
}
return checkedItems;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if(row==null){
LayoutInflater inflater=getLayoutInflater();
row=inflater.inflate(R.layout.row, parent, false);
}
CheckedTextView checkedTextView = (CheckedTextView)row.findViewById(R.id.checkedTextView);
checkedTextView.setText(emp_names_list.get(position));
Boolean checked = myChecked.get(position);
if (checked != null) {
checkedTextView.setChecked(checked);
}
return row;
}
}
}
I have tried the following example but returns null:
Bundle bundle=new Bundle();
bundle.putBundle("bundle_DescriptioneTab",bundle_DescriptioneTab);
bundle.putBundle("bundle_User_Review",bundle_User_Review);
The first thing is that you have to declare your Class as Serializable
public class MyClass implements Serialisable{
}
and using
Bundle bundle = new Bundle();
bundle.putSerialisable("myclass",MyClass);
to send data of only class
And
If you want to send Arraylisyt use:
public class MyClass implements Parcelable{
}
Intent intent = new Intent(this,SecondaryActivity.class);
ArrayList<MyClass> mArrayList = new ArrayList<MyClass>();
and using
intent.putParcelableArrayListExtra("key", mArrayList);
You can store it in an object:
public class Thing implements Serializable {
private ArrayList<String> emp_names_list = new ArrayList<String>();
public ArrayList<Integer> emp_id_list = new ArrayList<Integer>();
[...]
}
And pass it like so:
bundle.putBundle("thing",object_thing);
I want to generate list view from an existing database . I have gone through several websites which will create database on run time ,but I don't want it like that . What I want is to read database from the exiting one, and populate listview from it. I am new to android development.
My database path .
assets/databases/example.sqlite
Check this library: SQLiteAssetHelper.
This is working example:
public class MyDataBase extends SQLiteAssetHelper {
private static final String TAG = "MyDataBase.class";
private static final String DATABASE_NAME = "news.sqlite";
private static final int DATABASE_VERSION = 1;
//Table Fields
private static final String ITEM_TITLE = "title";
private static final String ITEM_DESCRIPTION = "description";
private static final String ITEM_CATEGORY = "category";
private static final String ITEM_PUBDATE = "pubDate";
private static final String ITEM_CREATOR = "creator";
private static final String ITEM_URL = "url";
private static final String ITEM_IMAGE_URI = "image_uri";
private static final String ITEM_IMAGE_PATH = "image_path";
//Table name
private static final String TABLE = "Item";
public MyDataBase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//getting Items from database
public ArrayList<Item> getItems(){
ArrayList<Item> items=new ArrayList<>();
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String [] sqlSelect = {"id", ITEM_TITLE, ITEM_DESCRIPTION, ITEM_CATEGORY, ITEM_PUBDATE,
ITEM_CREATOR, ITEM_URL, ITEM_IMAGE_URI, ITEM_IMAGE_PATH };
String sqlTables = TABLE;
qb.setTables(sqlTables);
Cursor c = qb.query(db, sqlSelect, null, null,
null, null, null);
if (c.moveToFirst()) {
do {
Item item = new Item();
item.setTitle(c.getString(c.getColumnIndex(ITEM_TITLE)));
item.setCategory(c.getString(c.getColumnIndex(ITEM_CATEGORY)));
item.setDescription(c.getString(c.getColumnIndex(ITEM_DESCRIPTION)));
item.setPubDate(c.getString(c.getColumnIndex(ITEM_PUBDATE)));
item.setCreator(c.getString(c.getColumnIndex(ITEM_CREATOR)));
item.setURL(c.getString(c.getColumnIndex(ITEM_URL)));
item.setImage_uri(c.getString(c.getColumnIndex(ITEM_IMAGE_URI)));
item.setImage_path(c.getString(c.getColumnIndex(ITEM_IMAGE_PATH)));
items.add(item);
} while (c.moveToNext());
}
Log.i(TAG, "getItems() completed");
c.close();
db.close();
return items;
}
And now get your data from DB asynchronously:
private class DbTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
MyDataBase db = new MyDataBase(context);
list.clear();
list.addAll(db.getItems());
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
adapter.notifyDataSetChanged();
}
Hope this answer will be useful for you.
Happy coding!