How to display image from storage to cardview? - android

i Was try to display image to card view but it not working and do not show error. Anyone help me please. I am new android. i checked file exists from downloaded folder: /storage/emulated/0/hismart/hinhmon
public class Album {
private String name;
private String gia;
private String thumbnail;
private String url;
public Album() {
}
public Album(String name, String gias, String thumbnail, String url) {
this.name = name;
this.gia = gias;
this.thumbnail = thumbnail;
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGia() {
return gia;
}
public void setGia(String gia) {
this.gia = gia;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Creat and add data to ArrayList:
List<String> ArrTenmon = new ArrayList<String>();
List<String> ArrGia = new ArrayList<String>();
List<String> ArrImgLocal = new ArrayList<String>();
List<String> ArrImgUrl = new ArrayList<String>();
and add
} Cursor c = db.getdata("select * from tbl_mon_app");
int count = c.getCount();
for (int i = 0; i < count; i++) {
new DownloadFile().execute(ArrImgUrl.get(i));
if (!fileloc.exists()) {
fileloc.mkdirs();
}
Album a = new Album(ArrTenmon.get(i), ArrGia.get(i), ArrImgLocal.get(i), ArrImgUrl.get(i));
albumList.add(a);
adapter.notifyDataSetChanged();
}
and in adapter:
String folder_main = "hismart/hinhmon";
File fileloc = new File(Environment.getExternalStorageDirectory(), folder_main);
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, count;
public ImageView thumbnail, overflow;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
count = (TextView) view.findViewById(R.id.count);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
overflow = (ImageView) view.findViewById(R.id.overflow);
}
}
public AlbumsAdapter(Context mContext, List<Album> albumList) {
this.mContext = mContext;
this.albumList = albumList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.album_card, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
Album album = albumList.get(position);
holder.title.setText(album.getName());
holder.count.setText(album.getGia() + " vnđ");
File imgFile = new File(fileloc+"/"+ "album" + position);
Glide.with(mContext).load(imgFile).into(holder.thumbnail);
}
#Override
public int getItemCount() {
return albumList.size();
}
And Problem in bellow can not display image, name of image is: album1, alubm2...
File imgFile = new File(fileloc+"/"+ "album" + position);
Glide.with(mContext).load(imgFile).into(holder.thumbnail);
Download file:
class DownloadFile extends AsyncTask<String, Integer, String> {
ProgressDialog mProgressDialog = new ProgressDialog(BookActivity.this);// Change Mainactivity.this with your activity name.
String strFolderName;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl) {
int count;
String targetFileName = null;
try {
URL url = new URL((String) aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
targetFileName = aurl[0].substring(aurl[0].lastIndexOf("/") + 1);
int lenghtOfFile = conexion.getContentLength();
String PATH = Environment.getExternalStorageDirectory() + "/hismart/hinhmon/";
File folder = new File(PATH);
if (!folder.exists()) {
folder.mkdir();//If there is no folder it will be created.
}
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(PATH + targetFileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return targetFileName;
}
protected void onProgressUpdate(Integer... progress) {
mProgressDialog.setProgress(progress[0]);
if (mProgressDialog.getProgress() == mProgressDialog.getMax()) {
mProgressDialog.dismiss();
}
}
protected void onPostExecute(String result) {
}
}
call asyntask to download file
Cursor c = db.getdata("select * from tbl_mon_app");
int count = c.getCount();
for (int i = 0; i < count; i++) {
new DownloadFile().execute(ArrImgLocal.get(i));
if (!fileloc.exists()) {
fileloc.mkdirs();
}
}
Logcat: Show nothing error
Result like this:image after run

I am sure Glide code which you used will works, i have used it many project. There might be problem in your image file. Cross check all the points Sd card permissions, file path use are getting correct
if not worked try to convert file to Uri, it may help
File imgFile = new File(fileloc+"/"+ "album" + position);
Uri imageUri = Uri.fromFile(file);
Glide.with(this).load(imageUri).into(imgView);

Related

Can fragments retain the state of collected data of cardviews

Before I change my design of my android application, I was wondering if I can retain the state of my fragment including all data collected when it is recreated. In my fragment i have an async task that collects the proper data usinf json and it publishes them to diffeerent cardviews. Here is my code:
LatestEventsFragment.java
public class LatestEventsFragment extends Fragment {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
ArrayList<Event> arrayList = new ArrayList();
ProgressDialog progressDialog;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setRetainInstance(true);
View view = inflater.inflate(R.layout.events_list, container, false);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView = (RecyclerView)view.findViewById(R.id.events_recycler);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
adapter = new EventsRecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
EventsAsyncTask eventsAsyncTask = new EventsAsyncTask();
eventsAsyncTask.execute();
return view;
}
class EventsAsyncTask extends AsyncTask<String, Event, String> {
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Please wait...");
progressDialog.setMessage("Loading");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPostExecute(String s) {
progressDialog.dismiss();
}
#Override
protected void onProgressUpdate(Event... values) {
arrayList.add(values[0]);
adapter.notifyDataSetChanged();
}
#Override
protected String doInBackground(String... params) {
try {
ServerConfig serverConfig = new ServerConfig();
URL url = new URL(serverConfig.getEvents_url());
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while((line = bufferedReader.readLine()) != null){
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
String json_string = stringBuilder.toString().trim();
JSONObject jsonObject = new JSONObject(json_string);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while(count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
count++;
String jsonString = JO.get("image").toString();
byte[] temp = Base64.decode(jsonString.getBytes(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(temp, 0, temp.length);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("UCT"));
Date date = dateFormat.parse(JO.getString("date_posted"));
Date server_date = dateFormat.parse(JO.getString("server_date"));
Event event = new Event(JO.getString("name"), decodedByte, JO.getInt("views"), date, server_date);
publishProgress(event);
Thread.sleep(500);
}
} catch (Exception e){
e.printStackTrace();
}
return null;
}
}
}
EventsRecyclerAdapter.java
public class EventsRecyclerAdapter extends RecyclerView.Adapter<EventsRecyclerAdapter.RecyclerViewHolder>{
ArrayList<Event> arrayList = new ArrayList<>();
public EventsRecyclerAdapter(ArrayList<Event> arrayList){
this.arrayList = arrayList;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.latest_events_card, parent, false);
return new RecyclerViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
Event event = arrayList.get(position);
try{
String views = String.valueOf(event.getViews())+" views";
String date_string = getTime(event.getServer_date().getTime() - event.getDate_posted().getTime());
holder.name.setText(event.getName());
holder.image.setImageBitmap(event.getImage());
holder.views.setText(views);
holder.date_posted.setText(date_string);
}catch (Exception e){
e.printStackTrace();
}
}
private String getTime(Long time_difference){
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = time_difference / daysInMilli;
int daysInt = (int)elapsedDays;
time_difference = time_difference % daysInMilli;
long elapsedHours = time_difference / hoursInMilli;
int hoursInt = (int)elapsedHours;
time_difference = time_difference % hoursInMilli;
long elapsedMinutes = time_difference / minutesInMilli;
int minutesInt = (int)elapsedMinutes;
//time_difference = time_difference % minutesInMilli;
//long elapsedSeconds = time_difference / secondsInMilli;
String date_string = String.valueOf(daysInt);
if(daysInt > 0) {
if (daysInt == 1) {
date_string = "1 Day";
} else if (daysInt > 1) {
date_string = daysInt + " Days";
}
}else if(hoursInt > 0){
if(hoursInt == 1){
date_string = "1 Hour ";
if(minutesInt > 1){
date_string = date_string + minutesInt + " Minutes";
}
} else if(hoursInt > 1){
date_string = hoursInt + " Hours ";
if(minutesInt > 1){
date_string = date_string + minutesInt + " Minutes";
}
}
}else if(minutesInt > 0){
if (minutesInt == 1) {
date_string = "1 Minute";
} else if (minutesInt > 1) {
date_string = minutesInt + " Minutes";
}
}
return date_string + " ago";
}
#Override
public int getItemCount() {
return arrayList.size();
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder{
protected TextView name, views, date_posted, start_date, end_date;
protected ImageView image;
public RecyclerViewHolder(View v){
super(v);
name = (TextView)v.findViewById(R.id.name);
image = (ImageView)v.findViewById(R.id.thumbnail);
views = (TextView)v.findViewById(R.id.views);
date_posted = (TextView)v.findViewById(R.id.date_posted);
}
}
}
and finally Events.java
public class Event {
private int id;
private String name;
private String description;
private String start_date;
private String end_date;
private double entrance_fee;
private Bitmap image;
private int views;
private Date date_posted;
private Date server_date;
public Event(String name, Bitmap image, int views, Date date_posted, Date server_date){
//int id, String name, , String start_date, double entrance_fee, Bitmap image, int views
this.setDescription(description);
this.setEnd_date(end_date);
this.setEntrance_fee(entrance_fee);
this.setId(id);
this.setImage(image);
this.setName(name);
this.setViews(views);
this.setStart_date(start_date);
this.setDate_posted(date_posted);
this.setServer_date(server_date);
}
public Date getServer_date() {
return server_date;
}
public void setServer_date(Date server_date) {
this.server_date = server_date;
}
public Date getDate_posted() {
return date_posted;
}
public void setDate_posted(Date date_posted) {
this.date_posted = date_posted;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getStart_date() {
return start_date;
}
public void setStart_date(String start_date) {
this.start_date = start_date;
}
public String getEnd_date() {
return end_date;
}
public void setEnd_date(String end_date) {
this.end_date = end_date;
}
public double getEntrance_fee() {
return entrance_fee;
}
public void setEntrance_fee(double entrance_fee) {
this.entrance_fee = entrance_fee;
}
public Bitmap getImage() {
return image;
}
public void setImage(Bitmap image) {
this.image = image;
}
public int getViews() {
return views;
}
public void setViews(int views) {
this.views = views;
}
}
You can use onSaveInstanceState inside your Fragment to save your data, then check the savedInstanceState variable inside onCreateView to see if it has data. If it does, just retrieve the data to recreate your view.
Inside Fragment:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
if(mDataToSave != null) {
savedInstanceState.putString("myData", mDataToSave);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
if(savedInstanceState != null){
String restoredData = (String)savedInstanceState.getString("myData");
//do something with restoredData
}
return rootView;
}
Just remember to change the put and get: savedInstanceState.putString() to savedInstanceState.put<WhateverYourDataTypeIs>()
If you're adding your Fragment through a Fragment Transaction in your Main Activity, make sure to only add it if the Main Activity's savedInstanceState is null. That way you won't replace the Fragment if it's already been added.
Inside Activity (if you have a Fragment Transaction):
if(savedInstanceState == null) {
Fragment newFragment = new MyFragment();
//add main fragment to fragment frame
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().add(R.id.fragment_container, newFragment).commit();
}

Adapter data changes alternatively

the situation is that the Adapter result keeps changing alternatively
i.e
First it is:
[http://cache3.asset-cache.net/xt/540053243.jpg?v=1&g=fs1|0|FPG|53|243&s=1&b=RjI4,
then:
[http://cache1.asset-cache.net/xt/471950448.jpg?v=1&g=fs1|0|EPL|50|448&s=1&b=RjI4
for the same network call.
This is my Adapter class:
public ImageCustomAdapter(ArrayList<ModelGettyImages> images,Context context) {
this.images = images;
this.context = context;
}
#Override
public ImagesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_row, parent, false);
ImagesViewHolder imagesViewHolder = new ImagesViewHolder(view);
return imagesViewHolder;
}
#Override
public void onBindViewHolder(ImagesViewHolder holder, int position) {
List<String> text = images.get(position).getTitle();
Log.d("TitleAdapter : ",images.get(position).getTitle().toString());
List<String> image = images.get(position).getImagePath();
Log.d("ImageAdapter : ", images.get(position).getImagePath().toString());
holder.title.setText(text.get(position));
Picasso.with(context).load(image.get(position)).fit().centerCrop().into(holder.image);
}
#Override
public int getItemCount() {
return images.size();
}
public class ImagesViewHolder extends RecyclerView.ViewHolder{
ImageView image;
TextView title;
public ImagesViewHolder(View itemView) {
super(itemView);
image = (ImageView)itemView.findViewById(R.id.imageView);
title = (TextView)itemView.findViewById(R.id.textView);
}
}
Interesting thing is that Title field is the same.
Response class:
private ModelGettyImages getImageDetails(String jsonData) throws JSONException {
boolean ascending = sharedPreferences.getBoolean("Ascending",false);
Log.d("Ascending",Boolean.toString(ascending));
boolean descending = sharedPreferences.getBoolean("Descending",false);
Log.d("descending",Boolean.toString(descending));
String pathURI = "";
JSONObject imageData = new JSONObject(jsonData);
int resultCount = imageData.optInt("result_count");
Log.d("Result Count: ", Integer.toString(resultCount));
JSONArray imageArray = imageData.optJSONArray("images");
for (int i = 0; i < imageArray.length(); i++)
{
JSONObject img = imageArray.optJSONObject(i);
allID.add(i,img.optString("id"));
allTitles.add(i,img.optString("title"));
Log.d("Image ID: ", allID.get(i));
Log.d("Image Title: ", allTitles.get(i));
JSONArray imagePath = img.optJSONArray("display_sizes");
for (int j = 0; j < imagePath.length(); j++)
{
JSONObject jb = imagePath.optJSONObject(j);
allImagePath.add(j,jb.getString("uri"));
Log.d("Image Path: ", allImagePath.get(j));
}
if( ascending )
{
Log.d("Ass","True");
Collections.sort(allTitles, new Comparator<String>() {
#Override
public int compare(String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
});
}
else if( descending )
{
Log.d("Des","True");
Collections.sort(allTitles, new Comparator<String>() {
#Override
public int compare(String s1, String s2) {
return s2.compareToIgnoreCase(s1);
}
});
}
Log.d("Image Title Sort: ", allTitles.get(i));
modelGettyImages.setID(allID);
modelGettyImages.setTitle(allTitles);
modelGettyImages.setImagePath(allImagePath);
ImagesList.add(modelGettyImages);
}
return modelGettyImages;
}
Try to reset imageview before loading url in it use this code
Picasso.with(this.context).cancelRequest(holder.image);
before
Picasso.with(context).load(image.get(position)).fit().centerCrop().into(holder.image);

Saving/Storeing an external image into SQLite Database

I have a book-App, where I scan a book with barcodescanner and retrieving the information from googlebooksapi.
At the moment I can save the general bookinfos, title, author, date, rating and shelf (where i want to display the book) in my SQLite database
Now I want to save the bookcover, which comes with the googleapi, too.
Can you tell me how I can save the image in my SQlite Database. By looking for solution I realized that I have to blob the image. but I dont know how.
Following my activties.
ScanActivity.java -> at the end of the code, I save the book data into sql db
public class ScanActivity extends AppCompatActivity implements OnClickListener {
private Button scanBtn, previewBtn, linkBtn, addBookBtn, librarybtn;
public TextView authorText, titleText, descriptionText, dateText, ratingCountText;
public EditText shelfText;
private LinearLayout starLayout;
private ImageView thumbView;
private ImageView[] starViews;
private Bitmap thumbImg;
public BookDBHelper bookDBHelper;
public SQLiteDatabase sqLiteDatabase1;
public Context context1 = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
//Fonts
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
Button myButtonViewScan = (Button) findViewById(R.id.scan_button);
myButtonViewScan.setTypeface(myTypeface);
TextView myWheretoSaveTextView = (TextView) findViewById(R.id.textView_wheretosave);
myWheretoSaveTextView.setTypeface(myTypeface);
//Scanbutton
scanBtn = (Button) findViewById(R.id.scan_button);
scanBtn.setOnClickListener(this);
//Preview Button
previewBtn = (Button) findViewById(R.id.preview_btn);
previewBtn.setVisibility(View.GONE);
previewBtn.setOnClickListener(this);
//Weblink Button
linkBtn = (Button) findViewById(R.id.link_btn);
linkBtn.setVisibility(View.GONE);
linkBtn.setOnClickListener(this);
/* //AddBookBtn
addBookBtn= (Button)findViewById(R.id.btn_savebook);
addBookBtn.setVisibility(View.GONE);
addBookBtn.setOnClickListener(this);
//LibraryButton
librarybtn = (Button) findViewById(R.id.btn_maps);
librarybtn.setVisibility(View.GONE);
librarybtn.setOnClickListener(this);
*/
authorText = (TextView) findViewById(R.id.book_author);
titleText = (TextView) findViewById(R.id.book_title);
descriptionText = (TextView) findViewById(R.id.book_description);
dateText = (TextView) findViewById(R.id.book_date);
starLayout = (LinearLayout) findViewById(R.id.star_layout);
ratingCountText = (TextView) findViewById(R.id.book_rating_count);
thumbView = (ImageView) findViewById(R.id.thumb);
shelfText = (EditText) findViewById(R.id.editText_wheretosave);
starViews = new ImageView[5];
for (int s = 0; s < starViews.length; s++) {
starViews[s] = new ImageView(this);
}
starViews = new ImageView[5];
for (int s = 0; s < starViews.length; s++) {
starViews[s] = new ImageView(this);
}
}
public void onClick(View v) {
if (v.getId() == R.id.scan_button) {
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
} else if (v.getId() == R.id.link_btn) {
//get the url tag
String tag = (String) v.getTag();
//launch the url
Intent webIntent = new Intent(Intent.ACTION_VIEW);
webIntent.setData(Uri.parse(tag));
startActivity(webIntent);
} else if (v.getId() == R.id.preview_btn) {
String tag = (String) v.getTag();
Intent intent = new Intent(this, EmbeddedBook.class);
intent.putExtra("isbn", tag);
startActivity(intent);
//launch preview
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve result of scanning - instantiate ZXing object
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
//check we have a valid result
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
//get format name of data scanned
String scanFormat = scanningResult.getFormatName();
previewBtn.setTag(scanContent);
if (scanContent != null && scanFormat != null && scanFormat.equalsIgnoreCase("EAN_13")) {
String bookSearchString = "https://www.googleapis.com/books/v1/volumes?" +
"q=isbn:" + scanContent + "&key=AIzaSyDminlOe8YitHijWd51n7-w2h8W1qb5PP0";
new GetBookInfo().execute(bookSearchString);
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"Not a valid scan!", Toast.LENGTH_SHORT);
toast.show();
}
Log.v("SCAN", "content: " + scanContent + " - format: " + scanFormat);
} else {
//invalid scan data or scan canceled
Toast toast = Toast.makeText(getApplicationContext(),
"No book scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
private class GetBookInfo extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... bookURLs) {
StringBuilder bookBuilder = new StringBuilder();
for (String bookSearchURL : bookURLs) {
HttpClient bookClient = new DefaultHttpClient();
try {
HttpGet bookGet = new HttpGet(bookSearchURL);
HttpResponse bookResponse = bookClient.execute(bookGet);
StatusLine bookSearchStatus = bookResponse.getStatusLine();
if (bookSearchStatus.getStatusCode() == 200) {
HttpEntity bookEntity = bookResponse.getEntity();
InputStream bookContent = bookEntity.getContent();
InputStreamReader bookInput = new InputStreamReader(bookContent);
BufferedReader bookReader = new BufferedReader(bookInput);
String lineIn;
while ((lineIn = bookReader.readLine()) != null) {
bookBuilder.append(lineIn);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return bookBuilder.toString();
}
protected void onPostExecute(String result) {
try {
previewBtn.setVisibility(View.VISIBLE);
JSONObject resultObject = new JSONObject(result);
JSONArray bookArray = resultObject.getJSONArray("items");
JSONObject bookObject = bookArray.getJSONObject(0);
JSONObject volumeObject = bookObject.getJSONObject("volumeInfo");
try {
titleText.setText(volumeObject.getString("title"));
} catch (JSONException jse) {
titleText.setText("");
jse.printStackTrace();
}
StringBuilder authorBuild = new StringBuilder("");
try {
JSONArray authorArray = volumeObject.getJSONArray("authors");
for (int a = 0; a < authorArray.length(); a++) {
if (a > 0) authorBuild.append(", ");
authorBuild.append(authorArray.getString(a));
}
authorText.setText(authorBuild.toString());
} catch (JSONException jse) {
authorText.setText("");
jse.printStackTrace();
}
try {
dateText.setText(volumeObject.getString("publishedDate"));
} catch (JSONException jse) {
dateText.setText("");
jse.printStackTrace();
}
try {
descriptionText.setText("DESCRIPTION: " + volumeObject.getString("description"));
} catch (JSONException jse) {
descriptionText.setText("");
jse.printStackTrace();
}
try {
double decNumStars = Double.parseDouble(volumeObject.getString("averageRating"));
int numStars = (int) decNumStars;
starLayout.setTag(numStars);
starLayout.removeAllViews();
for (int s = 0; s < numStars; s++) {
starViews[s].setImageResource(R.drawable.star);
starLayout.addView(starViews[s]);
}
} catch (JSONException jse) {
starLayout.removeAllViews();
jse.printStackTrace();
}
try {
ratingCountText.setText(volumeObject.getString("ratingsCount") + " ratings");
} catch (JSONException jse) {
ratingCountText.setText("");
jse.printStackTrace();
}
try {
boolean isEmbeddable = Boolean.parseBoolean
(bookObject.getJSONObject("accessInfo").getString("embeddable"));
if (isEmbeddable) previewBtn.setEnabled(true);
else previewBtn.setEnabled(false);
} catch (JSONException jse) {
previewBtn.setEnabled(false);
jse.printStackTrace();
}
try {
linkBtn.setTag(volumeObject.getString("infoLink"));
linkBtn.setVisibility(View.VISIBLE);
} catch (JSONException jse) {
linkBtn.setVisibility(View.GONE);
jse.printStackTrace();
}
try {
JSONObject imageInfo = volumeObject.getJSONObject("imageLinks");
new GetBookThumb().execute(imageInfo.getString("smallThumbnail"));
} catch (JSONException jse) {
thumbView.setImageBitmap(null);
jse.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
titleText.setText("NOT FOUND");
authorText.setText("");
descriptionText.setText("");
dateText.setText("");
starLayout.removeAllViews();
ratingCountText.setText("");
thumbView.setImageBitmap(null);
previewBtn.setVisibility(View.GONE);
shelfText.setText("");
}
}
}
private class GetBookThumb extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... thumbURLs) {
try {
URL thumbURL = new URL(thumbURLs[0]);
URLConnection thumbConn = thumbURL.openConnection();
thumbConn.connect();
InputStream thumbIn = thumbConn.getInputStream();
BufferedInputStream thumbBuff = new BufferedInputStream(thumbIn);
thumbImg = BitmapFactory.decodeStream(thumbBuff);
thumbBuff.close();
thumbIn.close();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
protected void onPostExecute(String result) {
thumbView.setImageBitmap(thumbImg);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void showMaps(View view) {
Intent intent = new Intent(this, MapsActivity.class);
startActivity(intent);
}
//HERE I SAVE THE RETRIEVED DATA
public void saveBook(View view) { //Click on save Book
String title = titleText.getText().toString();
String author = authorText.getText().toString();
String date = dateText.getText().toString();
String rating = ratingCountText.getText().toString();
String shelf = shelfText.getText().toString();
bookDBHelper = new BookDBHelper(context1);
sqLiteDatabase1 = bookDBHelper.getWritableDatabase();
bookDBHelper.addInformations(title, author, date, rating, shelf, sqLiteDatabase1);
Toast.makeText(getBaseContext(), "Data Saved", Toast.LENGTH_LONG).show();
bookDBHelper.close();
}
}
BookDBHelper.java
public class BookDBHelper extends SQLiteOpenHelper{
private static final String DATABASE_BOOKS_NAME = "BookINFO.DB";
private static final int DATABASE_BOOKS_VERS = 2;
private static final String CREATE_QUERY_BOOKS =
"CREATE TABLE "
+ BookContent.NewBookInfo.TABLE_NAME_BOOKS
+"("
+ BookContent.NewBookInfo.BOOK_ID + "INTEGER PRIMARY KEY, "
+ BookContent.NewBookInfo.BOOK_IMAGE +" BLOB, "
+ BookContent.NewBookInfo.BOOK_IMAGE_TAG +" TEXT, "
+ BookContent.NewBookInfo.BOOK_TITLE+" TEXT, "
+ BookContent.NewBookInfo.BOOK_AUTHOR+" TEXT, "
+ BookContent.NewBookInfo.BOOK_DATE+" TEXT, "
+ BookContent.NewBookInfo.BOOK_RATING+" TEXT, "
+ BookContent.NewBookInfo.BOOK_SHELF+" TEXT);";
public BookDBHelper(Context context){
super(context, DATABASE_BOOKS_NAME, null, DATABASE_BOOKS_VERS);
Log.e("DATABASE OPERATIONS", " DATABASE CREATED");
}
#Override
public void onCreate(SQLiteDatabase bookdb) {
bookdb.execSQL(CREATE_QUERY_BOOKS);
Log.e("DATABASE OPERATIONS", " DATABASE CREATED");
}
#Override
public void onUpgrade(SQLiteDatabase bookdb, int oldVersion, int newVersion) {
bookdb.execSQL(" DROP TABLE IS EXISTS " + BookContent.NewBookInfo.TABLE_NAME_BOOKS);
onCreate(bookdb);
}
public void addInformations( String booktitle, String bookauthor, String bookdate, String bookrating, String bookshelf, SQLiteDatabase bookdb)
{
ContentValues contentValues = new ContentValues();
contentValues.put(BookContent.NewBookInfo.BOOK_TITLE, booktitle);
contentValues.put(BookContent.NewBookInfo.BOOK_AUTHOR, bookauthor);
contentValues.put(BookContent.NewBookInfo.BOOK_DATE, bookdate);
contentValues.put(BookContent.NewBookInfo.BOOK_RATING, bookrating);
contentValues.put(BookContent.NewBookInfo.BOOK_SHELF, bookshelf);
bookdb.insert(BookContent.NewBookInfo.TABLE_NAME_BOOKS, null, contentValues);
Log.e("DATABASE OPERATIONS", "ON ROW INSERTED");
}
public Cursor getInformations(SQLiteDatabase bookdb){
Cursor cursor2;
String[] projections = {
BookContent.NewBookInfo.BOOK_TITLE,
BookContent.NewBookInfo.BOOK_AUTHOR,
BookContent.NewBookInfo.BOOK_DATE,
BookContent.NewBookInfo.BOOK_RATING,
BookContent.NewBookInfo.BOOK_SHELF};
cursor2 = bookdb.query(BookContent.NewBookInfo.TABLE_NAME_BOOKS, projections,null, null, null, null, null);
return cursor2;
}
Afterwards the infos will be displayed in a liestview.
BookDataListActivity
public class BookDataListActivity extends Activity {
public ListView booklistView;
private EditText inputSearch = null;
public SQLiteDatabase sqLiteDatabaseBooks = null;
public BookDBHelper bookDBHelper;
public Cursor cursor2;
public BookListDataAdapter bookListDataAdapter;
public final static String EXTRA_MSG1 = "title";
public final static String EXTRA_MSG2 = "author";
public final static String EXTRA_MSG3 = "date";
public final static String EXTRA_MSG4 = "rating";
public final static String EXTRA_MSG5 = "shelf";
public TextView editTextBooktitle;
public TextView editTextBookauthor;
public TextView editTextBookdate;
public TextView editTextBookrating;
public TextView editTextBookshelf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.book_data_list_layout);
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
TextView myTextView = (TextView) findViewById(R.id.text_yourbooks);
myTextView.setTypeface(myTypeface);
booklistView = (ListView) findViewById(R.id.book_list_view);
inputSearch = (EditText) findViewById(R.id.search_bar);
bookListDataAdapter = new BookListDataAdapter(getApplicationContext(), R.layout.row_book_layout);
booklistView.setAdapter(bookListDataAdapter);
//onItemClickListener
booklistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), BookInfoActivity.class);
editTextBooktitle = (TextView) view.findViewById(R.id.text_book_title);
String book_title = editTextBooktitle.getText().toString();
intent.putExtra(EXTRA_MSG1, book_title);
editTextBookauthor = (TextView) view.findViewById(R.id.text_book_author);
String bookauthor = editTextBookauthor.getText().toString();
intent.putExtra(EXTRA_MSG2, bookauthor);
editTextBookdate = (TextView) view.findViewById(R.id.text_book_date);
String bookdate = editTextBookdate.getText().toString();
intent.putExtra(EXTRA_MSG3, bookdate);
editTextBookrating = (TextView) view.findViewById(R.id.text_book_rating);
String bookrating = editTextBookrating.getText().toString();
intent.putExtra(EXTRA_MSG4, bookrating);
editTextBookshelf = (TextView) view.findViewById(R.id.text_book_shelf);
String bookshelf = editTextBookshelf.getText().toString();
intent.putExtra(EXTRA_MSG5, bookshelf);
startActivity(intent);
}
});
bookDBHelper = new BookDBHelper(getApplicationContext());
sqLiteDatabaseBooks = bookDBHelper.getReadableDatabase();
cursor2 = bookDBHelper.getInformations(sqLiteDatabaseBooks);
if (cursor2.moveToFirst()) {
do {
String booktitle, bookauthor, bookdate, bookrating, bookshelf;
booktitle = cursor2.getString(0);
bookauthor = cursor2.getString(1);
bookdate = cursor2.getString(2);
bookrating = cursor2.getString(3);
bookshelf = cursor2.getString(4);
BookDataProvider bookDataProvider = new BookDataProvider(booktitle, bookauthor, bookdate, bookrating, bookshelf);
bookListDataAdapter.add(bookDataProvider);
} while (cursor2.moveToNext());
}
}
}
And I think you will need the DataAdapter
DataListDataAdapter
public class BookListDataAdapter extends ArrayAdapter implements Filterable{
List booklist = new ArrayList();
public SQLiteDatabase sqLiteDatabaseBooks;
public BookListDataAdapter(Context context,int resource) {
super(context, resource);
}
static class BookLayoutHandler {
TextView BOOKTITLE, BOOKAUTHOR, BOOKDATE, BOOKRATING, BOOKSHELF;
}
#Override
public void add (Object object){
super.add(object);
booklist.add(object);
}
#Override
public int getCount() {
return booklist.size();
}
#Override
public Object getItem(int position) {
return booklist.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row1= convertView;
BookLayoutHandler bookLayoutHandler;
if(row1 == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row1 = layoutInflater.inflate(R.layout.row_book_layout, parent, false);
bookLayoutHandler = new BookLayoutHandler();
bookLayoutHandler.BOOKTITLE = (TextView) row1.findViewById(R.id.text_book_title);
bookLayoutHandler.BOOKAUTHOR = (TextView) row1.findViewById(R.id.text_book_author);
bookLayoutHandler.BOOKDATE = (TextView) row1.findViewById(R.id.text_book_date);
bookLayoutHandler.BOOKRATING = (TextView) row1.findViewById(R.id.text_book_rating);
bookLayoutHandler.BOOKSHELF = (TextView) row1.findViewById(R.id.text_book_shelf);
row1.setTag(bookLayoutHandler);
}else{
bookLayoutHandler = (BookLayoutHandler) row1.getTag();
}
BookDataProvider bookDataProvider = (BookDataProvider) this.getItem(position);
bookLayoutHandler.BOOKTITLE.setText(bookDataProvider.getBooktitle());
bookLayoutHandler.BOOKAUTHOR.setText(bookDataProvider.getBookauthor());
bookLayoutHandler.BOOKDATE.setText(bookDataProvider.getBookdate());
bookLayoutHandler.BOOKRATING.setText(bookDataProvider.getBookrating());
bookLayoutHandler.BOOKSHELF.setText(bookDataProvider.getBookshelf());
return row1;
}
BookDataProvider:
public class BookDataProvider {
private Bitmap bookimage;
private String booktitle;
private String bookauthor;
private String bookdate;
private String bookrating;
private String bookshelf;
public Bitmap getBookimage() {
return bookimage;
}
public void setBookimage(Bitmap bookimage) {
this.bookimage = bookimage;
}
public String getBooktitle() {
return booktitle;
}
public void setBooktitle(String booktitle) {
this.booktitle = booktitle;
}
public String getBookauthor() {
return bookauthor;
}
public void setBookauthor(String bookauthor) {
this.bookauthor = bookauthor;
}
public String getBookdate() {
return bookdate;
}
public void setBookdate(String bookdate) {
this.bookdate = bookdate;
}
public String getBookrating() {
return bookrating;
}
public void setBookrating(String bookrating) {
this.bookrating = bookrating;
}
public String getBookshelf() {
return bookshelf;
}
public void setBookshelf(String bookshelf) {
this.bookshelf = bookshelf;
}
public BookDataProvider ( Bitmap bookimage, String booktitle, String bookauthor, String bookdate, String bookrating, String bookshelf)
{
this.bookimage = bookimage;
this.booktitle = booktitle;
this.bookauthor = bookauthor;
this.bookdate = bookdate;
this.bookrating = bookrating;
this.bookshelf = bookshelf;
}
}
BookContent
public class BookContent {
public static abstract class NewBookInfo{ //Tabllenspalten deklaration
public static final String BOOK_IMAGE = "book_image";
public static final String BOOK_IMAGE_TAG ="image_tag";
public static final String BOOK_TITLE = "book_title";
public static final String BOOK_AUTHOR = "book_author";
public static final String BOOK_DATE = "book_date";
public static final String BOOK_RATING = "book_rating";
public static final String BOOK_SHELF = "book_shelf";
public static final String TABLE_NAME_BOOKS = "book_info";
public static final String BOOK_ID = "_id";
}
}
If I get your question right, you need to convert your image to a blob.
Well, blob is a byte array, so the following code would help you to convert your Bitmap to a byte[]
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, thumbImg);
byte[] blob = stream.toByteArray();
You can also get the whole implementation from another question here:
how to store Image as blob in Sqlite & how to retrieve it?
EDIT:
Of course, you have to edit your BookDBHelper.addInformations function and add one additional parameter for your image:
public void addInformations( String booktitle, String bookauthor, String bookdate, String bookrating, String bookshelf, byte[] image, SQLiteDatabase bookdb)
{
ContentValues contentValues = new ContentValues();
contentValues.put(BookContent.NewBookInfo.BOOK_TITLE, booktitle);
contentValues.put(BookContent.NewBookInfo.BOOK_AUTHOR, bookauthor);
contentValues.put(BookContent.NewBookInfo.BOOK_DATE, bookdate);
contentValues.put(BookContent.NewBookInfo.BOOK_RATING, bookrating);
contentValues.put(BookContent.NewBookInfo.BOOK_SHELF, bookshelf);
contentValues.put(YOUR_IMAGE_CONSTANT, image);
bookdb.insert(BookContent.NewBookInfo.TABLE_NAME_BOOKS, null, contentValues);
Log.e("DATABASE OPERATIONS", "ON ROW INSERTED");
}
Now you can save your Book through ScanActivity.saveBook:
public void saveBook(View view) { //Click on save Book
// ...
BitmapDrawable bitmapDrawable = (BitmapDrawable) thumbView.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
byte[] blob = stream.toByteArray();
sqLiteDatabase1 = bookDBHelper.getWritableDatabase();
bookDBHelper.addInformations(title, author, date, rating, shelf, blob, sqLiteDatabase1);
Toast.makeText(getBaseContext(), "Data Saved", Toast.LENGTH_LONG).show();
bookDBHelper.close();
}

Android - Listview .remove() function is not working as expected

I have a listview that is able to delete a specific image via onLongClick, but it isn't working so far. When testing, the dialog appears If i want to delete or not, i press Yes/Ok and the toast appears saying Item deleted, however the item is still there.
UPDATED ( I got the remove and delete function working thanks to user1140237)
UPDATED MAIN ACTIVITY
private String[] FilePathStrings;
private String[] FileNameStrings;
private File[] listFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yearbook);
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"/CapturyGallery");
// Check for SD Card
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Toast.makeText(this, "Error! No SDCARD Found!", Toast.LENGTH_LONG)
.show();
} else {
// Locate the image folder in your SD Card
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"/CapturyGallery");
// Create a new folder if no folder named CapturyGallery exist
file.mkdirs();
}
if (file.isDirectory())
{
listFile = file.listFiles();
// Create a String array for FilePathStrings
FilePathStrings = new String[listFile.length];
// Create a String array for FileNameStrings
FileNameStrings = new String[listFile.length];
for (int i = 0; i < listFile.length; i++)
{
//Get the path image file
FilePathStrings[i] = listFile[i].getAbsolutePath();
// Get the name image file
FileNameStrings[i] = listFile[i].getName();
}
}
Arrays.sort(listFile);
final ListAdapter listAdapter = new CustomAdapter(Yearbook.this, FilePathStrings, FileNameStrings);
ListView lv = (ListView) findViewById(R.id.ListingView);
lv.setAdapter(listAdapter);
final ArrayList<String> list = new ArrayList(Arrays.asList(FilePathStrings));
lv.setOnItemClickListener(this);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
//Deletes item
AlertDialog.Builder adb=new AlertDialog.Builder(Yearbook.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete " + FileNameStrings[position]);
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
File file = new File(list.get(positionToRemove));
if (file.delete()) {
list.remove(position);
((CustomAdapter) listAdapter).updateMyData(FilePathStrings, FileNameStrings);
Toast.makeText(getApplicationContext(), FileNameStrings[position] + " deleted", Toast.LENGTH_LONG).show();
}
}
});
adb.show();
return true;
}
});
}
CUSTOMADAPTER
public class CustomAdapter extends BaseAdapter {
private Activity activity;
private String[] filepath;
private String[] filename;
private static LayoutInflater inflater = null;
public CustomAdapter(Activity a, String[] fpath, String[] fname) {
activity = a;
filepath = fpath;
filename = fname;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void updateMyData(String[] fpath, String[] fname) {
filepath = fpath;
filename = fname;
notifyDataSetChanged();
}
#Override
public int getCount() {
return filepath.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
class MyViewHolder {
ImageView myImage;
TextView timestamp;
TextView myName;
TextView myHeader;
MyViewHolder(View v) {
myImage = (ImageView) v.findViewById(R.id.PicView);
timestamp = (TextView) v.findViewById(R.id.timestamp);
myName = (TextView) v.findViewById(R.id.myName);
myHeader = (TextView) v.findViewById(R.id.textSeparator);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
MyViewHolder holder = null;
if (vi == null) {
vi = inflater.inflate(R.layout.custom_row, null);
holder = new MyViewHolder(vi);
vi.setTag(holder);
} else {
holder = (MyViewHolder) vi.getTag();
}
Bitmap bmp = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(filepath[position]),100,100);
holder.myImage.setImageBitmap(bmp);
//PicImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
holder.myImage.setPadding(8, 8, 8, 8);
//Set Title
holder.myName.setText(filename[position]);
ExifInterface intf = null;
try {
intf = new ExifInterface(filepath[position]);
} catch(IOException e) {
e.printStackTrace();
}
if(intf != null) {
String dateString = intf.getAttribute(ExifInterface.TAG_DATETIME);
holder.timestamp.setText("Date Taken: " + dateString.toString());
}
return vi;
}
And so my last problem is, whenever i remove something from my listview it crashed. However, the file was indeed removed. Im not sure what is the error because i tested it on my mobile phone
You need to update list data in your custom adapter too. after removing than call notifydatasetchanged
Keep below method in you customadapter to udpate list data & after that call it in longpress
public void updateMyData(String[] fpath, String[] fname) {
filepath = fpath;
filename = fname;
notifyDataSetChanged();
}
You need to call this from longPress
list.remove(position);
((CustomAdapter )listAdapter).updateMyData( FilePathStrings, FileNameStrings); /// here in your case you need to define both array global sorry not time to clean up your code
Toast.makeText(getApplicationContext(), FileNameStrings[position] +" deleted",Toast.LENGTH_LONG).show();
UPDATED
To remove file from the mentioned dir & updating listview you need to delete file from that location first and than you need to update listview
File file = new File(list.get(position));
if (file.delete()) {// this will required permission in Manifest for Write_EXTERNAL_STORATE
// if file is deleted from SD CARD
list.remove(position);
((CustomAdapter )listAdapter).updateMyData( FilePathStrings, FileNameStrings); /// here in your case you need to define both array global sorry not time to clean up your code
Toast.makeText(getApplicationContext(), FileNameStrings[position] + " deleted", Toast.LENGTH_LONG).show();
}
*CustomAdapter *
public class CustomAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<String> filepath;
private ArrayList<String> filename;
private JSONArray jListData;
private int size = 0;
public CustomAdapter(Activity a, JSONArray jListData) {
activity = a;
this.jListData = jListData;
if (filepath != null)
size = jListData.length();
}
public void updateMyData(JSONArray jListData) {
this.jListData = jListData;
size = jListData.length();
notifyDataSetChanged();
}
#Override
public int getCount() {
return size;
}
public JSONObject getItem(int position) {
try {
return (JSONObject) jListData.get(position);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public long getItemId(int position) {
return position;
}
class MyViewHolder {
ImageView myImage;
TextView timestamp;
TextView myName;
TextView myHeader;
MyViewHolder(View v) {
myImage = (ImageView) v.findViewById(R.id.PicView);
timestamp = (TextView) v.findViewById(R.id.timestamp);
myName = (TextView) v.findViewById(R.id.myName);
myHeader = (TextView) v.findViewById(R.id.textSeparator);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
MyViewHolder holder = null;
try {
if (vi == null) {
vi = LayoutInflater.from(activity).inflate(R.layout.custom_row, parent, false);
holder = new MyViewHolder(vi);
vi.setTag(holder);
} else {
holder = (MyViewHolder) vi.getTag();
}
JSONObject rowObject = this.jListData.getJSONObject(position);
Bitmap bmp = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(rowObject.optString("filename")), 100, 100);
holder.myImage.setImageBitmap(bmp);
//PicImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
holder.myImage.setPadding(8, 8, 8, 8);
//Set Title
holder.myName.setText(rowObject.optString("filename"));
ExifInterface intf = null;
try {
intf = new ExifInterface(rowObject.optString("filepath"));
} catch (IOException e) {
e.printStackTrace();
}
if (intf != null) {
String dateString = intf.getAttribute(ExifInterface.TAG_DATETIME);
holder.timestamp.setText("Date Taken: " + dateString.toString());
}
} catch (JSONException e) {
}
return vi;
}
}
ACTIVITY
private JSONArray jArrayFileData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yearbook);
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "/CapturyGallery");
// Check for SD Card
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Toast.makeText(this, "Error! No SDCARD Found!", Toast.LENGTH_LONG)
.show();
} else {
// Locate the image folder in your SD Card
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "/CapturyGallery");
// Create a new folder if no folder named CapturyGallery exist
file.mkdirs();
}
jArrayFileData = new JSONArray();
if (file.isDirectory()) {
listFile = file.listFiles();
// Create a String array for FilePathStrings
FilePathStrings = new String[listFile.length];
// Create a String array for FileNameStrings
FileNameStrings = new String[listFile.length];
for (int i = 0; i < listFile.length; i++) {
JSONObject jObject = new JSONObject();
//Get the path image file
// FilePathStrings[i] = listFile[i].getAbsolutePath();
// Get the name image file
// FileNameStrings[i] = listFile[i].getName();
jObject.put("filepath", listFile[i].getAbsolutePath());
jObject.put("filename", listFile[i].getName());
jArrayFileData.put(jObject);
}
}
// Arrays.sort(listFile);
final ListAdapter listAdapter = new CustomAdapter(Yearbook.this, jArrayFileData);
ListView lv = (ListView) findViewById(R.id.ListingView);
lv.setAdapter(listAdapter);
// final ArrayList<String> list = new ArrayList(Arrays.asList(FilePathStrings));
lv.setOnItemClickListener(this);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
//Deletes item
AlertDialog.Builder adb = new AlertDialog.Builder(Yearbook.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete " + FileNameStrings[position]);
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
File file = new File(list.get(positionToRemove));
if (file.delete()) {
Toast.makeText(getApplicationContext(), jArrayFileData.getJSONObject(position).optString("filename") + " deleted", Toast.LENGTH_LONG).show();
jArrayFileData.remove(position);
// list.remove(position);
((CustomAdapter) listAdapter).updateMyData(jArrayFileData);
}
} catch (JSONException e) {
}
}
});
adb.show();
return true;
}
});
}
Use Arraylist<String> for fpath and fname in your code: Then to delete data from your listview.
Use this:
fpath.remove(index_toDelete);
fpath.remove(index_toDelete);
customAdapter.notifyDataSetChanged();

