NullPointerException when downloading images for ImageView in android - java

I am attempting to brush up on my android for a project at work, and it seams that im more out of touch than i first thought.
I am creating an app that uploads pictures to a remote server and then shows these uploads as thumbnails.
The section i am struggling is with downloading the image and applying it to the image view within a list view.
Im receiving a Null Pointer Exception which is never nice.
Im not sure if this is due to me starting a number of ASync tasks (one for each image) or if its something more obvious
Stack Trace
Process: com.example.alex.documentupload, PID: 5788
java.lang.NullPointerException
at com.example.alex.documentupload.DownloadImageTask.onPostExecute(DownloadImage.java:35)
at com.example.alex.documentupload.DownloadImageTask.onPostExecute(DownloadImage.java:14)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5748)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Android Code
Show images Class
package com.example.alex.documentupload;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.example.alex.documentupload.JSONParser;
import com.example.alex.documentupload.DownloadImageTask;
public class ShowImages extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
ImageView img;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://www.500kgiveaway.co.uk/getimagesmob.php";
//JSON Node Names
private static final String TAG_PATH = "path";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_images);
oslist = new ArrayList<HashMap<String, String>>();
new JSONParse().execute();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// clear the list before adding more
//update the list
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONArray> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
img = (ImageView)findViewById(R.id.img);
pDialog = new ProgressDialog(ShowImages.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONArray doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONArray json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONArray json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json;
for(int i = 0 ; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String path = c.getString(TAG_PATH);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_PATH, path);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(ShowImages.this, oslist,
R.layout.list_v,
new String[] { TAG_PATH }, new int[] {
R.id.vers});
list.setAdapter(adapter);
new DownloadImageTask((ImageView) list.findViewById(R.id.img))
.execute("http://www.500kgiveaway.co.uk/" + path);
// list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//
// #Override
// public void onItemClick(AdapterView<?> parent, View view,
// int position, long id) {
// Toast.makeText(ShowImages.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
// }
// });
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public void loadcamera(View view) {
// Do something in response to button
Intent myIntent = new Intent(ShowImages.this, MainActivity.class);
myIntent.putExtra("dir", "BS"); //Optional parameters
ShowImages.this.startActivity(myIntent);
}
}
DownloadImages Class
package com.example.alex.documentupload;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
import java.io.InputStream;
/**
* Created by Alex on 03/05/2015.
*/
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 mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}

This turned out to be a bit of a tricky fix, but got there in the end.
The issue was that i was unable to reference the imageview object inside the listview object whilst using a SimpleAdaptor.
The answer is that you need to create a custom class that extends SimpleAdaptor
I ended up using the picasso library, not because it helped fix the problem, more that it offered some image processing features, like resize etc which i had not previously allowed for.
I followed this answer Android - How can diplay pictures in a simpleApapter list view
However i run in to additional issues with context.
Here is my custom class that extends SimpleAdaptor
package com.example.alex.documentupload;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import com.squareup.picasso.Picasso;
import java.util.List;
import java.util.Map;
public class ExtendedAdaptor extends SimpleAdapter {
public static Context NewContext;
public ExtendedAdaptor(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to){
super(context, data, resource, from, to);
NewContext = context;
}
public View getView(int position, View convertView, ViewGroup parent){
// here you let SimpleAdapter built the view normally.
View v = super.getView(position, convertView, parent);
// Then we get reference for Picasso
ImageView img = (ImageView) v.getTag();
if(img == null){
img = (ImageView) v.findViewById(R.id.img);
v.setTag(img); // <<< THIS LINE !!!!
}
// get the url from the data you passed to the `Map`
String url = ((Map)getItem(position)).get("path").toString();
// do Picasso
// maybe you could do that by using many ways to start
Picasso.with(NewContext).load(url)
.resize(100, 100).into(img);
// return the view
return v;
}
}
and here is how i called it
ListView list = (ListView) findViewById(R.id.list);
ListAdapter adapter =
new ExtendedAdaptor(
context,
oslist,
R.layout.list_v,
new String[]{TAG_PATH},
new int[]{R.id.vers});
list.setAdapter(adapter);
Its all works pretty well, the image cache and image only download if they change.
I hope this helps someone else in the future
Thanks to all that contributed

