Im Developing an Application where the ListView with Images will be displayed the text data and Images are downloaded from the services. I want to save the data in SQLite also I want to save the thumbnail Images my code is
public class MainActivity extends Activity {
// TAG for LogCat
public static final String TAG = "SQLiteDebug";
// list view control
private ListView mListUserInfo;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
// load list view control
mListUserInfo = (ListView)findViewById(R.id.listUsers);
// create data creator
UserInfoCreator creator = new UserInfoCreator(this);
// open connection
creator.open();
// insert data
creator.insert();
// add data to list view through adapter
mListUserInfo.setAdapter(new UserInfoAdapter(this, creator.queryAll()));//,thumbURLStrings));
// close connection
creator.close();
}
}
Data inserted in
public class UserInfoCreator {
static String [] thumbURLStrings = null;
// db adapter
private UserDbAdapter mDbAdapter;
/*
* constructor
*/
public UserInfoCreator(Context c) {
mDbAdapter = new UserDbAdapter(c);
}
/*
* open DBAdapter connection
*/
public void open() {
mDbAdapter.open();
}
/*
* insert random data
*/
public void insert() {
mDbAdapter.insertUser("Toteninsel 100. Fall", 1, "André Marx");
mDbAdapter.insertUser("Geisterbucht 150. Fall", 2, "Astrid Vollenbruch");
mDbAdapter.insertUser("Feuermond 125. Fall", 3, "André Marx");
mDbAdapter.insertUser("Top Secret Edition", 4, "Peter Lerangis");
mDbAdapter.insertUser("Der dreiTag", 5, "Hendrik Buchna");
mDbAdapter.insertUser("Die blutenden Bilder", 6, "Kari Erlhoff");
String xml = XMLfunction.getXML("http://ddfzentrale.europa-websites.de/Zentrale_php/XML/Buecher.xml");
Document doc = XMLfunction.XMLfromString(xml);
NodeList nodes = doc.getElementsByTagName("book");
String [] titleStrings = new String[nodes.getLength()];
String [] authorStrings = new String[nodes.getLength()];
Log.d("nodeLength","len: "+nodes.getLength());
for(int i=0;i < nodes.getLength();i++){
Element eleBook = (Element)nodes.item(i);
Log.d("Node_TagName", eleBook.getTagName());
NodeList titleNode = eleBook.getElementsByTagName("Title");
Element TitleEle = (Element) titleNode.item(0);
Log.i("Title", "Title - "+TitleEle.getFirstChild().getNodeValue());
titleStrings[i]= TitleEle.getFirstChild().getNodeValue();
NodeList AuthorFName1Node = eleBook.getElementsByTagName("AutorFName1");
Element AuthorFName1Ele = (Element) AuthorFName1Node.item(0);
Log.i("AuthorFName1","AuthorFName1 - "+AuthorFName1Ele.getFirstChild().getNodeValue());
NodeList AuthorLName1Node = eleBook.getElementsByTagName("AutorLName1");
Element AuthorLName1Ele = (Element) AuthorLName1Node.item(0);
Log.i("AuthorLName1","AuthorLName1 - "+AuthorLName1Ele.getFirstChild().getNodeValue());
authorStrings[i]=AuthorFName1Ele.getFirstChild().getNodeValue()+" "+AuthorLName1Ele.getFirstChild().getNodeValue();
mDbAdapter.insertUser(titleStrings[i], i, authorStrings[i]);
}
}
/*
* query all user info from db
*/
public List<UserInfo> queryAll() {
return mDbAdapter.fetchAllUsers();
}
/*
* close connection
*/
public void close() {
mDbAdapter.close();
}
}
Im parsing and inserting data in same class But with the Text I want to display and show thumbnail Image to display thumbnail with the images I used tutorial https://github.com/thest1/LazyList Please anyone have an Idea about how to store the Images in SQLite Please help me
Check this Code for Inserting images into Database downloading from Server :
Download Image from Server store it as BLOB and Retrieve it back.
It is not advisable to store images in SQLite database. But still it is possible to to so. You can convert the image to a byte array and store it as a BLOB in database. I hope it helps!
Related
I'm using cardslib library in my Android Studio project. I'm working on a CardListView. I'm retrieving each CardView information from an sqlite database row which has a BLOB field (used to store images). As shown in this picture, after filling CardListView from database, everything seems to be fine except for the CardThumbnail. It only shows the last iterated database row Bitmap field in every CardView of the list.
I'm using this code to iterate every sqlite row and fill CardListView items :
/* Retrieving items from database */
List<Item> items = dataBase.getAllItemsLOC();
int itemsLOCCount = items.size();
/* Iterating retrieved database items */
for (int i = 0; i < itemsLOCCount; i++) {
final Item item = items.get(i);
RentCard card = new RentCard(getActivity());
/* Add thumbnail */
CardThumbnail cardThumbnail = new CardThumbnail(getActivity());
cardThumbnail.setCustomSource(new CardThumbnail.CustomSource() {
#Override
public String getTag() {
return "com.google.android.apps.maps";
}
#Override
public Bitmap getBitmap() {
Bitmap bitmap = item.getImageBitmap();
return bitmap;
}
});
card.addCardThumbnail(cardThumbnail);
card.setDevise(item.getDevise());
/* ... setting the rest of the CardView properties ... */
card.setId("" + items.get(i).getId());
cards.add(card);
}
mCardArrayAdapter.notifyDataSetChanged();
Could you please help me identify the problem?
Thanks to Rami, I solved my problem by replacing this part of the code :
#Override
public String getTag() {
return "com.google.android.apps.maps";
}
By this :
#Override
public String getTag() {
return item.getId();
}
Now, my CardListView is correctly displaying each CardThumbnail Image from each sqlite row as shown in this picture.
I'm using a web service which returns data in JSON format like this:
{"content":[{"id":"1","asset_id":"62","title":"sample page","alias":"","introtext":"","fulltext":"Some Contents"},{"id":"2","asset_id":"62","title":"sample page2","alias":"","introtext":"","fulltext":"Some Contents"},{"id":"3","asset_id":"62","title":"sample page3","alias":"","introtext":"","fulltext":"Some Contents"}]}
onCreate() of MainActivity.java is :
boolean myFlag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.myView);
setFlag = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
dataSource = new ContentsDataSource(this);
dataSource.open();
parseAndIsertData();
}
the parseAndInsertData() is :
EDIT
private void parseAndIsertData() {
// Creating JSON Parser instance
MyJSONParser jParser = new MyJSONParser();
contentDataObject = new ContentDataObject();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(BASE_URL);
try {
// first time check if data is inserted
editor = setFlag.edit();
editor.putBoolean(MY_KEY, true);
// Getting Array of Contents
jsonArray = json.getJSONArray(MOBILE_CONTENT);
// looping through All Contents
if(!myFlag){
for(int i = 0; i < jsonArray.length(); i++){
contentDataObject.setId(jsonArray.getJSONObject(i).getInt(MOBILE_CONTENT_ID));
contentDataObject.setTitle(jsonArray.getJSONObject(i).getString(MOBILE_CONTENT_TITLE));
contentDataObject.setFulltext(jsonArray.getJSONObject(i).getString(MOBILE_CONTENT_FULLTEXT));
contentDataObject.setState(jsonArray.getJSONObject(i).getInt(MOBILE_CONTENT_STATE));
contentDataObject.setNewValue(jsonArray.getJSONObject(i).getInt(MOBILE_CONTENT_NEW));
contentDataObject.setHeader(jsonArray.getJSONObject(i).getString(MOBILE_CONTENT_HEADER));
contentDataObject.setColor(jsonArray.getJSONObject(i).getInt(MOBILE_CONTENT_COLOR));
contentDataObject.setNext(jsonArray.getJSONObject(i).getString(MOBILE_CONTENT_NEXT));
contentDataObject.setPrevious(jsonArray.getJSONObject(i).getString(MOBILE_CONTENT_PREVIOUS));
contentDataObject = dataSource.create(contentDataObject);
Log.i(MY_TAGT, "Data Inserted " + contentDataObject.getId() + " Times");
}
myFlag = setFlag.getBoolean(MY_KEY, false);
}
} catch (JSONException e) {
e.printStackTrace();
}
}}
Now My logcat for first time launch is :
and when I relaunch the app my logcat is :
Now I want ask that is this approach correct or not if YES! then will I be able to update that later on!!
Thanks!
You are correct that this code will insert the data multiple times. It will be up to you to implement a pattern that allows only one row.
You need to either query the data source first and not insert the data if it exists or you need to delete the data from the data source and then insert it every time. There are other patterns but these two will be the most common. Which one you choose will depend on what the data is and how you want it maintained or updated.
define a column in your table to be primary key or unique
use SQLiteDatabase.insertWithOnConflict(...) with the conflictAlgorithm parameter (the last one) set to ``SQLiteDatabase.CONFLICT_IGNORE`
See this
In my scenario i am having 3 records in sqlite which were fetched from websercive that contains id,name,description and image now i want to display the first record and second one after flipping the first record.and 3 one after second record flips..
What i have done so far is
while (cursor.moveToNext())
{
String temp_bookid = cursor.getString(0);
Log.i("temp_bookid",temp_bookid);
String temp_desc=cursor.getString(1);
byte[] temp_image1 = cursor.getBlob(2);
byte[] temp_image2 = cursor.getBlob(3);
String temp_id=cursor.getString(4);
String temp_name = cursor.getString(5);
String temp_bname=cursor.getString(6);
mapId.add(temp_id);
mapBname.add(temp_bname);
mapBookId.add(temp_bookid);
mapName.add(temp_name);
mapDesc.add(temp_desc);
map2.add(temp_image2);
map1.add(temp_image1);
Log.i("temp_id of the page in sqlite", temp_id);
TextView txtDesc = (TextView) findViewById(R.id.tDescription);
text = (TextView) findViewById(R.id.tTitle);
text.setText(temp_name);
txtDesc.setText(temp_desc);
ImageView img = (ImageView)findViewById(R.id.smallImage);
img.setImageBitmap(BitmapFactory.decodeByteArray(temp_image1, 0,temp_image1.length));
txtName1 = (TextView) findViewById(R.id.tvName);
txtName1.setText(temp_bname);
break;
}
mContext = this;
vf = (ViewFlipper) this.findViewById(R.id.vfShow);
vf.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(final View view, final MotionEvent event) {
detector.onTouchEvent(event);
Log.i("ew","ae");
return true;
}
});
I am able to display first record data when i set break; statement otherwise it is displaying last record data..How can proceed for this approach?
First fetch all the records and store in List<YourDataClass> myList object from onCreate method. As I have just giving you the examples
Now after fetching the data and stored in your list object you need to implement flipper change event so when flipper was change get the current position and using this position get the data as object from your list object. As you move right/left it will giving you the current position and you just need to use this position to fetch the records from list object
For example
Your POJO class will store the data MyData.java
public class MyData{
public long id = -1;
public String name = "";
public String description = "";
public String imagePath = ""; /// I don't know you want exactly, you need to implement image as per your requirement.
}
In your activity
private List<MyData> myList = new ArrayList<MyData>();
oncreate(){
fetchData(); // you need to implement this in AsyncTask so UI was not block just implement AsyncTask and call this method in doInBackground().
// after this you can implment View flipper and add view and set the data by fetch the list object using current view flipper position.
}
private void fetchData(){
while (cursor.moveToNext()){
MyData myData = new MyData();
myData.id = cursor.getLong(0);
myData.desc=cursor.getString(1);
myData.name = cursor.getString(5);
list.add(myData);
myData = null;
}
}
In my scenario i am having 3 records in sqlite which were fetched from websercive that contains id,name,description and image now i want to display the first record and second one after flipping the first record.and 3 one after second record flips..
What i have done so far is
while (cursor.moveToNext())
{
String temp_bookid = cursor.getString(0);
Log.i("temp_bookid",temp_bookid);
String temp_desc=cursor.getString(1);
byte[] temp_image1 = cursor.getBlob(2);
byte[] temp_image2 = cursor.getBlob(3);
String temp_id=cursor.getString(4);
String temp_name = cursor.getString(5);
String temp_bname=cursor.getString(6);
mapId.add(temp_id);
mapBname.add(temp_bname);
mapBookId.add(temp_bookid);
mapName.add(temp_name);
mapDesc.add(temp_desc);
map2.add(temp_image2);
map1.add(temp_image1);
Log.i("temp_id of the page in sqlite", temp_id);
TextView txtDesc = (TextView) findViewById(R.id.tDescription);
text = (TextView) findViewById(R.id.tTitle);
text.setText(temp_name);
txtDesc.setText(temp_desc);
ImageView img = (ImageView)findViewById(R.id.smallImage);
img.setImageBitmap(BitmapFactory.decodeByteArray(temp_image1, 0,temp_image1.length));
txtName1 = (TextView) findViewById(R.id.tvName);
txtName1.setText(temp_bname);
break;
}
mContext = this;
vf = (ViewFlipper) this.findViewById(R.id.vfShow);
vf.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(final View view, final MotionEvent event) {
detector.onTouchEvent(event);
Log.i("ew","ae");
return true;
}
});
I am able to display first record data when i set break; statement otherwise it is displaying last record data..How can proceed for this approach?
First fetch all the records and store in List<YourDataClass> myList object from onCreate method. As I have just giving you the examples
Now after fetching the data and stored in your list object you need to implement flipper change event so when flipper was change get the current position and using this position get the data as object from your list object. As you move right/left it will giving you the current position and you just need to use this position to fetch the records from list object
For example
Your POJO class will store the data MyData.java
public class MyData{
public long id = -1;
public String name = "";
public String description = "";
public String imagePath = ""; /// I don't know you want exactly, you need to implement image as per your requirement.
}
In your activity
private List<MyData> myList = new ArrayList<MyData>();
oncreate(){
fetchData(); // you need to implement this in AsyncTask so UI was not block just implement AsyncTask and call this method in doInBackground().
// after this you can implment View flipper and add view and set the data by fetch the list object using current view flipper position.
}
private void fetchData(){
while (cursor.moveToNext()){
MyData myData = new MyData();
myData.id = cursor.getLong(0);
myData.desc=cursor.getString(1);
myData.name = cursor.getString(5);
list.add(myData);
myData = null;
}
}
In my scenario i am having 3 records in sqlite which were fetched from websercive that contains id,name,description and image now i want to display the first record and second one after flipping the first record.and 3 one after second record flips..
What i have done so far is
while (cursor.moveToNext())
{
String temp_bookid = cursor.getString(0);
Log.i("temp_bookid",temp_bookid);
String temp_desc=cursor.getString(1);
byte[] temp_image1 = cursor.getBlob(2);
byte[] temp_image2 = cursor.getBlob(3);
String temp_id=cursor.getString(4);
String temp_name = cursor.getString(5);
String temp_bname=cursor.getString(6);
mapId.add(temp_id);
mapBname.add(temp_bname);
mapBookId.add(temp_bookid);
mapName.add(temp_name);
mapDesc.add(temp_desc);
map2.add(temp_image2);
map1.add(temp_image1);
Log.i("temp_id of the page in sqlite", temp_id);
TextView txtDesc = (TextView) findViewById(R.id.tDescription);
text = (TextView) findViewById(R.id.tTitle);
text.setText(temp_name);
txtDesc.setText(temp_desc);
ImageView img = (ImageView)findViewById(R.id.smallImage);
img.setImageBitmap(BitmapFactory.decodeByteArray(temp_image1, 0,temp_image1.length));
txtName1 = (TextView) findViewById(R.id.tvName);
txtName1.setText(temp_bname);
break;
}
mContext = this;
vf = (ViewFlipper) this.findViewById(R.id.vfShow);
vf.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(final View view, final MotionEvent event) {
detector.onTouchEvent(event);
Log.i("ew","ae");
return true;
}
});
I am able to display first record data when i set break; statement otherwise it is displaying last record data..How can proceed for this approach?
First fetch all the records and store in List<YourDataClass> myList object from onCreate method. As I have just giving you the examples
Now after fetching the data and stored in your list object you need to implement flipper change event so when flipper was change get the current position and using this position get the data as object from your list object. As you move right/left it will giving you the current position and you just need to use this position to fetch the records from list object
For example
Your POJO class will store the data MyData.java
public class MyData{
public long id = -1;
public String name = "";
public String description = "";
public String imagePath = ""; /// I don't know you want exactly, you need to implement image as per your requirement.
}
In your activity
private List<MyData> myList = new ArrayList<MyData>();
oncreate(){
fetchData(); // you need to implement this in AsyncTask so UI was not block just implement AsyncTask and call this method in doInBackground().
// after this you can implment View flipper and add view and set the data by fetch the list object using current view flipper position.
}
private void fetchData(){
while (cursor.moveToNext()){
MyData myData = new MyData();
myData.id = cursor.getLong(0);
myData.desc=cursor.getString(1);
myData.name = cursor.getString(5);
list.add(myData);
myData = null;
}
}