all images not displaying from the same url - android

Not all images are displaying when running my app. I am getting from json this result
{"result":[{"id":"1","name":null,"path":"http://api.androidhive.info/json/movies/1.jpg"},{"id":"2","name":null,"path":"http://www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"32","name":null,"path":"http://www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"31","name":null,"path":"http://www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"30","name":null,"path":"http://www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"29","name":null,"path":"http://www.justedhak.comlu.com/images/uploaded_images.jpg"}]}
the first 2 url images are displaying correctly in the app however the rest of the url are not displaying
these are working
[{"id":"1","name":null,"path":"http:\api.androidhive.info\json\movies\1.jpg"},{"id":"2","name":null,"path":"http:\justedhak.comlu.com\images\uploaded_images.jpg"}
these is my code of reading the image
//showlist() is under asynctask prePostExecute
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String id = c.getString(TAG_ID);
String url = c.getString(TAG_PATH);
Listitem.add(new Listitem(id,url));
}
GridViewAdapter adapter = new GridViewAdapter(this, R.layout.grid_item_layout, Listitem);
// gridView.setAdapter(gridAdapter);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://justedhak.comlu.com/get-data.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
I guess my error is here grid view adapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder;
if (row == null) {
LayoutInflater inflater = LayoutInflater.from(mcontext);
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.imageTitle = (TextView) row.findViewById(R.id.text);
holder.imageView = (ImageView) row.findViewById(R.id.imageView);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
Listitem item = getItem(position);
System.out.println(item.getUrl());
holder.imageTitle.setText(item.getId());
Picasso.
with(mcontext).
load(item.getUrl())
.placeholder(R.drawable.ic_launcher)
.fit()
.into(holder.imageView);
return row;
}
static class ViewHolder {
TextView imageTitle;
ImageView imageView;
}
}
upload
public void upload()
{
Calendar thisCal = Calendar.getInstance();
thisCal.getTimeInMillis();
// android.util.Log.i("Time Class ", " Time value in millisecinds "+ thisCal);
// Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
// ByteArrayOutputStream stream = new ByteArrayOutputStream();
// bmp.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
Intent intent = getIntent();
String selectedImage= intent.getStringExtra("imagePath");
Uri fileUri = Uri.parse(selectedImage);
// Uri selectedImage = intent.getData();
System.out.println(fileUri);
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(fileUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 30, stream);
byte[] byteArray = stream.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
imageview.setImageBitmap(bitmap);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
System.out.println(width);
System.out.println(height);
getResizedBitmap( bitmap, 200);
try {
stream.close();
stream = null;
} catch (IOException e) {
e.printStackTrace();
}
String image_str = Base64.encodeBytes(byteArray);
final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",image_str));
nameValuePairs.add(new BasicNameValuePair("caption",caption));
nameValuePairs.add(new BasicNameValuePair("name","je"));
nameValuePairs.add(new BasicNameValuePair("categorie",categorie));
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://justedhak.comlu.com/images/upload_image.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
final String the_string_response = convertResponseToString(response);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(AddImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
}
});
}catch(final Exception e){
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(AddImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
System.out.println("Error in http connection "+e.toString());
}
}
});
t.start();
}

Getting reference for GridView sample from here, I have just customized and tested loading all your images with it.
Item.java:
public class Item {
String imageUrl;
String title;
public Item(String imageUrl, String title) {
super();
this.imageUrl = imageUrl;
this.title = title;
}
public String getImageUrl() {
return imageUrl;
}
public String getTitle() {
return title;
}
}
CustomGridViewAdapter.java:
public class CustomGridViewAdapter extends ArrayAdapter<Item> {
Context context;
int layoutResourceId;
ArrayList<Item> data = new ArrayList<>();
public CustomGridViewAdapter(Context context, int layoutResourceId,
ArrayList<Item> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RecordHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new RecordHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.item_text);
holder.imageItem = (ImageView) row.findViewById(R.id.item_image);
row.setTag(holder);
} else {
holder = (RecordHolder) row.getTag();
}
Item item = data.get(position);
holder.txtTitle.setText(item.getTitle());
Picasso.with(context).load(item.getImageUrl()).into(holder.imageItem);
return row;
}
static class RecordHolder {
TextView txtTitle;
ImageView imageItem;
}
}
And MainActivity.java:
customGridAdapter = new CustomGridViewAdapter(this, R.layout.row_grid, gridArray);
gridView.setAdapter(customGridAdapter);
String url = "http://justedhak.comlu.com/get-data.php";
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (response != null && !response.isNull("result")) {
try {
JSONArray jsonArray = response.getJSONArray("result");
if (jsonArray != null && jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (jsonObject != null && !jsonObject.isNull("path")) {
String imagePath = jsonObject.getString("path");
if (imagePath != null && !imagePath.isEmpty()) {
gridArray.add(new Item(imagePath,"BNK"));
}
}
}
customGridAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
});
queue.add(jsonObjectRequest);
Other files such as layout... I think you know already
Here is the screenshot

As per my study It's a bug that is reported to be fixed in the next release of the lib.
You can clone the repo of the lib and compile your own jar or wait.
I recommend you to take a look at Glide. Migrating from Picasso is quite trivial, it has better performance and it makes a nice smooth scrolling on lists.
Or try to remove .fit() from picasso.
Picasso.
with(mcontext).
load(item.getUrl())
.placeholder(R.drawable.ic_launcher)
.into(holder.imageView);
Hope it will help you.