Related

Adapter not working inside asyncTask when notifyDataSetChanged?

i've got problem when trying to implement loadmore, exactly problem is adapter.notifyDataSetChanged inside AsyncTask. i trying to implement from this tuts https://github.com/shontauro/android-pulltorefresh-and-loadmore
, this tuts try implementing using extend ListActivity in Class, but i'm using extend Fragment, anyway this code is working, but just data not updated when trying to get data from loadmore. i'm sorry if my language is bad :)
this is my class :
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.bye.swipetab.adapter.ViewPagerAdapter;
import com.viewpagerindicator.CirclePageIndicator;
import com.viewpagerindicator.UnderlinePageIndicator;
import java.util.Arrays;
import java.util.LinkedList;
public class Tour extends Fragment {
private static final String TAG = Tour.class.getSimpleName();
View myView;
private String[] values ;
private static final String brand_value = "brand_value";
// Array of strings...
String[] mobileArray = {"Android","IPhone","WindowsMobile","Blackberry","WebOS"};
// list with the data to show in the listview
private LinkedList<String> mListItems;
// The data to be displayed in the ListView
private String[] mNames = { "Fabian", "Carlos", "Alex", "Andrea", "Karla",
"Freddy", "Lazaro", "Hector", "Carolina", "Edwin", "Jhon",
"Edelmira", "Andres" };
// Declare Variables
ViewPager viewPager;
PagerAdapter vAdapter;
String[] rank;
String[] country;
String[] population;
int[] flag;
UnderlinePageIndicator mIndicator;
ListView listView;
ArrayAdapter adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myView = inflater.inflate(R.layout.tour_layout, null);
View header = inflater.inflate(R.layout.tour_header_layout, null);
//View footer = inflater.inflate(R.layout.tour_footer_layout, null);
listView = (ListView) myView.findViewById(android.R.id.list);
listView.addHeaderView(header, null, false); // header will not be clickable
mListItems = new LinkedList<String>();
mListItems.addAll(Arrays.asList(mNames));
adapter = new ArrayAdapter<String>(getActivity(), R.layout.tour_listview, R.id.MobileArray, mNames);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When clicked, show a toast with the TextView text
String brand_text = ((TextView) view.findViewById(R.id.MobileArray)).getText().toString();
//Toast.makeText(getApplicationContext(),brand_text, Toast.LENGTH_SHORT).show();
// Starting single contact activity
Intent in = new Intent(getActivity(), TourActivity.class);
in.putExtra(brand_value, brand_text);
in.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(in);
}
});
population = new String[] {
"1,354,040,000",
"1,210,193,422",
"315,761,000",
"315,123,000",
"363,752,000" };
flag = new int[] {
R.drawable.offline_ide_4,
R.drawable.offline_ide_1,
R.drawable.offline_ide_2,
R.drawable.offline_ide_3,
R.drawable.offline_ide_5 };
// Locate the ViewPager in viewpager_main.xml
viewPager = (ViewPager) myView.findViewById(R.id.pager);
// Pass results to ViewPagerAdapter Class
vAdapter = new ViewPagerAdapter(getContext(), rank, country, population, flag);
// Binds the Adapter to the ViewPager
viewPager.setAdapter(vAdapter);
CirclePageIndicator indicator = (CirclePageIndicator)myView.findViewById(R.id.indicator);
indicator.setViewPager(viewPager);
final float density = getResources().getDisplayMetrics().density;
indicator.setRadius(5 * density);
//indicator.setBackgroundColor(0x7f0c006a);
//indicator.setPageColor(R.color.black);
//indicator.setFillColor(R.color.tab_bg_yellow_deep);
//indicator.setStrokeColor(R.color.tab_bg_yellow_deep);
//indicator.setStrokeWidth(2 * density);
// set a listener to be invoked when the list reaches the end
((LoadMoreListView) listView)
.setOnLoadMoreListener(new LoadMoreListView.OnLoadMoreListener() {
public void onLoadMore() {
// Do the work to load more items at the end of list
// here
new LoadDataTask().execute();
}
});
return myView;
}
private class LoadDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
if (isCancelled()) {
return null;
}
// Simulates a background task
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
for (int i = 0; i < mobileArray.length; i++) {
mListItems.add(mobileArray[i]);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
mListItems.add("Added after load more");
// We need notify the adapter that the data have been changed
adapter.notifyDataSetChanged();
// Call onLoadMoreComplete when the LoadMore task, has finished
((LoadMoreListView) listView).onLoadMoreComplete();
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
// Notify the loading more operation has finished
((LoadMoreListView) listView).onLoadMoreComplete();
}
}
}
please tell me why this is not working ?
mListItems is not used for anything.
mNames is the one linked to the adapter, not mListItems which you are filling in the AsyncTask, may be you should review that.
mListItems.addAll(Arrays.asList(mNames));
adapter = new ArrayAdapter<String>(getActivity(), R.layout.tour_listview, R.id.MobileArray, mNames);
and then you do
for (int i = 0; i < mobileArray.length; i++) {
mListItems.add(mobileArray[i]);
}