Implementing Picasso not loading image

After I decided to implement Universal Image Loader, because I had implemented a method that convert URL to Drawable, but since I don't know how many images it will return my SQLite query I decided to implement an Image Loader...
The thing is I'm stuck at the moment, cause I thought I did all what the GitHub say but at the time I load the Image it stays white and never loads.
On my Adapter class I've changed the line of the drawable as :
Picasso.with(context)
.load(Uri.parse(String.valueOf(item.icon)))
.resize(180, 180)
.placeholder(R.drawable.ic_launcher).into(viewHolder.ivIcon);
It works, beucase it shows yo me the ic_launcher icon... but never changes to the real image.
On my class where I fetch the data I have this (on my OnCreate()) :
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new MyAsyncTask().execute();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// progress.dismiss();
}
});
}
}).start();
}
Then I created an inner class where I fetch the data into my ListView... but it doesn't works. I don't know If I've to delte those methods since I've changed it to Picasso.
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
Conexion = new MarketSQLite(getActivity(), "market", null, 1);
mItems = new ArrayList<ListViewItem>();
db = Conexion.getReadableDatabase();
Cursor c;
c = db.rawQuery("Select NOM_OFER,PREU_OFERTA,DATA_F,FOTO,PERCENTDESCOMPTE from T_OFERTA", null);
c.moveToFirst();
if (c != null) {
do {
for (int i = 0; i < c.getColumnCount(); i++) {
Title = c.getString((c.getColumnIndex("NOM_OFER")));
Preu = c.getColumnIndex("PREU_OFERTA");
percent = c.getString((c.getColumnIndex("PERCENTDESCOMPTE")));
data_f = c.getString((c.getColumnIndex("DATA_F")));
URLTest = c.getString((c.getColumnIndex("FOTO")));
FOTO = Imagehandler(URLTest);
Log.e("", "" + c.getString(i));
// initialize and set the list adapter
// Toast.makeText(getActivity(), "Title" + Title + "Preu" + Preu + "Percent" + percent + "Cheese is " + data_f, Toast.LENGTH_LONG).show();
}
mItems.add(new ListViewItem(FOTO, Title, Preu.toString(), percent, data_f));
}while (c.moveToNext());
}
c.close();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
myAdapter = new ListViewDemoAdapter(getActivity(), mItems);
setListAdapter(myAdapter);
}
}
Where ImageHandler is a method that I've created before this is :
protected Drawable Imagehandler(String url) {
try {
url=url.replaceAll(" ", "%20");
InputStream is = (InputStream)this.fetch(url);
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (MalformedURLException e)
{
System.out.println(url);
System.out.println("error at URI"+e);
return null;
}
catch (IOException e)
{
System.out.println("io exception: "+e);
System.out.println("Image NOT FOUND");
return null;
}
}
protected Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
I don't know why isn't the image loading on my ListView if it shows all of the rest of data...
Instead of Drawable, try to get url string in your adapter like
Change From
public ListViewItem(Drawable icon, String title, String precio, String descuento, String date) {
this.icon = icon;
this.title = title;
this.precio = precio;
this.descuento = descuento;
this.date = date;
}
To
public ListViewItem(String icon_url, String title, String precio, String descuento, String date) {
this.icon_url = icon_url;
this.title = title;
this.precio = precio;
this.descuento = descuento;
this.date = date;
}
and use Picasso where you are loading your imageview like this -
Picasso.with(context)
.load(icon_url))
.resize(180, 180)
.placeholder(R.drawable.ic_launcher).into(viewHolder.ivIcon);
1) Your ListViewItem class should be like this -
public class ListViewItem {
public final String icon; // the drawable for the ListView item ImageView
public final String title; // the text for the ListView item title
public final String precio; // the price for the ListView item
public final String descuento; // the price for the discount for the ListView item
public final String date; //the date for the sale for the ListView item
// the text for the ListView item description
public ListViewItem(String icon_url, String title, String precio, String descuento, String date) {
this.icon = icon_url;
this.title = title;
this.precio = precio;
this.descuento = descuento;
this.date = date;
}
}
2) ListViewDemoAdapterClass
public class ListViewDemoAdapter extends ArrayAdapter<ListViewItem> {
Context context;
public ListViewDemoAdapter(Context context, List<ListViewItem> items) {
super(context, R.layout.listview_item, items);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null) {
// inflate the GridView item layout
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.listview_item, parent, false);
// initialize the view holder
viewHolder = new ViewHolder();
viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
viewHolder.tvPrice = (TextView) convertView.findViewById(R.id.tvPrice);
viewHolder.tvDiscount = (TextView) convertView.findViewById(R.id.tvDiscount);
viewHolder.tvDate = (TextView) convertView.findViewById(R.id.tvDatas);
convertView.setTag(viewHolder);
} else {
// recycle the already inflated view
viewHolder = (ViewHolder) convertView.getTag();
}
// update the item view
ListViewItem item = getItem(position);
Picasso.with(context)
.load(item.icon)
.resize(180, 180)
.placeholder(R.drawable.ic_launcher).into(viewHolder.ivIcon);
viewHolder.tvTitle.setText(item.title);
viewHolder.tvDiscount.setText(item.descuento);
viewHolder.tvPrice.setText(item.precio);
viewHolder.tvDate.setText(item.date);
return convertView;
}
private static class ViewHolder {
ImageView ivIcon;
TextView tvTitle;
TextView tvDiscount;
TextView tvPrice;
TextView tvDate;
}
}
ListFragment code, just add this
Cursor c;
c = db.rawQuery("Select
NOM_OFER,PREU_OFERTA,DATA_F,FOTO,PERCENTDESCOMPTE from T_OFERTA", null);
c.moveToFirst();
if (c != null) {
do {
for (int i = 0; i < c.getColumnCount(); i++) {
Title = c.getString((c.getColumnIndex("NOM_OFER")));
Preu = c.getColumnIndex("PREU_OFERTA");
percent = c.getString((c.getColumnIndex("PERCENTDESCOMPTE")));
data_f = c.getString((c.getColumnIndex("DATA_F")));
URLTest = c.getString((c.getColumnIndex("FOTO")));
Hope this helps :)
you just need to add your picasso code snippet as the following in your ImageHandler method and nothing else-
Picasso.with(context)
.load(url))
.resize(180, 180)
.placeholder(R.drawable.ic_launcher).into(your_imageview);
you don't need to download the image or make the bitmap or convert that into drawable to load from url. hope this helps you.

Categories

Resources