You should normalize your Uri cause this seems to be to problem here.
Take a look at normalizeScheme() of the Uri class.
It fixes such problems regargng to upper/lowercase letters.
It will convert:
Http:\justedhak.comlu.com\images\uploaded_images.jpg
to
http:\justedhak.comlu.com\images\uploaded_images.jpg
If you want some more details you can take a look at this RFC 2396
Scheme names consist of a sequence of characters beginning with a
lower case letter and followed by any combination of lower case
letters[...]

Related

Populate data into listview using json parsom with restful api

I have to run json format which is shown in below
and have to parse this data into listview
and for this i tried following code
MainActivity
swipeRefreshLayout.setOnRefreshListener(this);
// swipeRefreshLayout.setRefreshing(true);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
SyncMethod("http://52.26.35.210/api/web/v1/api-beautician/country-state-city");
}
}
);
notification_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String postloadid = actorsList.get(position).gettitle();
String source_addoc=actorsList.get(position).gettitle();
Constants.vCountry=actorsList.get(position).gettitle();
Toast.makeText(getApplicationContext(),"Selecting "+ Constants.vCountry+" State ", Toast.LENGTH_LONG).show();
finish();
}
});
}
public void init()
{
norecord=(LinearLayout)findViewById(R.id.norecord);
notification_listview=(ListView)findViewById(R.id.listView_notification);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
}
#Override
public void onRefresh()
{
swipeRefreshLayout.setRefreshing(false);
SyncMethod("http://52.26.35.210/api/web/v1/api-beautician/country-state-city");
}
private static String pad(int c)
{
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
#Override
public void onResume()
{
super.onResume();
swipeRefreshLayout.setRefreshing(false);
SyncMethod("http://52.26.35.210/api/web/v1/api-beautician/country-state-city");
}
public void SyncMethod(final String GetUrl)
{
Log.i("Url.............", GetUrl);
final Thread background = new Thread(new Runnable() {
// After call for background.start this run method call
public void run() {
try {
String url = GetUrl;
String SetServerString = "";
// document all_stuff = null;
SetServerString = fetchResult(url);
threadMsg(SetServerString);
} catch (Throwable t) {
Log.e("Animation", "Thread exception " + t);
}
}
private void threadMsg(String msg) {
if (!msg.equals(null) && !msg.equals("")) {
Message msgObj = handler11.obtainMessage();
Bundle b = new Bundle();
b.putString("message", msg);
msgObj.setData(b);
handler11.sendMessage(msgObj);
}
}
// Define the Handler that receives messages from the thread and update the progress
private final Handler handler11 = new Handler() {
public void handleMessage(Message msg) {
try {
String aResponse = msg.getData().getString("message");
Log.e("Exam", "screen>>" + aResponse);
swipeRefreshLayout.setRefreshing(false);
JSONObject jobj = new JSONObject(aResponse);
Log.e("Home Get draft--", jobj.toString());
String status = jobj.getString("status");
Log.e("Myorder Homestatusdraft",status);
Log.e("--------------------", "----------------------------------");
if (status.equalsIgnoreCase("true"))
{
actorsList = new ArrayList<Doctortype_method>();
JSONArray array = new JSONArray();
array = jobj.getJSONArray("response");
if(actorsList.size()>0){
actorsList.clear();
}
for(int i=0;i<array.length();i++)
{
JSONObject jsonChildNode = array.getJSONObject(i);
actorsList.add(new Doctortype_method(jsonChildNode.optString("State id"),jsonChildNode.optString("State name")));
}
if (getApplicationContext() != null)
{
if (adapter == null)
{
adapter = new Doctortype_Adapter(getApplicationContext(),actorsList);
notification_listview.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
}
if(actorsList.size()==0)
{
norecord.setVisibility(View.VISIBLE);
}
}
else
{
swipeRefreshLayout.setRefreshing(false);
norecord.setVisibility(View.VISIBLE);
// UF.msg(message + "");
}
} catch (Exception e) {
}
}
};
});
// Start Thread
background.start();
}
public String fetchResult(String urlString) throws JSONException {
StringBuilder builder;
BufferedReader reader;
URLConnection connection = null;
URL url = null;
String line;
builder = new StringBuilder();
reader = null;
try {
url = new URL(urlString);
connection = url.openConnection();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
//Log.d("DATA", builder.toString());
} catch (Exception e) {
}
//JSONArray arr=new JSONArray(builder.toString());
return builder.toString();
}
}
For this i also add adapter as well as arraylist.
but when i run this application api is not called perfectly..
hope anyone a]can help me..
here i add adapter and arraylist
Adapter
public Doctortype_Adapter(Context context, ArrayList<Doctortype_method> objects) {
super(context, R.layout.list_doctortype, objects);
this.context = context;
this.vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
//View v = convertView;
View rowView;
ViewHolder vh;
if (convertView == null) {
rowView = vi.inflate(R.layout.list_doctortype, null);
setViewHolder(rowView);
} else {
rowView = convertView;
}
vh = (ViewHolder) rowView.getTag();
vh.title.setText(Html.fromHtml(actorList.get(position).gettitle()));
vh.subtitle.setText(Html.fromHtml(actorList.get(position).getsubtitle()));
/* String image=actorList.get(position).getid();
UrlImageViewHelper.setUrlDrawable(vh.dimage, image.toString(), R.drawable.no_img);*/
return rowView;
}
static class ViewHolder {
public TextView title, subtitle;
}
private void setViewHolder(View rowView) {
ViewHolder vh = new ViewHolder();
vh.title = (TextView) rowView.findViewById(R.id.tvProfileName);
vh.subtitle = (TextView) rowView.findViewById(R.id.tvDesc);
}
}
arraylist
public Doctortype_method( String title, String subtitle) {
super();
this.title = title;
this.subtitle = subtitle;
}
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title = title;
}
public String getsubtitle()
{
return subtitle;
}
public void setsubtitle(String subtitle) {
this.subtitle = subtitle;
}
there is no error but when i run this code api is not called and i didnt get the output i want.
Thnx in advance..
if (status.equalsIgnoreCase("true")) is wrong because you getting status:1 so it is if (status.equalsIgnoreCase("1")) try this and then change this array = jobj.getJSONArray("response"); to array = jobj.getJSONArray("data"); your JSONArray key is "data"
And replace this also
actorsList.add(new Doctortype_method(jsonChildNode.optString("State id"),jsonChildNode.optString("State name")));
with
actorsList.add(new Doctortype_method(jsonChildNode.optString("countryID"),jsonChildNode.optString("vCountry")));
hope this helps. if this doesn't help feel free to ask
EDIT:
I cant understand what you want but have a look at this
-> you need to create baseAdapter for listview and set that adapter into the listview with your arraylist
FOR FETCHING YOUR ABOVE DATA YOU NEED TO DO BELOW CODE:
String data;//your entire JSON data as String
try {
JSONObject object = new JSONObject(data);
String status = object.getString("status");
JSONArray dataArray = object.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject json1 = dataArray.getJSONObject(i);
String countryID = json1.getString("countryID");
String vCountry = json1.getString("vCountry");
}
} catch (JSONException e) {
e.printStackTrace();
}
Now if you want to show this vCountry in listview you have to add vCountry in ArrayList and then in listview.setAdapter you have to pass this ArrayList which is filled by vCountry. Hope you understand now. If you want adapter and listview code please check this link http://www.vogella.com/tutorials/AndroidListView/article.html
Finally i got the right answer.
May anyone get help from this in future.
ActivityClass.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_list_item);
lv_city = (ListView)findViewById(R.id.listView_city);
Bundle b=getIntent().getExtras();
city_stateid = b.getString("stateid");
city_statename=b.getString("stateName");
city_countryid=b.getString("country");
lv_city.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
page_cityname = cityist.get(position).getCityName();
SharedPreferences sp=getSharedPreferences("abc",MODE_WORLD_WRITEABLE);
SharedPreferences.Editor edit=sp.edit();
edit.putString("city_name", page_cityname);
edit.commit();
Toast.makeText(getApplicationContext(),"Selected city & State"+page_cityname + "-" +city_statename, Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), NextActivity.class);
/*i.putExtra("cityname", page_cityname);*/
startActivity(i);
}
});
}
#Override
public void onResume() {
super.onResume();
params12 = new ArrayList<NameValuePair>();
params12.add(new BasicNameValuePair("type", city_type));
params12.add(new BasicNameValuePair("stateID", city_stateid));
params12.add(new BasicNameValuePair("countryID", city_countryid));
new Sync().execute();
}
class Sync extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(Void... params) {
String obj;//new JSONArray();
try {
// obj=getJSONFromUrl("Your posting path", params11);
obj = getJSONFromUrl("http://52.26.35.210/api/web/v1/api-beautician/country-state-city", params12);
return obj;
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
Log.e("Result of geting data", "" + result);
try {
Log.e("Exam", "screen>>" + result);
JSONObject get_res = new JSONObject(result);
String status = get_res.getString("status");
Log.e("Exam", "screen33333>>" + status);
if (status.equalsIgnoreCase("1")) {
cityist = new ArrayList<city_method>();
JSONArray array = new JSONArray();
array = get_res.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
cityist.add(new city_method(array.getJSONObject(i).getString("cityID"),array.getJSONObject(i).getString("cityName")));
}
if (getApplicationContext() != null)
{
if (adapter == null)
{
adapter = new city_Adapter(getApplicationContext(),cityist);
lv_city.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
}
}
} catch (Exception e) {
}
}
}
public String fetchResult(String urlString) throws JSONException {
StringBuilder builder;
BufferedReader reader;
URLConnection connection = null;
URL url = null;
String line;
builder = new StringBuilder();
reader = null;
try {
url = new URL(urlString);
connection = url.openConnection();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
//Log.d("DATA", builder.toString());
} catch (Exception e) {
}
//JSONArray arr=new JSONArray(builder.toString());
return builder.toString();
}
public String getJSONFromUrl(String url, List<NameValuePair> params) {
InputStream is = null;
String json = "";
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
//sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
}
Adapterclass.java
public class city_Adapter extends ArrayAdapter<city_method> {
ArrayList<city_method> citylist;
LayoutInflater vi;
Context context;
public city_Adapter(Context context, ArrayList<city_method> items) {
super(context, R.layout.list_doctortype, items);
this.context = context;
this.vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.citylist = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
//View v = convertView;
View rowView;
city_Adapter.ViewHolder vh;
if (convertView == null) {
rowView = vi.inflate(R.layout.program_list, null);
setViewHolder(rowView);
} else {
rowView = convertView;
}
vh = (city_Adapter.ViewHolder) rowView.getTag();
vh.cityid.setText((citylist.get(position).getCityID()));
vh.cityname.setText((citylist.get(position).getCityName()));
return rowView;
}
static class ViewHolder {
private TextView cityid,cityname;
}
private void setViewHolder(View rowView) {
ViewHolder vh = new ViewHolder();
vh.cityid = (TextView) rowView.findViewById(R.id.cityid);
vh.cityname = (TextView) rowView.findViewById(R.id.cityname);
rowView.setTag(vh);
}
}
Methodclass.java
public class city_method {
private String cityID,cityName;
public String getCityID() {
return cityID;
}
public void setCityID(String cityID) {
this.cityID = cityID;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public city_method(String cityID, String cityName) {
this.cityID = cityID;
this.cityName = cityName;
}
}

images fetched via JSON takes time to load in android

i am fetching text and images via JSON, text loads quickly but images are taking some time to load. How to make it fast?? Here is my code for fetching image from JSON and loading
public class FetchHyperVChannelInfo extends AsyncTask> {
final String KEY_TITLE = "title";
final String KEY_THUMB = "url";
HyperV hyperV;
final String KEY_VIDEO_ID = "videoId";
final String KEY_DESCRIPTION = "description";
final String KEY_POSITION = "position";
public FetchHyperVChannelInfo(HyperV context)
{
hyperV = context;
}
#Override
protected List<HyperVBean> doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String channeljsonString;
List<HyperVBean> hyperBeanList = new ArrayList<>();
try {
String base_uri = "https://www.googleapis.com/youtube/v3/playlistItems?";
Uri builtUri = Uri.parse(base_uri).buildUpon()
.appendQueryParameter("part", "snippet")
.appendQueryParameter("maxResults", "50")
.appendQueryParameter("playlistId", "PLjnOm_giI__5EiPY3GS7tr59pdAlvxd46")
.appendQueryParameter("key", "AIzaSyBRdEqF_FW-LF1ru4ejnZYxt_nYwSehl3w").build();
URL url = new URL(builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuilder buffer = new StringBuilder();
if (inputStream == null)
{
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null)
{
buffer.append(line).append("\n");
}
if (buffer.length() == 0)
{
return null;
}
channeljsonString = buffer.toString();
getDataFromJson(channeljsonString, hyperBeanList);
} catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (urlConnection != null)
{
urlConnection.disconnect();
}
if (reader != null)
{
try
{
reader.close();
} catch (Exception e) {
}
}
}
return hyperBeanList;
}
public void getDataFromJson(String StringChannelJson, List<HyperVBean> channelList) throws JSONException
{
JSONObject mainObject = new JSONObject(StringChannelJson);
JSONArray jsonArray = mainObject.getJSONArray("items");
HyperVBean bean1 = new HyperVBean();
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject channelObject = jsonArray.getJSONObject(i);
HyperVBean bean = new HyperVBean();
JSONObject temp = channelObject.getJSONObject("snippet");
bean.setHyperBeanName(temp.getString(KEY_TITLE));
JSONObject thumburl = channelObject.getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("maxres");
String s = thumburl.getString(KEY_THUMB);
bean.setHyperBeanImages(thumburl.getString(KEY_THUMB));
JSONObject tempDesc = channelObject.getJSONObject("snippet");
JSONObject tempPosition = channelObject.getJSONObject("snippet");
JSONObject videoId = channelObject.getJSONObject("snippet").getJSONObject("resourceId");
bean.setHypervVideoDescArray(tempDesc.getString(KEY_DESCRIPTION));
bean.setHypervPositionArray(tempPosition.getString(KEY_POSITION));
bean.setHypervVideosArray(videoId.getString(KEY_VIDEO_ID));
channelList.add(bean);
}
}
#Override
protected void onPostExecute(List<HyperVBean> channelList) {
hyperV.onPostExecute(channelList);
}
}
Here is my code for adapter class.
public class HyperVAdapter extends ArrayAdapter {
private LayoutInflater inflater;
List<String> videoIdArray = new ArrayList<String>();
List<String> videoDescArray = new ArrayList<String>();
List<String> videoPositionArray = new ArrayList<String>();
public static class ViewHolder
{
public final TextView hyperVName;
public final ImageView hyperVImages;
public ViewHolder(View view)
{
hyperVName = (TextView) view.findViewById(R.id.nameHyperVRowLayout);
hyperVImages = (ImageView) view.findViewById(R.id.imageHyperVRowLayout);
}
}
public HyperVAdapter(Context context, int resources, List<HyperVBean> objects)
{
super(context, R.layout.row_layout_hyper, objects);
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
if (view == null)
{
LayoutInflater vi = LayoutInflater.from(getContext());
view = vi.inflate(R.layout.row_layout_hyper, null);
}
final ViewHolder viewHolder = new ViewHolder(view);
HyperVBean hyperVBean = getItem(position);
viewHolder.hyperVName.setText(hyperVBean.getHyperBeanName());
Picasso.with(getContext()).load(hyperVBean.getHyperBeanImages()).into(viewHolder.hyperVImages);
viewHolder.hyperVImages.setTag(position);
viewHolder.hyperVImages.setClickable(true);
videoIdArray.add(hyperVBean.getHypervVideosArray());
videoDescArray.add(hyperVBean.getHypervVideoDescArray());
videoPositionArray.add(hyperVBean.getHypervPositionArray());
final String[] myVideoIdArray = new String[videoIdArray.size()];
videoIdArray.toArray(myVideoIdArray);
final String[] myVideoPosition = new String[videoPositionArray.size()];
videoPositionArray.toArray(myVideoPosition);
final String[] myVideoDesc = new String[videoDescArray.size()];
videoDescArray.toArray(myVideoDesc);
viewHolder.hyperVImages.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int position = (Integer) v.getTag();
for (int i = 0; i<myVideoPosition.length; i++)
{
if (position == Integer.parseInt(myVideoPosition[i]))
{
Intent intent = new Intent(getContext(), VideoScreen.class);
intent.putExtra("description", myVideoDesc[i]);
intent.putExtra("videoId", myVideoIdArray[i]);
intent.putExtra("position", myVideoPosition[i]);
getContext().startActivity(intent);
}
}
}
});
return view;
}
}