Display image in GridView using Picasso

I want to build an app that displays images in a gridview by using the picasso library. This is my code. The image didn't load. In Picasso log, after request it always error to load. Can you help me ?Please Thank you
UPDATE
CustomGridViewAdapter.Java
import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* Created by Nicky-PC on 4/9/2016.
*/
public class CustomGridViewAdapter extends ArrayAdapter<gridItem> {
Context context;
int layoutResourceId;
ArrayList<gridItem> data = new ArrayList<gridItem>();
public CustomGridViewAdapter(Context context, int layoutResourceId,
ArrayList<gridItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
public void setGridData(ArrayList<gridItem> mGridData)
{
this.data=mGridData;
notifyDataSetChanged();
}
#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.tvItem);
holder.imageItem = (ImageView) row.findViewById(R.id.imageView);
row.setTag(holder);
} else {
holder = (RecordHolder) row.getTag();
}
gridItem item = data.get(position);
holder.txtTitle.setText(item.getBarang());
Picasso.with(context).
load(item.getImageUrl()).
into(holder.imageItem);
return row;
}
static class RecordHolder {
TextView txtTitle;
ImageView imageItem;
}
}
MainActivity.Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends ActionBarActivity {
JSONParser jParser= new JSONParser();
ArrayList<HashMap<String, String>> nameList;
JSONArray names=null;
GridView data;
private static final String URL_TEST_BARANG= "http://lomapod.azurewebsites.net/readBarang.php";
private static final String TAG_PESAN = "message";
private static final String TAG_HASIL = "result";
private static final String TAG_BARANG = "nama_barang";
private static final String TAG_IMAGE= "image_name";
ImageView imageview;
CustomGridViewAdapter mGridAdapter;
ArrayList<gridItem> mGridData;
public MainActivity()
{}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data=(GridView) findViewById(R.id.lvSeller);
nameList= new ArrayList<HashMap<String, String>>();
imageview =(ImageView) findViewById(R.id.imageView);
mGridData=new ArrayList<>();
mGridAdapter=new CustomGridViewAdapter(this,R.layout.grid_item,mGridData);
new AmbilDataJson("1").execute();
}
public class AmbilDataJson extends AsyncTask<String,String,String> {
String id;
int sukses=0;
public AmbilDataJson(String id) {
this.id=id;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id_penjual",id));
try
{
JSONObject json = jParser.makeHttpRequest(URL_TEST_BARANG, "GET", params);
gridItem item=null;
if(json != null)
{
sukses = json.getInt(TAG_PESAN);
if(sukses == 0)
{
nameList = new ArrayList<HashMap<String,String>>();
Log.d("Semua Nama: ", json.toString());
names = json.getJSONArray(TAG_HASIL);
for(int i = 0; i < names.length();i++)
{
JSONObject c = names.getJSONObject(i);
String barang = c.getString(TAG_BARANG);
String image = "lomapod.esy.es/assets/"+c.getString(TAG_IMAGE);
item = new gridItem();
item.setBarang(barang);
item.setImageUrl(image);
HashMap<String,String> map = new HashMap<String,String>();
map.put(TAG_BARANG,barang);
map.put(TAG_IMAGE,image);
nameList.add(map);
mGridData.add(item);
}
}
}
}catch(JSONException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
if(sukses == 0)
{
CustomGridViewAdapter adapter = new CustomGridViewAdapter(
MainActivity.this,R.layout.grid_item,mGridData);
if(mGridData.size()>0)
{
mGridAdapter.setGridData(mGridData);
data.setAdapter(adapter);
}
else
Toast.makeText(getApplicationContext(),"Error - No Data Available", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this,"Failed",Toast.LENGTH_LONG);
}
}
}
}
CustomGridViewAdapter adapter = new CustomGridViewAdapter(
MainActivity.this,R.layout.grid_item,mGridData);
mGridAdapter.setGridData(mGridData);
data.setAdapter(adapter);
mGridData is empty, you have not added data for this list. And you don't not need initialize new adapter.
You didn't add values to mGridData thats why its not showing anything. Before passing values to adapter check the size of mGridData.
`#Override
protected void onPostExecute(String s) {
if(sukses == 0)
{
CustomGridViewAdapter adapter = new CustomGridViewAdapter(
MainActivity.this,R.layout.grid_item,mGridData);
if(mGridData.size()>0)
{
mGridAdapter.setGridData(mGridData);
data.setAdapter(adapter);
}
else
Toast.makeText(getApplicationContext(),"Error - No Data Available", Toast.LENGTH_SHORT).show();
}`
The reason why your GridView is not showing anything is because the ArrayList<gridItem> you are passing to your CustomGridViewAdapter is empty.
You have initialized your ArrayList<gridItem> in MainActivity but never added a any item to the list.
There are some things you need to change in your program to make it work.
Since you are added server response in the ArrayList<HashMap<String, String>> nameList, you need to pass that ArrayList to your Adapter, and then use that ArrayList's items to bind in your grid's textView and imageView.
In onPostExecute(), initialize your adapter as,
CustomGridViewAdapter adapter = new CustomGridViewAdapter(MainActivity.this,R.layout.grid_item, nameList);
data.setAdapter(adapter);
//you don't even need to call mGridAdapter.setGridData(mGridData) method.
Also change your Adapter's constructor as,
public CustomGridViewAdapter(Context context, int layoutResourceId,
ArrayList<HashMap<String, String>> nameList) {
....
}

