Getting Images from url in ListView - java

I am trying to get images from url and set it in a listview through my listviewadapter class. I am getting NULLPOINTEREXCEPTION at openConnection()
in getBitmapFromUrl method at the end.
Here is my code:
ListViewAdapter.java
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ListViewAdapter extends BaseAdapter {
public String msgType[] = new String[8];
public String msgData[] = new String[8];
public String msgTimeStamp[] = new String[8];
Bitmap[] myBitmap = new Bitmap[8];
public Activity context;
int positionX;
URL urlX;
public LayoutInflater inflater;
public ListViewAdapter(Activity context, String[] type, String[] data,
String[] timestamp) {
super();
this.context = context;
this.msgType = type;
this.msgData = data;
this.msgTimeStamp = timestamp;
this.inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return msgData.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder {
ImageView imgView;
TextView txtType;
TextView txtData;
TextView txtTimestamp;
Bitmap myBitmap;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item, null);
holder.imgView = (ImageView) convertView.findViewById(R.id.image);
holder.txtType = (TextView) convertView.findViewById(R.id.type);
holder.txtData = (TextView) convertView.findViewById(R.id.data);
holder.txtTimestamp = (TextView) convertView
.findViewById(R.id.timestamp);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
// holder.imgView.setImageBitmap(myBitmap[position]);
holder.txtType.setText(msgType[position]);
holder.txtTimestamp.setText(msgTimeStamp[position]);
if (msgType[position].equals("0"))
holder.txtData.setText(msgData[position]);
else {
holder.txtData.setText("");
URL url = null;
try {
url = new URL(msgData[position]);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
urlX=url;
positionX=position;
try {
Thread t = new Thread(new Runnable() {
public void run(){
myBitmap[positionX] = getBitmapFromUrl(urlX);
}
});
t.start();
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
holder.imgView.setImageBitmap(myBitmap[position]);
}
return convertView;
}
public Bitmap getBitmapFromUrl(URL url1) {
Bitmap Bitmap = null;
try {
HttpURLConnection connection = (HttpURLConnection) url1
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
}
return Bitmap;
}
}
EDIT:
Thread t = new Thread(new Runnable() {
public void run(){
myBitmap[positionX] = getBitmapFromUrl(urlX);
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
LOGCAT(after edit):
04-03 12:01:26.860: E/AndroidRuntime(11944): FATAL EXCEPTION: Thread-1155
04-03 12:01:26.860: E/AndroidRuntime(11944): java.lang.NullPointerException
04-03 12:01:26.860: E/AndroidRuntime(11944): at com.appquest.flatcassign.ListViewAdapter.getBitmapFromUrl(ListViewAdapter.java:127)
04-03 12:01:26.860: E/AndroidRuntime(11944): at com.appquest.flatcassign.ListViewAdapter$1.run(ListViewAdapter.java:107)
04-03 12:01:26.860: E/AndroidRuntime(11944): at java.lang.Thread.run(Thread.java:856)

Hi I update your base adpter class see blow with implement of the picasso library, you just have to copy and replace the code, sure help you. do not forget to add the jar file.
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ListViewAdapter extends BaseAdapter {
public String msgType[] = new String[8];
public String msgData[] = new String[8];
public String msgTimeStamp[] = new String[8];
public Activity context;
public LayoutInflater inflater;
public ListViewAdapter(Activity context, String[] type, String[] data,
String[] timestamp) {
super();
this.context = context;
this.msgType = type;
this.msgData = data;
this.msgTimeStamp = timestamp;
this.inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return msgData.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
ImageView imgView;
TextView txtType;
TextView txtData;
TextView txtTimestamp;
Bitmap myBitmap;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item, null);
holder.imgView = (ImageView) convertView.findViewById(R.id.image);
holder.txtType = (TextView) convertView.findViewById(R.id.type);
holder.txtData = (TextView) convertView.findViewById(R.id.data);
holder.txtTimestamp = (TextView) convertView
.findViewById(R.id.timestamp);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
// holder.imgView.setImageBitmap(myBitmap[position]);
holder.txtType.setText(msgType[position]);
holder.txtTimestamp.setText(msgTimeStamp[position]);
if (msgType[position].equals("0"))
holder.txtData.setText(msgData[position]);
else {
holder.txtData.setText("");
Picasso.with(context).load(msgData[position]).into(holder.imgView);
}
return convertView;
}
}
Thank you.

Related

Control over loading item in listview from server after scrolldown

I would like to stop listview after loading from server instead of moving up when I scrolldown veryfast.
I tired setFriction property also but it doesn't seem to be that much effective.
Can anybody suggest how to control this?
This is my code.
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private DataListAdapter dataListAdapter;
Activity _activity;
ArrayList<DataObject> dataArrayList;
private ListView lv;
private String jsonResult;
boolean loadingMore = false;
private DataObject dataObject;
View footerView;
ProgressDialog progress;
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_activity = this;
lv = (ListView) findViewById(R.id.listView1);
dataArrayList = new ArrayList<DataObject>();
footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.loading_view, null, false);
if (isOnline(_activity)) {
progress = new ProgressDialog(this);
lv.setFriction(ViewConfiguration.getScrollFriction() * 0.5f);
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if ((lastInScreen == totalItemCount) && !(loadingMore)) {
new LoadJsonData().execute();
}
}
});
}
dataListAdapter = new DataListAdapter(dataArrayList);
lv.setAdapter(dataListAdapter);
}
private void scrollNotifyChange() {
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if ((lastInScreen == totalItemCount) && !(loadingMore)) {
new LoadJsonData().execute();
}
}
});
}
public static boolean isOnline(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
private class LoadJsonData extends AsyncTask<Void, Void, String> {
// ProgressDialog progress;
#Override
protected void onPreExecute() {
super.onPreExecute();
if (dataArrayList.size() == 0) {
progress = ProgressDialog.show(_activity, "Progress",
"Please wait", true);
}
}
#Override
protected String doInBackground(Void... params) {
String jsonResult = "";
loadingMore = true;
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet("https://datatables.net/examples/server_side/scripts/server_processing.php");
HttpResponse httpResponse = httpclient.execute(request);
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null) {
jsonResult = convertInputStreamToString(inputStream);
} else {
jsonResult = "Did not work!";
}
} catch (Exception e) {
Log.e(TAG, "GET failed", e);
}
return jsonResult;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progress.dismiss();
try {
JSONObject dataJsontObject = new JSONObject(result);
JSONArray dataJsonArray = dataJsontObject.getJSONArray("data");
for (int i = 0; i < dataJsonArray.length(); i++) {
JSONArray dataSubArray = dataJsonArray.getJSONArray(i);
DataObject dataObject = new DataObject();
dataObject.setName((String) dataSubArray.get(0));
dataObject.setType((String) dataSubArray.get(1));
dataObject.setProfession((String) dataSubArray.get(2));
dataObject.setCountry((String) dataSubArray.get(3));
dataObject.setCurrency((String) dataSubArray.get(5));
dataArrayList.add(dataObject);
// dataListAdapter.add(dataObject);
}
lv.addFooterView(footerView);
dataListAdapter.notifyDataSetChanged();
loadingMore = false;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class DataListAdapter extends BaseAdapter {
ArrayList<DataObject> dataListObject = new ArrayList<DataObject>();
public DataListAdapter(ArrayList<DataObject> dataListObject) {
this.dataListObject = dataListObject;
}
#Override
public int getCount() {
return dataListObject.size();
}
#Override
public Object getItem(int position) {
return dataListObject.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(_activity);
convertView = inflater.inflate(R.layout.single_row, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.type = (TextView) convertView.findViewById(R.id.type);
holder.profession = (TextView) convertView.findViewById(R.id.profession);
holder.country = (TextView) convertView.findViewById(R.id.country);
holder.currency = (TextView) convertView.findViewById(R.id.currecy);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final DataObject current = dataListObject.get(position);
holder.name.setText("Name--" + current.getName());
holder.type.setText("Type--" + current.getType());
holder.profession.setText("Professoion--" + current.getProfession());
holder.country.setText("Country--" + current.getCountry());
holder.currency.setText("Currency--" + current.getCurrency());
return convertView;
}
}
static class ViewHolder {
TextView name;
TextView type;
TextView profession;
TextView country;
TextView currency;
}
public static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
inputStream.close();
return result;
}
}

caching images from json in listview?

I followed this lesson here which talk about json parsing and image loading in list view the example works good but it has a problem in imageview when scrolling up & down all images reloading so can anyone solve this problem?
this the adapter of listview
package com.wingnity.jsonparsingtutorial;
import java.io.InputStream;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
holder.tvName = (TextView) v.findViewById(R.id.tvName);
holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
holder.tvSpouse = (TextView) v.findViewById(R.id.tvSpouse);
holder.tvChildren = (TextView) v.findViewById(R.id.tvChildren);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.ic_launcher);
new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
holder.tvName.setText(actorList.get(position).getName());
holder.tvDescription.setText(actorList.get(position).getDescription());
holder.tvDOB.setText("B'day: " + actorList.get(position).getDob());
holder.tvCountry.setText(actorList.get(position).getCountry());
holder.tvHeight.setText("Height: " + actorList.get(position).getHeight());
holder.tvSpouse.setText("Spouse: " + actorList.get(position).getSpouse());
holder.tvChildren.setText("Children: " + actorList.get(position).getChildren());
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView tvName;
public TextView tvDescription;
public TextView tvDOB;
public TextView tvCountry;
public TextView tvHeight;
public TextView tvSpouse;
public TextView tvChildren;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
Used the Android Universal Image-Loader This is best
Declare
private ImageLoader imageLoader1;
On Create
imageLoader1 = ImageLoader.getInstance();
imageLoader1.init(ImageLoaderConfiguration.createDefault(getActivity()));
no_image here a drawable image without any image load in Cache
DisplayImageOptions
options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.showImageOnLoading(R.drawable.no_image) // resource or drawable
.showImageForEmptyUri(R.drawable.no_image) // resource or drawable
.showImageOnFail(R.drawable.no_image)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
imageLoader1.displayImage(yourpath.replace(" ", "%20"), ivprofile, options);
You Can Use Piccaso Also and Glide also
here is the code after editing it works like a charm
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
public class ActorAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Actors> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public ActorAdapter(Activity activity, List<Actors> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_item, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.flag);
TextView title = (TextView) convertView.findViewById(R.id.rank);
// getting movie data for the row
Actors m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getImage(), imageLoader);
// title
title.setText(m.getName());
return convertView;
}
}