Get URL image from MySQL and display on android listView (setImageURI)

I'm new to Android and PHP. I've successfully uploaded the image URI from Android to MySQL and now getting trouble to get the image URI back and display on the listView Activity A. Any help would be greatly appreciated. Thanks a lot.
MySQL
Sending to MySQL:
I'm sending the image uri to server, and store the image path to MySQL, images are saved in PhotoUpload folder.
#Override
protected String doInBackground(String... params) {
for (int index = 0; index < jsonArray.length(); index++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(index);
String strUri = jsonObject.getString("image");
HashMap<String, String> data = new HashMap<String, String>();
data.put(Configs.KEY_IMAGE, getStringImage(Uri.parse(strUri)));
RequestHandler rh = new RequestHandler();
String result = rh.sendPostRequest(Configs.SEND, data);
return result;
} catch (Exception e) {
}
}
return "";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
public String getStringImage(Uri imgUri) {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imgUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
} catch (Exception e) {
}
return "";
}
And now I'm trying to fetch the url from MySQL and display the image into listView, but the image cannot be retrieved out, only String can be retrieved.
Retrieved from server:
public void BuildEditStaffList(final String id) {
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://192.168.107.115/Android/CRUD/staffRetrieve.php?id=" + id);
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void showList() {
try {
JSONObject jsonObj = new JSONObject(myJSON);
details = jsonObj.getJSONArray(Configs.TAG_RESULTS);
for (int i = 0; i < details.length(); i++) {
JSONObject c = details.getJSONObject(i);
String type = c.getString(Configs.TAG_TYPE);
String description = c.getString(Configs.TAG_DESCRIPTION);
String amount = c.getString(Configs.TAG_AMOUNT);
String image = c.getString(Configs.TAG_IMAGE);
int ID = c.getInt(Configs.TAG_ID);
Staff staff = new Staff(ID, type, description, amount, image);
staffs.add(staff);
}
CVAdapter adapter = new CVAdapter(getActivity(), staffs);
listViewEdit.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
CVAdapter:
public class CVAdapter extends ArrayAdapter<Staff> {
Activity context;
List<Staff> staffs;
static class ViewHolder {
public ImageView image;
public TextView type;
public TextView amount;
public TextView description;
}
#Override
public int getCount() {
return staffs.size();
}
public CVAdapter(Activity context, List<Staff> staffs) {
super(context, R.layout.retrieve_staff, staffs);
this.context = context;
this.staffs = staffs;
}
#Override
public Staff getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
ViewHolder v = new ViewHolder();
LayoutInflater inflater = context.getLayoutInflater();
convertView = inflater.inflate(R.layout.retrieve_staff, null);
v.image = (ImageView)convertView.findViewById(R.id.image);
v.amount = (TextView)convertView.findViewById(R.id.amount);
v.type = (TextView)convertView.findViewById(R.id.type);
v.description = (TextView)convertView.findViewById(R.id.description);
convertView.setTag(v);
}
holder = (ViewHolder)convertView.getTag();
Log.v("TEST", staffs.get(position).getImage());
holder.image.setImageURI(Uri.parse(staffs.get(position).getImage()));
holder.amount.setText(staffs.get(position).getAmount());
holder.type.setText(staffs.get(position).getType());
holder.description.setText(staffs.get(position).getDescription());
return convertView;
}
}
RetrieveImageAndText.php
<?php
define('HOST','127.0.0.1:3307');
define('USER','root');
define('PASS','');
define('DB','androiddb');
$con = mysqli_connect(HOST,USER,PASS,DB) or die('unable to connect');
$tws = $_GET['id'];
$sql = "select * from staff_benefit WHERE ts_id= '". $tws."' ";
$res = mysqli_query($con,$sql);
$result=array();
while($row=mysqli_fetch_array($res)){
array_push($result,array('id'=>$row[0],'type'=>$row[1],'amount'=>$row[2],'description'=>$row[3],'image'=>$row[4],
'ts_id'=>$row[5]));
}
echo (json_encode(array("result"=>$result)));
mysqli_close($con);
?>
Output
Use a networking library like Volley, Picasso, etc to GET the image over a network call as a Bitmap response and then you can set it to the ImageView via:
holder.image.setImageBitmap(bitmapResponse)
Here is tutorial for using Volley for image requests:
Image Requests with Volley
So I solved it by using Picasso
Just change holder.image.setImageURI(Uri.parse(staffs.get(position).getImage())); to Picasso.with(getContext()).load(staffs.get(position).getImage()).into(holder.image);
Use just a simple codes to get your image
String imageUrl="http://newhabari.000webhostapp.com/db_name/table_name/your_image";
Example
imageUrl="http://newhabari.000webhostapp.com/home_db/nhldb/boeing_787_2.png
Context context=image.getContext();
Picasso.with(context)
.load(imageUrl)
.placeholder(R.drawable.gazetter2)
.error(R.drawable.hands)
.into(image);
return view;
This will give you an image from your db

How to display image from url in json ListView?

ImageView is displayed but its not display all the list items, How to correct it ?
*this is the image view code *
try {
URL thumb_u = new URL("http://yathu.net46.net/uploads/19.jpg");
Drawable thumb_d = Drawable.createFromStream(thumb_u.openStream(), "src");
image.setImageDrawable(thumb_d);
}
catch (Exception e) {
// handle it
}
Full code below
public class Solutions extends Activity {
ArrayList<Person> arrayofWebData=new ArrayList<Person>();
class Person{
public String id;
public String Diseases_type, Treatments_type, desise_name, img_url;
}
FancyAdapter aa=null;
static ArrayList<String> resultRow;
public void onCreate(Bundle savedInstanceState){
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.solutions);
final String data = getIntent().getExtras().getString("Diseases_type");
String post_id = getIntent().getExtras().getString("id");
final String gen = getIntent().getExtras().getString("gen_id");
Toast.makeText(getApplicationContext(),
"Solution.java value is : "+post_id, Toast.LENGTH_LONG).show();
String result="";
try{
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost("http://yathu.net46.net/application/database/view_treadment.php");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("desise_id",post_id));
params.add(new BasicNameValuePair("gender_id",gen));
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response=httpclient.execute(httppost);
HttpEntity entity=response.getEntity();
InputStream webs= entity.getContent();
try{
BufferedReader reader= new BufferedReader(new InputStreamReader(webs,"iso-8859-1"),8);
StringBuilder sb= new StringBuilder();
String line=null;
while((line=reader.readLine())!=null){
sb.append(line+"\n");
}
webs.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result" + e.toString());
}
}catch(Exception e){
Log.e("log_tag","Error in http connection"+e.toString());
}
try{
JSONArray jArray=new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data=jArray.getJSONObject(i);
Person resultRow=new Person();
resultRow.id=json_data.getString("image");
resultRow.Treatments_type=json_data.getString("Treatments_type");
resultRow.desise_name=data+" - jPh;T "+(i+1);
resultRow.img_url="http://yathu.net46.net/uploads/"+json_data.getString("image");
arrayofWebData.add(resultRow);
}
}
catch(JSONException e){
Log.e("log_tag","Error parsing data"+e.toString());
}
final ListView myListView =(ListView)findViewById(R.id.solutionListView);
aa=new FancyAdapter();
myListView.setAdapter(aa);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
Person p = (Person) myListView.getItemAtPosition(position);
Log.i("SomeTag", "diseases_id: " + p.Treatments_type);
Log.i("SomeTag", "Tid: " + p.id);
Intent i = new Intent(Solutions.this, Single_diseases.class);
i.putExtra("diseases_id", p.Treatments_type);
i.putExtra("Tid", p.id);
i.putExtra("gend_id", gen);
i.putExtra("des_name", data);
Solutions.this.startActivity(i);
}
});
}
catch(Exception e){
Log.e("ERROR","ERROR IN CODE"+e.toString());
e.printStackTrace();
}
}
class FancyAdapter extends ArrayAdapter<Person> {
FancyAdapter(){
super(Solutions.this,android.R.layout.simple_list_item_1,arrayofWebData);
}
public View getView(int position,View convertView, ViewGroup parent){
ViewHolder holder;
if(convertView==null){
LayoutInflater inflater=getLayoutInflater();
convertView=inflater.inflate(R.layout.sol_list, null);
holder=new ViewHolder(convertView);
convertView.setTag(holder);
}
else{
holder=(ViewHolder)convertView.getTag();
}
holder.populateFrom(arrayofWebData.get(position));
return(convertView);
}
}
class ViewHolder{
public TextView desise_name=null;
public ImageView image = null;
public TextView showresult=null;
public TextView image_urldisplay=null;
int loader;
ImageLoader imgLoader;
public Activity activity = null;
ViewHolder(View row){
this.activity = activity;
Typeface font1 = Typeface.createFromAsset(getAssets(), "fonts/Bamini.ttf");
desise_name=(TextView)row.findViewById(R.id.solutions_types);
desise_name.setTypeface(font1);
showresult=(TextView)row.findViewById(R.id.showresult);
image_urldisplay=(TextView)row.findViewById(R.id.textView1);
image = (ImageView) findViewById(R.id.image);
}
void populateFrom(Person r){
desise_name.setText(r.desise_name);
showresult.setText(r.Treatments_type);
image_urldisplay.setText(r.img_url);
try {
URL thumb_u = new URL("http://yathu.net46.net/uploads/19.jpg");
Drawable thumb_d = Drawable.createFromStream(thumb_u.openStream(), "src");
image.setImageDrawable(thumb_d);
}
catch (Exception e) {
// handle it
}
}
}
}
Please help anyone
I can recommend a different way that works like a charm: Android Query.
You can download that JAR file from here
AQuery androidAQuery = new AQuery(this);
As an example:
androidAQuery.id(YOUR IMAGEVIEW).image(YOUR IMAGE TO LOAD, true, true, getDeviceWidth(), ANY DEFAULT IMAGE YOU WANT TO SHOW);
It's very fast and accurate, and using this you can find many more features like animation when loading, getting a bitmap (if needed), etc.