Images is not shown in my Full screen Activity from my json response..? while swiping also

How to swipe my full screen images from gridview...and that images should Loading from JSON response...?
i'm new to android...please help me friends...
But i want to use only One url in my program(JSON URL)...from that i need
Gridview--->FullScreenImage(zooming and swiping)
This is my gridView Activity...
package com.example.admin.loadingimagefromwebgridandswipe;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.widget.GridView;
import android.widget.ListView;
import com.example.admin.adapter.GridViewImageAdapter;
import com.example.admin.helper.AppConstant;
import com.example.admin.helper.JSONfunctions;
import com.example.admin.helper.Utils;
import com.example.admin.ndimageslider.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class GridViewActivity extends Activity {
private Utils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private GridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;
JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog mProgressDialog;
// ArrayList<HashMap<String, String>> imagePaths;
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String FLAG = "flag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid_view);
gridView = (GridView) findViewById(R.id.grid_view);
utils = new Utils(this);
// Initilizing Grid View
InitilizeGridLayout();
new DownloadJSON().execute();
}
private void InitilizeGridLayout() {
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
AppConstant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((utils.getScreenWidth() -
((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS);
gridView.setNumColumns(AppConstant.NUM_OF_COLUMNS);
gridView.setColumnWidth(columnWidth);
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setPadding((int) padding, (int) padding, (int) padding,
(int) padding);
gridView.setHorizontalSpacing((int) padding);
gridView.setVerticalSpacing((int) padding);
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(GridViewActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
imagePaths = new ArrayList<>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("actors");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
imagePaths.add( jsonobject.getString("name"));
imagePaths.add(jsonobject.getString("country"));
imagePaths.add( jsonobject.getString("spouse"));
imagePaths.add(jsonobject.getString("image"));
// Set the JSON Objects into the array
// imagePaths.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
gridView = (GridView) findViewById(R.id.grid_view);
// Pass the results into ListViewAdapter.java
adapter = new GridViewImageAdapter(GridViewActivity.this, imagePaths,columnWidth);
// Set the adapter to the ListView
gridView.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
this is my Gridview Adapter...
package com.example.admin.adapter;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.admin.loadingimagefromwebgridandswipe.FullScreenViewActivity;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
public class GridViewImageAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<String> filePaths = new ArrayList<String>();
private int imageWidth;
public GridViewImageAdapter(Activity activity, ArrayList<String> filePaths,
int imageWidth) {
this.activity = activity;
this.filePaths = filePaths;
this.imageWidth = imageWidth;
}
#Override
public int getCount() {
return this.filePaths.size();
}
#Override
public Object getItem(int position) {
return this.filePaths.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(activity);
} else {
imageView = (ImageView) convertView;
}
String designationUrl = filePaths.get(position);
// Log.d("designationUrl",""+designationUrl);
// URL url = null;
// try {
// url = new URL(designationUrl);
// } catch (MalformedURLException e) {
// e.printStackTrace();
// }
// Bitmap bmp = null;
// try {
// bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
// } catch (IOException e) {
// e.printStackTrace();
// }
Picasso.with(activity)
.load(designationUrl)
.resize(imageWidth, imageWidth).into(imageView);
// image view click listener
imageView.setOnClickListener(new OnImageClickListener(position));
//Toast.makeText(GridViewImageAdapter.this,"url: "+designationUrl,Toast.LENGTH_LONG).show();
return imageView;
}
class OnImageClickListener implements OnClickListener {
int _postion;
// constructor
public OnImageClickListener(int position) {
this._postion = position;
}
#Override
public void onClick(View v) {
// on selecting grid view image
// launch full screen activity
// Toast.makeText(GridViewImageAdapter.this,"url: "+,Toast.LENGTH_LONG).show();
Intent i = new Intent(activity, FullScreenViewActivity.class);
i.putExtra("position", _postion);
activity.startActivity(i);
}
}
/*
* Resizing image size
*/
public static Bitmap decodeFile(String filePath, int WIDTH, int HIGHT) {
try {
File f = new File(filePath);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_WIDTH = WIDTH;
final int REQUIRED_HIGHT = HIGHT;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
&& o.outHeight / scale / 2 >= REQUIRED_HIGHT)
scale *= 2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
Fullscreen imageViewActivity....
package com.example.admin.loadingimagefromwebgridandswipe;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.widget.ImageView;
import com.example.admin.Application;
import com.example.admin.adapter.FullScreenImageAdapter;
import com.example.admin.helper.JSONfunctions;
import com.example.admin.helper.Utils;
import com.example.admin.ndimageslider.R;
public class FullScreenViewActivity extends Activity{
private Utils utils;
private FullScreenImageAdapter adapter;
private ViewPager viewPager;
private ImageView flag;
private ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_view);
viewPager = (ViewPager) findViewById(R.id.pager);
utils = new Utils(getApplicationContext());
//flag=(ImageView)findViewById(R.id.flag);
image=(ImageView)findViewById(R.id.image);
Intent i = getIntent();
int position = i.getIntExtra("position", 0);
adapter = new FullScreenImageAdapter(FullScreenViewActivity.this,
Application.url());
viewPager.setAdapter(adapter);
// displaying selected image first
viewPager.setCurrentItem(position);
}
}
FullScreenImageAdapter:
package com.example.admin.adapter;
import android.app.Activity;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import com.example.admin.helper.TouchImageView;
import com.example.admin.ndimageslider.R;
import com.squareup.picasso.Picasso;
import org.json.JSONObject;
import java.util.ArrayList;
public class FullScreenImageAdapter extends PagerAdapter {
private Activity activity;
private ArrayList<String> imagePaths;
private LayoutInflater inflater;
// constructor
public FullScreenImageAdapter(Activity activity,
ArrayList<String> imagePaths) {
this.activity = activity;
this.imagePaths = imagePaths;
}
#Override
public int getCount() {
return this.imagePaths.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
TouchImageView imgDisplay;
Button btnClose;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.layout_fullscreen_image, container,
false);
imgDisplay = (TouchImageView) viewLayout.findViewById(R.id.imgDisplay);
btnClose = (Button) viewLayout.findViewById(R.id.btnClose);
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inPreferredConfig = Bitmap.Config.ARGB_8888;
// Bitmap bitmap = BitmapFactory.decodeFile(_imagePaths.get(position), options);
// imgDisplay.setImageBitmap(bitmap);
Picasso.with(activity)
.load(imagePaths.get(position)).into(imgDisplay);
// close button click event
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activity.finish();
}
});
((ViewPager) container).addView(viewLayout,0);
return viewLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((RelativeLayout) object);
}
}
Application:
package com.example.admin;
import android.widget.Toast;
import com.example.admin.helper.FileCache;
import java.util.ArrayList;
public class Application extends android.app.Application {
public static ArrayList<String> url(){
ArrayList<String> filePaths = new ArrayList<String>();
filePaths.add("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
return filePaths;
}
}
JSONfunctions:
package com.example.admin.helper;
/**
* Created by Admin on 14-03-2016.
*/
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
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 + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
you'll have to implement Viewpage in your application. Take a look at this tutorial for the application you are trying to make.
http://www.androidhive.info/2013/09/android-fullscreen-image-slider-with-swipe-and-pinch-zoom-gestures/
Follow this link. Cheers.

Issues with Searching ListView (Android)

I have been having trouble trying to get my Searchbox working to search the Listview for appropriate rows, and then displaying as required.
Basically, when I type in the searchbox, either the app crashed or gives me 'null object reference' errors from various files (ListView.java, TextView.java etc..)
I suspect it has a lot to do with inexperience on comparing strings between the EditText and the array created from JSON values. Displaying the listview is fine, searching it has been a frustrating hurdle. Would appreciate any help possible, thanks!
My code sections are as below,
ListViewActivity.java
package com.example.myapplication;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.util.Log;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.example.myapplication.WaterWellRigsJsonUrl;
import com.example.myapplication.Rig;
public class ListViewActivity extends Activity {
private ListView listview;
private ArrayList<Rig> Rigs;
private ArrayList<Rig> RigsTemp;
private ArrayAdapter<Rig> adapter;
private ArrayAdapter<Rig> adapter2;
private EditText et;
String searchString = "";
private final static String TAG = ListViewActivity.class.getSimpleName();
private final static String url = "http://www.world-rigs.com/waterwellrigs/json.php";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
listview = (ListView) findViewById(R.id.listview);
setListViewAdapter();
getDataFromInternet();
final EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
//adapter.getFilter().filter(s);
String searchString = s.toString();
if (s.length() > 0) {
for (int i = 0; i < Rigs.size();i++) {
if (searchString.equalsIgnoreCase(Rigs.get(i).getName())) {
Rig rigtemp = new Rig();
rigtemp.setName(Rigs.get(i).getName());
rigtemp.setImageUrl(Rigs.get(i).getImageUrl());
rigtemp.setRigId(Rigs.get(i).getRigId());
RigsTemp.add(rigtemp);
Log.e("myTag2", "value:" + RigsTemp.size());
}
}
}
adapter2 = new CustomListViewAdapter(ListViewActivity.this, R.layout.item_listview, RigsTemp);
listview.setAdapter(adapter2);
}
});
}
private void getDataFromInternet() {
new WaterWellRigsJsonUrl(this, url).execute();
}
private void setListViewAdapter() {
Rigs = new ArrayList<Rig>();
adapter = new CustomListViewAdapter(this, R.layout.item_listview, Rigs);
listview.setAdapter(adapter);
listview.setTextFilterEnabled(true);
}
//parse response data after asynctask finished
public void parseJsonResponse(String result) {
Log.i(TAG, result);
try {
JSONObject json = new JSONObject(result);
JSONArray jArray = new JSONArray(json.getString("rig_array"));
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
Rig rig = new Rig();
rig.setName(jObject.getString("name"));
rig.setImageUrl(jObject.getString("image"));
rig.setRigId(jObject.getString("rigid"));
Rigs.add(rig);
Log.e("myTag", Rigs.get(i).getRigId());
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
CustomListViewAdapter.java
package com.example.myapplication;
import java.util.List;
import android.app.Activity;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.myapplication.Rig;
import com.loopj.android.image.SmartImageView;
import com.squareup.picasso.Picasso;
public class CustomListViewAdapter extends ArrayAdapter<Rig> {
private Activity activity;
public CustomListViewAdapter(Activity activity, int resource, List<Rig> rigs) {
super(activity, resource, rigs);
this.activity = activity;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.item_listview, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
Rig rig = getItem(position);
holder.name.setText(rig.getName());
holder.authorName.setText("WR" + rig.getRigId());
Picasso.with(activity).load(rig.getImageUrl()).into(holder.image);
return convertView;
}
private static class ViewHolder {
private TextView name;
private TextView authorName;
private ImageView image;
public ViewHolder(View v) {
name = (TextView) v.findViewById(R.id.title);
image = (SmartImageView) v.findViewById(R.id.thumbnail);
// SmartImageView image = (SmartImageView) v.findViewById(R.id.my_image);
authorName = (TextView) v.findViewById(R.id.author);
}
}
}
Also getting the following errors, which do get frustrating but I think it has something to do with null reference in my Adapter or RigsTemp array while searching...
01-30 13:17:45.300 16835-16835/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 16835
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
at android.widget.ListView.setAdapter(ListView.java:487)
at com.example.myapplication.ListViewActivity$1.onTextChanged(ListViewActivity.java:84)
at android.widget.TextView.sendOnTextChanged(TextView.java:7663)
at android.widget.TextView.handleTextChanged(TextView.java:7723)
at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:9440)
at android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:964)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:515)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:454)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:33)
at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:685)
at android.view.inputmethod.BaseInputConnection.setComposingText(BaseInputConnection.java:445)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:340)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:78)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
You don't need to create two adapters and initialize them again and again. Create just one adapter and use notifyDataSetChanged to change data and update ListView
private ArrayList<Rig> RigsTemp;
private ArrayAdapter<Rig> adapter;
Change your function as follows:
private void setListViewAdapter() {
Rigs = new ArrayList<Rig>();
RigsTemp = new ArrayList<Rig>();
adapter = new CustomListViewAdapter(ListViewActivity.this, R.layout.item_listview, RigsTemp);
listview.setAdapter(adapter);
listview.setTextFilterEnabled(true);
}
And Change the TextWatcher code with following code:
public void onTextChanged(CharSequence s, int start, int before, int count) {
String searchString = myFilter.getText().toString();
RigsTemp.clear();
if (s.length() > 0) {
for (int i = 0; i < Rigs.size(); i++) {
if (searchString.equalsIgnoreCase(Rigs.get(i).getName())) {
Rig rigtemp = new Rig();
rigtemp.setName(Rigs.get(i).getName());
rigtemp.setImageUrl(Rigs.get(i).getImageUrl());
rigtemp.setRigId(Rigs.get(i).getRigId());
RigsTemp.add(rigtemp);
}
}
} else {
// Only if you want to show all results when user has not entered anything in EditText
// Else remove this line to show empty ListView at start
RigsTemp.addAll(Rigs);
}
adapter.notifyDataSetChanged();
}