RecyclerView lags on scrolling

I'm having an issue where when the RecyclerView has a big amount of items (say 2000) the scrolling is really laggy.
I would be really really thankful if someone helps me improving it. Thanks in advance.
EDIT: The lag may be caused when using this FastScroll library. If someone is able to do some pull requests to improve it, I'm sure the dev will be really thankful. https://github.com/plusCubed/recycler-fast-scroll
Here's the Fragment code:
package jahirfiquitiva.apps.iconshowcase.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.pluscubed.recyclerfastscroll.RecyclerFastScroller;
import java.util.ArrayList;
import java.util.Locale;
import jahirfiquitiva.apps.iconshowcase.R;
import jahirfiquitiva.apps.iconshowcase.adapters.IconsAdapter;
import jahirfiquitiva.apps.iconshowcase.utilities.Preferences;
import jp.wasabeef.recyclerview.adapters.AlphaInAnimationAdapter;
import jp.wasabeef.recyclerview.adapters.ScaleInAnimationAdapter;
public class IconsFragment extends Fragment {
private IconsAdapter mAdapter;
private Preferences mPrefs;
private ArrayList<String> iconsNames, filteredIconsList;
private ArrayList<Integer> iconsInts, filteredIconsInts;
private ViewGroup layout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mPrefs = new Preferences(getActivity());
if (layout != null) {
ViewGroup parent = (ViewGroup) layout.getParent();
if (parent != null) {
parent.removeView(layout);
}
}
try {
layout = (ViewGroup) inflater.inflate(R.layout.icons_grid, container, false);
} catch (InflateException e) {
}
RecyclerFastScroller fastScroller =
(RecyclerFastScroller) layout.findViewById(R.id.rvFastScroller);
fastScroller.setVisibility(View.GONE);
RecyclerView iconsGrid = (RecyclerView) layout.findViewById(R.id.iconsGrid);
iconsGrid.setHasFixedSize(true);
iconsGrid.setLayoutManager(new GridLayoutManager(getActivity(),
getResources().getInteger(R.integer.icon_grid_width)));
mAdapter = new IconsAdapter(getActivity(), new ArrayList<String>(), new ArrayList<Integer>());
if (getArguments() != null) {
iconsNames = getArguments().getStringArrayList("iconsNamesList");
iconsInts = getArguments().getIntegerArrayList("iconsArray");
mAdapter.setIcons(iconsNames, iconsInts);
}
iconsGrid.setAdapter(mPrefs.getAnimationsEnabled() ? animAdapter(mAdapter) : mAdapter);
fastScroller.setRecyclerView(iconsGrid);
fastScroller.setHideDelay(500);
fastScroller.setVisibility(View.VISIBLE);
return layout;
}
public static IconsFragment newInstance(ArrayList<String> iconsNames, ArrayList<Integer> iconsArray) {
IconsFragment fragment = new IconsFragment();
Bundle args = new Bundle();
args.putStringArrayList("iconsNamesList", iconsNames);
args.putIntegerArrayList("iconsArray", iconsArray);
fragment.setArguments(args);
return fragment;
}
public void performSearch(String query) {
filter(query, mAdapter);
}
private synchronized void filter(CharSequence s, IconsAdapter adapter) {
if (s == null || s.toString().trim().isEmpty()) {
if (filteredIconsList != null) {
filteredIconsList = null;
}
if (filteredIconsInts != null) {
filteredIconsList = null;
}
adapter.clearIconsList();
adapter.setIcons(iconsNames, iconsInts);
adapter.notifyDataSetChanged();
} else {
if (filteredIconsList != null) {
filteredIconsList.clear();
}
if (filteredIconsInts != null) {
filteredIconsList = null;
}
filteredIconsList = new ArrayList<String>();
filteredIconsInts = new ArrayList<Integer>();
for (int i = 0; i < iconsNames.size(); i++) {
String name = iconsNames.get(i);
if (name.toLowerCase(Locale.getDefault())
.startsWith(s.toString().toLowerCase(Locale.getDefault()))) {
filteredIconsList.add(iconsNames.get(i));
filteredIconsInts.add(iconsInts.get(i));
}
}
adapter.clearIconsList();
adapter.setIcons(filteredIconsList, filteredIconsInts);
adapter.notifyDataSetChanged();
}
}
private ScaleInAnimationAdapter animAdapter(IconsAdapter iconsAdapter) {
AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(iconsAdapter);
ScaleInAnimationAdapter scaleAdapter = new ScaleInAnimationAdapter(alphaAdapter);
scaleAdapter.setFirstOnly(true);
return scaleAdapter;
}
}
And RecyclerView adapter:
package jahirfiquitiva.apps.iconshowcase.adapters;
import android.content.Context;
import android.content.res.Resources;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.afollestad.materialdialogs.MaterialDialog;
import java.util.ArrayList;
import java.util.Locale;
import jahirfiquitiva.apps.iconshowcase.R;
import jahirfiquitiva.apps.iconshowcase.utilities.Util;
public class IconsAdapter extends RecyclerView.Adapter<IconsAdapter.IconsHolder> implements View.OnClickListener {
private final Context context;
private ArrayList<String> iconsList = new ArrayList<>();
private ArrayList<Integer> iconsArray = new ArrayList<>();
public IconsAdapter(Context context, ArrayList<String> iconsList, ArrayList<Integer> iconsArray) {
this.context = context;
this.iconsList = iconsList;
this.iconsArray = iconsArray;
}
public void setIcons(ArrayList<String> iconsList, ArrayList<Integer> iconsArray) {
this.iconsList.addAll(iconsList);
this.iconsArray.addAll(iconsArray);
this.notifyItemRangeInserted(0, iconsList.size() - 1);
}
public void clearIconsList() {
this.iconsList.clear();
this.iconsArray.clear();
}
#Override
public IconsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
return new IconsHolder(inflater.inflate(R.layout.item_icon, parent, false));
}
#Override
public void onBindViewHolder(IconsHolder holder, int position) {
if (iconsArray.size() > 0) {
holder.icon.setImageResource(iconsArray.get(position));
}
holder.view.setTag(position);
holder.view.setOnClickListener(this);
setAnimation(holder.icon, position);
}
private int lastPosition = -1;
private void setAnimation(View viewToAnimate, int position) {
if (position > lastPosition) {
viewToAnimate.setHasTransientState(true);
lastPosition = position;
}
}
#Override
public int getItemCount() {
return iconsList == null ? 0 : iconsList.size();
}
#Override
public void onClick(View v) {
int position = (Integer) v.getTag();
int resId = iconsArray.get(position);
String name = iconsList.get(position).toLowerCase(Locale.getDefault());
MaterialDialog dialog = new MaterialDialog.Builder(context)
.customView(R.layout.dialog_icon, false)
.title(Util.makeTextReadable(name))
.positiveText(R.string.close)
.show();
if (dialog.getCustomView() != null) {
ImageView dialogIcon = (ImageView) dialog.getCustomView().findViewById(R.id.dialogicon);
dialogIcon.setImageResource(resId);
}
}
class IconsHolder extends RecyclerView.ViewHolder {
final View view;
final ImageView icon;
IconsHolder(View v) {
super(v);
view = v;
icon = (ImageView) v.findViewById(R.id.icon_img);
}
}
}
From your comment you have mentioned that, you are not using any library for loading images, that's might be the issue, since libraries like Picasso ,glide... Use an asynctask to load images load on the main that is refused. You can do the same by writing it yourself but you will end up re-inventing the wheel again
How big are the images? Try to downscale them (for example resize through Picasso)