Android: Custom ListView and Threading problem

I'm working on a small project on Android and have a serious problem with implementing some multi-threading into my solution. Below is a class that is an activity inside the tab of the main interface, which displays a custom list with pictures and data downloaded from YouTube API.
The class works fine, but it completely blocks the UI when, first the data, and then the images are being loaded from the Internet. I know I need to implement some threading and I have tried various things, but I'm not quite sure which parts of the code I have to launch as separate threads. There's also a chance there is something fundamentally wrong with my code structure.
Ideally I'd like to have the UI shown to the user immediately after the application is launched with a progress dialog on top of it, while the textual data is being loaded from YouTube. Then the user should get control of the UI, while images are being loaded in another thread in the background.
public class VodsActivity extends ListActivity {
private LayoutInflater mInflater;
private Vector<RowData> data;
RowData rd;
//private Handler mHandler;
private ProgressDialog dialog;
//Generic names of custom ListView elements
private static String[] title;
private Vector<String> detail;
private Vector<String> status;
private Vector<String> imgurl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_list);
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
title = getResources().getStringArray(R.array.yt_channels);
detail = new Vector<String>();
status = new Vector<String>();
imgurl = new Vector<String>();
//mHandler = new Handler();
//dialog = ProgressDialog.show(VodsActivity.this, "","Loading. Please wait...", true);
loadData();
displayData();
//dialog.dismiss();
}
private void loadData() {
String[] values = {"error", "error", "http://www.ephotobay.com/thumb/message-error.jpg" };
for (int i = 0; i < title.length; i++) {
values = getData(title[i]);
values[1] = getTodaysUploads(title[i]);
detail.add(i, values[0]);
status.add(i, values[1]);
imgurl.add(i, values[2]);
}
}
/*** This function gets total number of uploads and thumbnail url for the user from a single feed ***/
private String[] getData (String username) {
String[] result = new String[3];
String ytFeedUrl = "http://gdata.youtube.com/feeds/api/users/" + username + "?v=2";
InputStream inStream = null;
try {
inStream = OpenHttpConnection(ytFeedUrl);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(inStream);
Element docEle = dom.getDocumentElement();
inStream.close();
NodeList nl = docEle.getElementsByTagName("entry");
if (nl != null && nl.getLength() > 0) {
for (int i = 0; i < nl.getLength(); i++) {
Element entry = (Element) nl.item(i);
Element thumbnail = (Element) entry.getElementsByTagName("media:thumbnail").item(0);
String thumbUrl = thumbnail.getAttribute("url");
Element feedLink = (Element) entry.getElementsByTagName("gd:feedLink").item(5);
String uploads = feedLink.getAttribute("countHint");
result[0] = uploads + " videos";
result[1] = ""; //not used here
result[2] = thumbUrl;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
finally {
//
}
return result;
}
/*** This function gets a number of today's uploads of the user ***/
private String getTodaysUploads (String username) {
String result = null;
String ytFeedUrl = "http://gdata.youtube.com/feeds/api/videos?author=" + username + "&time=today&v=2";
InputStream inStream = null;
try {
inStream = OpenHttpConnection(ytFeedUrl);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(inStream);
Element docEle = dom.getDocumentElement();
inStream.close();
NodeList nl = docEle.getElementsByTagName("feed");
if (nl != null && nl.getLength() > 0) {
for (int i = 0; i < nl.getLength(); i++) {
Element entry = (Element) nl.item(i);
Element title = (Element)entry.getElementsByTagName("openSearch:totalResults").item(0);
result = title.getFirstChild().getNodeValue();
result += " new today";
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
finally {
//
}
return result;
}
private void displayData () {
//Use vector instead of ArrayList for safe threading
data = new Vector<RowData>();
for (int i = 0; i < title.length; i++) { //Loop needs to be changed based on results
try {
rd = new RowData(i, title[i], detail.get(i), status.get(i));
} catch (Exception e) {
e.printStackTrace();
}
data.add(rd);
}
CustomAdapter adapter = new CustomAdapter (this, R.layout.custom_list_item, R.id.title, data);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}
private InputStream OpenHttpConnection(String strUrl) throws IOException {
InputStream inStream = null;
URL url = new URL(strUrl);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inStream = httpConn.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return inStream;
}
//This is temporary
public void onListItemClick(ListView parent, View v, int position, long id) {
CustomAdapter adapter = (CustomAdapter) parent.getAdapter();
RowData row = adapter.getItem(position);
Builder builder = new AlertDialog.Builder(this);
builder.setTitle(row.mTitle);
builder.setMessage(row.mDetail + " -> " + position );
builder.setPositiveButton("ok", null);
builder.show();
}
//Private class RowData - holds details of CustomAdapter item
private class RowData {
protected int mId;
protected String mTitle;
protected String mDetail;
protected String mStatus;
RowData (int id, String title, String detail, String status) {
mId = id;
mTitle = title;
mDetail = detail;
mStatus = status;
}
#Override
public String toString() {
return mId + " " + mTitle + " " + mDetail + " " + mStatus;
}
}
//Custom Adapter for the custom list, overrides onView() method
private class CustomAdapter extends ArrayAdapter<RowData> {
public CustomAdapter(Context context, int resource, int textViewResourceId, List<RowData> objects) {
super (context, resource, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
TextView title = null;
TextView detail = null;
TextView status = null;
ImageView image = null;
RowData rowData = getItem(position);
//Reuse existing row views
if(convertView == null) {
convertView = mInflater.inflate(R.layout.custom_list_item, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
title = holder.getTitle();
title.setText (rowData.mTitle);
detail = holder.getDetail();
detail.setText(rowData.mDetail);
status = holder.getStatus();
status.setText(rowData.mStatus);
//add if statements here for colors
image = holder.getImage();
/**** This loads the pictures ****/
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
String imageUrl = imgurl.get(rowData.mId);
Bitmap bm = LoadImage(imageUrl, bmOptions);
image.setImageBitmap(bm);
return convertView;
}
//Load image from the URL
private Bitmap LoadImage(String url, BitmapFactory.Options options) {
Bitmap bitmap = null;
InputStream inStream = null;
try {
inStream = OpenHttpConnection(url);
bitmap = BitmapFactory.decodeStream(inStream, null, options);
inStream.close();
} catch (IOException ioex) {
ioex.printStackTrace();
}
return bitmap;
}
}
/*** Wrapper for row data ***/
private class ViewHolder {
private View mRow;
private TextView title = null;
private TextView detail = null;
private TextView status = null;
private ImageView image = null;
public ViewHolder (View row) {
mRow = row;
}
public TextView getTitle() {
if (title == null) {
title = (TextView) mRow.findViewById(R.id.title);
}
return title;
}
public TextView getDetail() {
if (detail == null) {
detail = (TextView) mRow.findViewById(R.id.detail);
}
return detail;
}
public TextView getStatus() {
if (status == null) {
status = (TextView) mRow.findViewById(R.id.status);
}
return status;
}
public ImageView getImage() {
if (image == null) {
image = (ImageView) mRow.findViewById(R.id.thumbnail);
}
return image;
}
}
}
Thanks a lot for any pointers.
Check out the AsyncTask. This will let you background your long-running processes while showing the UI.
Also, you can find good/official tutorial on Android threading here.
I ended up using standard java Thread to load the data from API in the background and created a separate class for loading images in separate threads as well. In case you're wondering it now looks like this, and seem to work fine.
Loading the data:
public void onCreate(...) {
//...
mHandler = new Handler();
dialog = ProgressDialog.show(VodsActivity.this, "","Loading. Please wait...", true);
getData.start();
}
private Thread getData = new Thread() {
public void run() {
try {
loadData();
mHandler.post(showData);
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
private Runnable showData = new Runnable() {
public void run() {
try {
displayData();
dialog.dismiss();
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
Loading images (in CustomAdapter):
String imageUrl = imgurl.get(rowData.mId);
final ImageView image = holder.getImage();
//Reuse downloaded images or download new in separate thread
image.setTag(imageUrl);
Drawable cachedImage = imageLoader.loadDrawable(imageUrl, new ImageCallback() {
public void imageLoaded(Drawable imageDrawable, String imageUrl) {
ImageView imageViewByTag = (ImageView) image.findViewWithTag(imageUrl);
if (imageViewByTag != null) {
imageViewByTag.setImageDrawable(imageDrawable);
}
}
});
image.setImageDrawable(cachedImage);
ImageLoader class:
public class ImageLoader {
private HashMap<String, SoftReference<Drawable>> imageCache;
private static final String TAG = "ImageLoader";
public ImageLoader() {
imageCache = new HashMap<String, SoftReference<Drawable>>();
}
//Loads image from the cache if it exists or launches new thread to download it
public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback) {
Log.d(TAG, "loadDrawable(" + imageUrl + ")");
if (imageCache.containsKey(imageUrl)) {
SoftReference<Drawable> softReference = imageCache.get(imageUrl);
Drawable drawable = softReference.get();
if (drawable != null) {
return drawable;
}
}
final Handler handler = new Handler() {
#Override
public void handleMessage(Message message) {
imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
}
};
new Thread() {
#Override
public void run() {
Drawable drawable = loadImageFromUrl(imageUrl);
imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
Message message = handler.obtainMessage(0, drawable);
handler.sendMessage(message);
}
}.start();
return null;
}
//Downloads image from the url
public static Drawable loadImageFromUrl(String url) {
Log.d(TAG, "loadImageFromUrl(" + url + ")");
InputStream inputStream;
try {
inputStream = new URL(url).openStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
return Drawable.createFromStream(inputStream, "src");
}
public interface ImageCallback {
public void imageLoaded(Drawable imageDrawable, String imageUrl);
}
}

Categories

Resources