i use Glide for my image display in android studio but how can i implement Glide to my listview?

I need help from anyone.. please respect my question..
ok, my problem is i want to use Glide for my listview but i dont know to do..
please constract my listviewadapter so that the Glide will work give me any other possible solution to achieve my goal..
my goal is i just want to display image and text in listview or gridview with Glide and JSON, the JSON result is from my php script..
here is my code..
CategoryFragment.java
package com.example.administrator.mosbeau;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ListView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by Administrator on 9/18/2015.
*/
public class CategoryFragment extends Fragment {
public static CategoryFragment newInstance(String id,String name) {
CategoryFragment fragment = new CategoryFragment();
Bundle bundle = new Bundle();
bundle.putString("id", id);
bundle.putString("name", name);
fragment.setArguments(bundle);
return fragment;
}
public CategoryFragment () {
}
EditText tpid, tpname;
String cid;
String cname;
String myJSON;
JSONObject jsonobject;
JSONArray jsonarray;
ListView productlistview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
public static String products_id = "products_id";
public static String products_name = "products_name";
public static String products_price = "products_price";
public static String products_image = "products_image";
Boolean InternetAvailable = false;
Seocnd detectconnection;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.categorylayout, container, false);
getActivity().invalidateOptionsMenu();
tpid = (EditText) rootView.findViewById(R.id.tpid);
tpname = (EditText) rootView.findViewById(R.id.tpname);
if(getArguments() != null) {
String catid = getArguments().getString("id");
String catname = getArguments().getString("name");
tpid.setText(catid);
tpname.setText(catname);
cid = catid;
cname = catname;
}
productlistview = (ListView) rootView.findViewById(R.id.productlistview);
//new DownloadJSON().execute();
detectconnection = new Seocnd(getActivity());
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
getProduct();
} else {
NointernetFragment fragment = new NointernetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
return rootView;
}
public void getProduct(){
class DownloadJSON extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle(cname);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/products.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;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
try {
// Locate the array name in JSON
JSONObject jsonObj = new JSONObject(myJSON);
jsonarray = jsonObj.getJSONArray("products");
arraylist = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject p = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("products_id", p.getString("products_id"));
map.put("products_name", p.getString("products_name"));
map.put("products_price", p.getString("products_price"));
map.put("products_image", p.getString("products_image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
adapter = new ListViewAdapter(getActivity(), arraylist);
// Set the adapter to the ListView
productlistview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
DownloadJSON g = new DownloadJSON();
g.execute();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(2);
}
}
ListViewAdapter.java
package com.example.administrator.mosbeau;
/**
* Created by Administrator on 9/28/2015.
*/
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import com.bumptech.glide.Glide;
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView products_id;
TextView products_name;
TextView products_price;
ImageView products_image;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.product_listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in product_listview_item.xml
products_id = (TextView) itemView.findViewById(R.id.products_id);
products_name = (TextView) itemView.findViewById(R.id.products_name);
products_price = (TextView) itemView.findViewById(R.id.products_price);
// Locate the ImageView in product_listview_item.xml
products_image = (ImageView) itemView.findViewById(R.id.products_image);
// Capture position and set results to the TextViews
products_id.setText(resultp.get(CategoryFragment.products_id));
products_name.setText(resultp.get(CategoryFragment.products_name));
products_price.setText(resultp.get(CategoryFragment.products_price));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(CategoryFragment.products_image), products_image);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("products_id", resultp.get(CategoryFragment.products_id));
// Pass all data country
intent.putExtra("products_name", resultp.get(CategoryFragment.products_name));
// Pass all data population
intent.putExtra("products_price",resultp.get(CategoryFragment.products_price));
// Pass all data flag
intent.putExtra("products_image", resultp.get(CategoryFragment.products_image));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
Just use : Glide.with(context)
.load(resultp.get(CategoryFragment.products_image))
.into(products_image);
in place of
imageLoader.DisplayImage(resultp.get(CategoryFragment.products_image), products_image);
in your ListViewAdapter.java

Categories