Image Bitmap from URL

I am trying to get images from URLs in a string array and my app is crashing. It is crashing on line 110: InputStream input = connection.getInputStream(); What am I doing wrong?
Here is my class:
package kyfb.android.kyfb.com.kyfb;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.Image;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by KFB on 8/12/14.
*/
class ActionAlertsAdapter extends BaseAdapter {
private LayoutInflater inflater;
public ActionAlertsAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
public int getCount() {
// TODO Auto-generated method stub
return ActionAlertsFragment.title.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(convertView == null){
convertView = inflater.inflate(R.layout.item_feed, null);
holder = new ViewHolder();
holder.lytItemFeed = (RelativeLayout) convertView.findViewById(R.id.lytItemFeed);
holder.txtTitle= (TextView) convertView.findViewById(R.id.txtTitle);
holder.txtPubDate = (TextView) convertView.findViewById(R.id.txtPubDate);
holder.thumbnail = (ImageView) convertView.findViewById(R.id.thumbnail);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
if((position%2)!=0){
holder.lytItemFeed.setBackgroundColor(Color.TRANSPARENT);
}else{
holder.lytItemFeed.setBackgroundColor(Color.TRANSPARENT);
}
holder.txtTitle.setText(ActionAlertsFragment.title[position]);
holder.txtPubDate.setText(ActionAlertsFragment.pubDate[position]);
Bitmap bitmap = getBitmapFromURL(ActionAlertsFragment.thumb[position]);
if(bitmap == null) {
holder.thumbnail.setImageResource(R.drawable.kyfb);
}
else {
holder.thumbnail.setImageBitmap(bitmap);
}
holder.txtTitle.setTextColor(Color.WHITE);
holder.txtPubDate.setTextColor(Color.WHITE);
return convertView;
}
public Bitmap getBitmapFromURL(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
static class ViewHolder {
TextView txtTitle, txtPubDate;
ImageView thumbnail;
RelativeLayout lytItemFeed;
}
}
This doesn't directly answer your question, but you might want to consider using an image loading library such as Picasso or Volley. There is a lot of complexity--some subtle, some not so much--in loading images from network, even more so when you're trying to do it in a ListView. Both of those libraries (and several others out there) take care of all or most of the complexity for you.
You should move your method in an AsyncTask. You are downloading stuff on your main thread.

Change Activity Class to Fragment

I'm pretty new new Android development. I have a class that extends Activity and I'd like to change to to a Fragment. I know as a fragment it would use onCreateView(LayoutInflater, ViewGroup, Bundle) but I'm not sure how to change my working activity to a fragment.
EDIT: I have gotten it kind of working. The problem now is that my list from the RSS feed isn't showing. I get my loading indicator and it stops once it's finished but the list doesn't show.
EDIT: Actually the list is showing, but the text is the same color as the background so I couldn't see it.
Here is my existing Activity:
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ActionAlerts extends Activity {
ListView listFeed;
ProgressBar prgLoading;
TextView txtAlert;
ActionAlertsAdapter la;
static String[] title;
static String[] pubDate;
static String[] link;
String URLFeed;
URL Feed;
DocumentBuilder db;
Document doc;
NodeList nodeList;
Bundle rssBundle = new Bundle();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actionalerts);
Bundle b = getIntent().getExtras();
URLFeed = b.getString("url");
la = new ActionAlertsAdapter(this);
listFeed = (ListView) findViewById(R.id.listFeed);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
// ColorDrawable whiteColor = new ColorDrawable(Color.WHITE);
ColorDrawable blackColor = new ColorDrawable(Color.BLACK);
listFeed.setDivider(blackColor);
listFeed.setDividerHeight(3);
new getDataTask().execute();
listFeed.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
Intent web = new Intent(ActionAlerts.this, WebBrowser.class);
rssBundle.putString("myURL", link[position]);
web.putExtras(rssBundle);
startActivity(web);
}
});
}
/** this class is used to handle thread */
public class getDataTask extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
getDataFromFeed();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
//dialog.dismiss();
prgLoading.setVisibility(8);
if(title != null){
listFeed.setVisibility(0);
listFeed.setAdapter(la);
}else{
txtAlert.setVisibility(0);
}
}
}
/*
* This code is used to get data from feed and store them
* to array attributes
*/
public void getDataFromFeed(){
try {
Feed = new URL(URLFeed);
DocumentBuilderFactory dbf= DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
doc = db.parse(new InputSource(Feed.openStream()));
doc.getDocumentElement().normalize();
nodeList = doc.getElementsByTagName("item");
title = new String[nodeList.getLength()];
pubDate = new String[nodeList.getLength()];
link = new String[nodeList.getLength()];
for(int i=0;i<nodeList.getLength();i++){
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList titleList = fstElmnt.getElementsByTagName("title");
Element titleElement = (Element) titleList.item(0);
titleList = titleElement.getChildNodes();
title[i] = ((Node) titleList.item(0)).getNodeValue();
NodeList pubDateList = fstElmnt.getElementsByTagName("pubDate");
Element pubDateElement = (Element) pubDateList.item(0);
pubDateList = pubDateElement.getChildNodes();
pubDate[i] = ((Node) pubDateList.item(0)).getNodeValue();
// chops off the " +0000" on date
pubDate[i] = pubDate[i].substring(0, pubDate[i].length()-14);
NodeList linkList = fstElmnt.getElementsByTagName("link");
Element linkElement = (Element) linkList.item(0);
linkList = linkElement.getChildNodes();
link[i] = ((Node) linkList.item(0)).getNodeValue();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
}
Here is my adapter class:
package kyfb.android.kyfb.com.kyfb;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
class ActionAlertsAdapter extends BaseAdapter {
private LayoutInflater inflater;
public ActionAlertsAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
public int getCount() {
// TODO Auto-generated method stub
return ActionAlertsFragment.title.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(convertView == null){
convertView = inflater.inflate(R.layout.item_feed, null);
holder = new ViewHolder();
holder.lytItemFeed = (RelativeLayout) convertView.findViewById(R.id.lytItemFeed);
holder.txtTitle= (TextView) convertView.findViewById(R.id.txtTitle);
holder.txtPubDate = (TextView) convertView.findViewById(R.id.txtPubDate);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
if((position%2)!=0){
// holder.lytItemFeed.setBackgroundResource(R.drawable.row_1);
holder.lytItemFeed.setBackgroundColor(Color.TRANSPARENT);
}else{
// holder.lytItemFeed.setBackgroundResource(R.drawable.row_2);
holder.lytItemFeed.setBackgroundColor(Color.TRANSPARENT);
}
holder.txtTitle.setText(ActionAlertsFragment.title[position]);
holder.txtPubDate.setText(ActionAlertsFragment.pubDate[position]);
holder.txtTitle.setTextColor(Color.BLACK);
holder.txtPubDate.setTextColor(Color.BLACK);
return convertView;
}
static class ViewHolder {
TextView txtTitle, txtPubDate;
RelativeLayout lytItemFeed;
}
}
Here is my Fragment class that I'm trying to make from the activity class above:
package kyfb.android.kyfb.com.kyfb;
import android.app.Fragment;
import android.app.ListFragment;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
public class ActionAlertsFragment extends Fragment {
ListView listFeed;
ProgressBar prgLoading;
TextView txtAlert;
ActionAlertsAdapter la;
static String[] title;
static String[] pubDate;
static String[] link;
String URLFeed;
URL Feed;
DocumentBuilder db;
Document doc;
NodeList nodeList;
Bundle rssBundle = new Bundle();
public ActionAlertsFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
// View rootView = inflater.inflate(R.layout.fragment_actionalerts, container, false);
View rootView = inflater.inflate(R.layout.fragment_actionalerts, null);
URLFeed = "http://kyfbnewsroom.com/category/notifications/feed";
Context ctx = rootView.getContext();
la = new ActionAlertsAdapter(ctx);
listFeed = (ListView) rootView.findViewById(R.id.listFeed);
prgLoading = (ProgressBar) rootView.findViewById(R.id.prgLoading);
txtAlert = (TextView) rootView.findViewById(R.id.txtAlert);
// ColorDrawable whiteColor = new ColorDrawable(Color.WHITE);
ColorDrawable blackColor = new ColorDrawable(Color.BLACK);
listFeed.setDivider(blackColor);
listFeed.setDividerHeight(3);
new getDataTask().execute();
listFeed.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
// Intent web = new Intent(ActionAlertsFragment.this, WebBrowser.class);
// rssBundle.putString("myURL", link[position]);
// web.putExtras(rssBundle);
// startActivity(web);
}
});
return rootView;
}
/** this class is used to handle thread */
public class getDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
getDataFromFeed();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
//dialog.dismiss();
prgLoading.setVisibility(8);
if(title != null){
listFeed.setVisibility(0);
listFeed.setAdapter(la);
}else{
txtAlert.setVisibility(0);
}
}
}
/*
* This code is used to get data from feed and store them
* to array attributes
*/
public void getDataFromFeed(){
try {
Feed = new URL(URLFeed);
DocumentBuilderFactory dbf= DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
doc = db.parse(new InputSource(Feed.openStream()));
doc.getDocumentElement().normalize();
nodeList = doc.getElementsByTagName("item");
title = new String[nodeList.getLength()];
pubDate = new String[nodeList.getLength()];
link = new String[nodeList.getLength()];
for(int i=0;i<nodeList.getLength();i++){
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList titleList = fstElmnt.getElementsByTagName("title");
Element titleElement = (Element) titleList.item(0);
titleList = titleElement.getChildNodes();
title[i] = ((Node) titleList.item(0)).getNodeValue();
NodeList pubDateList = fstElmnt.getElementsByTagName("pubDate");
Element pubDateElement = (Element) pubDateList.item(0);
pubDateList = pubDateElement.getChildNodes();
pubDate[i] = ((Node) pubDateList.item(0)).getNodeValue();
// chops off the " +0000" on date
pubDate[i] = pubDate[i].substring(0, pubDate[i].length()-14);
NodeList linkList = fstElmnt.getElementsByTagName("link");
Element linkElement = (Element) linkList.item(0);
linkList = linkElement.getChildNodes();
link[i] = ((Node) linkList.item(0)).getNodeValue();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
}
First change this.
View rootView = inflater.inflate(R.layout.fragment_actionalerts, null);
to
View rootView = inflater.inflate(R.layout.fragment_actionalerts, container, false);
And use Fragment Context as a getActivity().
Try this:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_submenus_list, null);
....
return view;
}
And change every findViewById(...) to view.findViewById(...)

Categories