I am new android now I want to display image from an url. I am using imageview in listview. I want to add the list of images into the each row of the list item. I used SimpleAdapter but the imageview shows blank.
Here's the main activity:
package com.example.mysqltest;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
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.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class ReadComments extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// testing on Emulator:
private static final String READ_COMMENTS_URL = "http://192.168.30.198/test/webservice/comments.php";
// JSON IDS:
private static final String TAG_SUCCESS = "success";
private static final String TAG_TITLE = "title";
private static final String TAG_POSTS = "posts";
private static final String TAG_POST_ID = "post_id";
private static final String TAG_USERNAME = "username";
private static final String TAG_MESSAGE = "message";
private static final String TAG_IMAGE = "image";
// An array of all of our comments
private JSONArray mComments = null;
// manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mCommentList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// note that use read_comments.xml instead of our single_post.xml
setContentView(R.layout.read_comments);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// loading the comments via AsyncTask
new LoadComments().execute();
}
public void addComment(View v) {
Intent i = new Intent(ReadComments.this, AddComment.class);
startActivity(i);
}
/**
* Retrieves recent post data from the server.
*/
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
try {
mComments = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
// gets the content of each tag
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_MESSAGE);
String username = c.getString(TAG_USERNAME);
String image = c.getString(TAG_IMAGE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
map.put(TAG_IMAGE, image);
// adding HashList to ArrayList
mCommentList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.single_post, new String[] { TAG_TITLE, TAG_MESSAGE,
TAG_USERNAME,TAG_IMAGE }, new int[] { R.id.title, R.id.message,
R.id.username, R.id.imageView1 });
// I shouldn't have to comment on this one:
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ReadComments.this);
pDialog.setMessage("Loading Comments...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
Okay. So I assume here that you insist on using SimpleAdapter. No probem, problem solved, just follow the steps:
First lets create our custom row.xml for our ListView which will consist of only one ImageView.(You can add whatever you like to it later on but now i'll assume that you only wanna load the ImageView)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:src="#drawable/ic_launcher" />
</RelativeLayout>
Second lets create our custom SimpleAdapter
package com.example.helpstack;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
public class MySimpleAdapter extends SimpleAdapter {
private Context mContext;
public LayoutInflater inflater = null;
public MySimpleAdapter(Context context,
List<? extends Map<String, ?>> data, int resource, String[] from,
int[] to) {
super(context, data, resource, from, to);
mContext = context;
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.row, null);
HashMap<String, Object> data = (HashMap<String, Object>) getItem(position);
new DownloadTask((ImageView) vi.findViewById(R.id.imageView1))
.execute((String) data.get("uri"));
return vi;
}
}
Third lets create our DownloadTask, this class will download the image:
package com.example.helpstack;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
public class DownloadTask extends AsyncTask<String, Void, Boolean> {
ImageView v;
String url;
Bitmap bm;
public DownloadTask(ImageView v) {
this.v = v;
}
#Override
protected Boolean doInBackground(String... params) {
url = params[0];
bm = loadBitmap(url);
return true;
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
v.setImageBitmap(bm);
}
public static Bitmap loadBitmap(String url) {
try {
URL newurl = new URL(url);
Bitmap b = BitmapFactory.decodeStream(newurl.openConnection()
.getInputStream());
return b;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Now the DownloadTask is being used from inside the getView() in SimpleAdapter
Fourth lets run our amazing small project from our MainActivity.java
package com.example.helpstack;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class MainActivity extends Activity {
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
Map<String, Object> map = new HashMap<String, Object>();
map.put("uri",
"http://upload.wikimedia.org/wikipedia/commons/thumb/f/f9/Wiktionary_small.svg/350px-Wiktionary_small.svg.png");
//here u can add as many uri as u want
data.add(map);
MySimpleAdapter adapter = new MySimpleAdapter(MainActivity.this, data,
R.layout.row, new String[] {}, new int[] {});
lv.setAdapter(adapter);
}
}
You can use any image cache library. Example, Picasa, Universal Image Loader..
You can cache the images from the URL and then you can use the images in your app.
You can find the libraries in the following links
http://square.github.io/picasso/ and https://github.com/nostra13/Android-Universal-Image-Loader
You can use multiple thread to download and decode bitmap .please follow this website and try to learn how android Developer use thread pool executer to execute different image in thread.
http://developer.android.com/training/multiple-threads/create-threadpool.html
1) To set the image Uri to the ImageView you can use a ViewBinder
You have to implement the abstract class and override setViewValue
2) You can use Picasso to load the images in a background thread and cache them.
The setViewValue method would look like this:
boolean setViewValue (View view, Object data, String textRepresentation) {
if(view.getId() == R.id.imageView1) {
Picasso.with(view.getContext()).load(textRepresentation).into((ImageView) view);
return true;
}
return false;
}
You return true if you want to take care of the binding. You return false for the default behavior.
3) Set your adapter to use the ViewBinder by calling adapter.setViewBinder(ViewBinder);
for now, my suggestion for you is:
1. download the image from url
2. save it as drawable in the storage
3. set this drawable to the image src of imageview
(I didn't see you do this part of job from your code...)
This tutorial is the best example to parse image using json parsing and show it in a listview: http://www.androidbegin.com/tutorial/android-json-parse-images-and-texts-tutorial/
Some other:
http://imagelistviewdynamic.blogspot.in/2012/12/image-parsed-from-json-using-async-into.html
http://www.java2s.com/Open-Source/Android_Free_Code/JSON/Download_Free_code_Android_JSON_Parse_Images_and_Texts_Tutorial.htm
I suggest you use Universal Image Loader, it uses asynchronous image downloading, caching and displaying, there you can find examples how to implement it. After you do it you dont have to concern about the number of images, or its size.
If you download the project you will find this example that does all the work you want:
/**
* #author Sergey Tarasevich (nostra13[at]gmail[dot]com)
*/
public class ImageListActivity extends AbsListViewBaseActivity {
DisplayImageOptions options;
String[] imageUrls;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_list);
// here you get a String array with images URL
Bundle bundle = getIntent().getExtras();
imageUrls = bundle.getStringArray(Extra.IMAGES);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.cacheInMemory(true)
.cacheOnDisc(true)
.considerExifParams(true)
.displayer(new RoundedBitmapDisplayer(20))
.build();
listView = (ListView) findViewById(android.R.id.list);
((ListView) listView).setAdapter(new ItemAdapter());
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startImagePagerActivity(position);
}
});
}
#Override
public void onBackPressed() {
AnimateFirstDisplayListener.displayedImages.clear();
super.onBackPressed();
}
// it gets the position of listView and opens that image in a new Activity
private void startImagePagerActivity(int position) {
Intent intent = new Intent(this, ImagePagerActivity.class);
intent.putExtra(Extra.IMAGES, imageUrls);
intent.putExtra(Extra.IMAGE_POSITION, position);
startActivity(intent);
}
class ItemAdapter extends BaseAdapter {
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
private class ViewHolder {
public TextView text;
public ImageView image;
}
#Override
public int getCount() {
return imageUrls.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = getLayoutInflater().inflate(R.layout.item_list_image, parent, false);
holder = new ViewHolder();
holder.text = (TextView) view.findViewById(R.id.text);
holder.image = (ImageView) view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.text.setText("Item " + (position + 1));
// here is the place where is loaded the image using Universal ImageLoader , imageUrls[position] is a list of images URL
imageLoader.displayImage(imageUrls[position], holder.image, options, animateFirstListener);
return view;
}
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
}
Related
i was tring to load image using url.a single url is working properly. but i need to add a few more images to this page.i need to add this image s to a list view.pls tell me how can i add a string array to this code.
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class FareCrd extends Activity {
String image_url="http://movito.nervov.com/img/ace-hd.png";
String[] mString ={"http://movito.nervov.com/img/ace-hd.png",
"http://movito.nervov.com/img/Movito_Logo_M.png"};
JSONArray jsonary;
ListView list;
private Activity activity;
private String[] data;
private static View inflater=null;
//private String[] mStrings={"http://movito.nervov.com/img/ace-hd.png"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fare_crd);
list=(ListView)findViewById(R.id.farelist);
new ServConn().execute();
}
private void parsedata(String data){
//System.out.println(data);
try {
JSONObject json = new JSONObject(data);
jsonary = json.getJSONArray("data");
ListView list = (ListView) findViewById(R.id.farelist);
list.setAdapter(new DriverOrderList(getApplicationContext(),
R.layout.farecrd, new JSONObject[jsonary.length()]));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class DriverOrderList extends ArrayAdapter<JSONObject> {
int listViewResource;
public DriverOrderList(Context context, int resource, JSONObject[] s) {
super(context, resource, s);
listViewResource = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(listViewResource, parent, false);
ImageLoader imgLoader = new ImageLoader(getApplicationContext());
JSONObject rowdata = new JSONObject();
int loader = R.drawable.stub;
try {
rowdata = jsonary.getJSONObject(position);
System.out.println(rowdata);
ImageLoader imgLoader1 = new ImageLoader(getApplicationContext());
ImageView img=(ImageView) row.findViewById(R.id.imgid);
imgLoader.DisplayImage(image_url, loader, img);
TextView nameTxt = (TextView) row.findViewById(R.id.truckname);
TextView idTxt = (TextView) row.findViewById(R.id.id);
TextView minrttv =(TextView) row.findViewById(R.id.minimumRate);
TextView kmrttxt =(TextView) row.findViewById(R.id.kilometerRate);
TextView mindurtv=(TextView) row.findViewById(R.id.minimumDuration);
TextView freewatintim = (TextView) row.findViewById(R.id.freeWaitingTime);
TextView minuterttxt =(TextView) row.findViewById(R.id.minuteRate);
TextView watingchrttv =(TextView)row.findViewById(R.id.waitingCharge);
double freewt=(Double) rowdata.get("freeWaitingTime");
double kmratetxt=(Double) rowdata.get("kilometerRate");
double mindurtxt=(Double) rowdata.get("minimumDuration");
double mindur= mindurtxt/60;
double minkmrttxt=(Double) rowdata.get("minimumKilometer");
double minrttxt=(Double) rowdata.get("minimumRate");
double mintrate=(Double) rowdata.get("minuteRate");
double minutrat=mintrate/60;
double watingchrtxt=(Double) rowdata.get("waitingCharge");
double waitchgunittxt=(Double) rowdata.get("waitingChargeUnit");
nameTxt.setText(rowdata.getString("truckModel"));
minrttv.setText("Rs."+minrttxt+" /-");
kmrttxt.setText("Rs."+kmratetxt+"/km after "+minkmrttxt+"km");
mindurtv.setText("first"+mindur+"hr and "+minkmrttxt+"km");
//minuterttxt.setText(minutrat+"/-");
freewatintim.setText("first "+freewt+"min free");
watingchrttv.setText("RS"+watingchrtxt+"after every "+waitchgunittxt+"min");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return row;
}
}
private class ServConn extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
System.out.println("do in backgrnd");
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://movito.nervov.com/v1/trucks/miniTruckCategories");
httpget.setHeader(HTTP.CONTENT_TYPE, "application/json");
String replyString = "";
try {
HttpResponse response = httpclient.execute(httpget);
replyString = EntityUtils.toString(response
.getEntity());
} catch (ClientProtocolException e) {
System.out.println("ex: " + e);
} catch (IOException e) {
System.out.println("e: " + e);
}
return replyString;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
System.out.println(result);
result = "{\"data\":"+result+"}";
parsedata(result);
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
}
Try to use Glide libreries instead od picasso .It might help full for you.Please look at following link which might help you out.
http://inthecheesefactory.com/blog/get-to-know-glide-recommended-by-google/en
try this code I am using Picasso library to populate ImageView,
if you are using android studio add this library using following code into your gradle file
compile 'com.squareup.picasso:picasso:2.5.2'
use following code,
It is complete example of how you can make a custom ListView, I didn't include code where you have to get he JSON data from WebService as i didn't want to make the code complicated, I will write a separate code where i will show how to read the data you are interested in.
XML
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#+id/CustomListViewActivity_listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
single_item.xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<TextView
android:id="#+id/single_item_textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:layout_weight="0.5"
android:text="New Text" />
<ImageView
android:id="#+id/single_item_imageView"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="4dp"
android:layout_weight="0.5" />
</LinearLayout>
Code
public class CustomListViewActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_list_view);
ArrayList<SingleItem> singleItems = new ArrayList<>();
singleItems.add(new SingleItem("http://movito.nervov.com/img/ace-hd.png","first Text"));
singleItems.add(new SingleItem("http://movito.nervov.com/img/Movito_Logo_M.png","Second Text"));
singleItems.add(new SingleItem("http://movito.nervov.com/img/ace-hd.png","third Text"));
singleItems.add(new SingleItem("http://movito.nervov.com/img/Movito_Logo_M.png","fourth Text"));
ListView listView = (ListView)findViewById(R.id.CustomListViewActivity_listView);
MyAdapter adapter = new MyAdapter(getApplicationContext(), R.layout.single_item,singleItems);
listView.setAdapter(adapter);
}
private class MyAdapter extends ArrayAdapter {
private ArrayList<SingleItem> singleItems;
private LayoutInflater layoutInflater;
private Context context;
private View single_View;
public MyAdapter(Context context, int resource, ArrayList<SingleItem> singleItems) {
super(context, resource, singleItems);
this.context = context;
this.singleItems = singleItems;
layoutInflater = LayoutInflater.from(this.context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
row = layoutInflater.inflate(R.layout.single_item, parent, false);
holder = new ViewHolder();
holder.textView = (TextView) row.findViewById(R.id.single_item_textView);
holder.imageView = (ImageView) row.findViewById(R.id.single_item_imageView);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final SingleItem singleItem = singleItems.get(position);
holder.textView.setText("" + singleItem.getText());
Picasso.with(context).load(""+singleItem.getUrl()).into(holder.imageView);
return row;
}
private class ViewHolder {
// Instance Variable (state or data)
TextView textView;
ImageView imageView;
}
}
public class SingleItem {
private String url;
private String text;
public SingleItem() {
}
public SingleItem(String url, String text) {
this.url = url;
this.text = text;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
}
Output
As you will see the loading the images from the URL provided to the appropriate ImageView is taken care by Picasso, do make sure you add the permission for the internet in the AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
I am creating an application in which I am parsing data using Json parsing. I've implemented listview and in my response i have totalpage and current page objects,
A new user will get items from the first page. While the user is scrolling through the listview, the list expands with items from the next page (and the next and the next etc.)
this is my response
http://pastie.org/10259792
The following is code I've tried:
HomeFragment
public class HomeFragment extends Fragment {
// Listview Adapter
ListViewAdapter adapters;
// Connection detector
ConnectionDetector cd;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONparserr jsonParser = new JSONparserr();
ArrayList<HashMap<String, String>> WebsiteList;
// albums JSONArray
JSONArray data = null;
String link_url;
ArrayList<HashMap<String, String>> arrayTemplist;
private AutoCompleteTextView inputSearch;
private ListView lv;
private static final String URL_ALBUMS = "";
private static final String WEBSITE_MENU_ID ="Brand_name";
private static final String TAG_MATCH="data";
//private static final String TAG_NAME="Brand_name";
private static final String TAG_PROFILE="id";
private static final String TAG_CAST="Company";
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
lv = (ListView)rootView.findViewById(R.id.listpehlu);
cd = new ConnectionDetector(getActivity());
WebsiteList = new ArrayList<HashMap<String, String>>();
// Loading Albums JSON in Background Thread
new LoadAlbums().execute();
// get listview
inputSearch = (AutoCompleteTextView)rootView.findViewById(R.id.autoCompleteTextViewhomefrag);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
arrayTemplist= new ArrayList<HashMap<String,String>>();
String searchString =inputSearch.getText().toString().toLowerCase();
for (int i = 0; i < WebsiteList.size(); i++)
{
String currentString =WebsiteList.get(i).get(HomeFragment.this.WEBSITE_MENU_ID);
if (currentString.toLowerCase().startsWith(searchString ))
{
arrayTemplist.add(WebsiteList.get(i));
}
}
for (int i = 0; i < arrayTemplist.size(); i++)
{
String currentstrin = arrayTemplist.get(i).get(HomeFragment.this.WEBSITE_MENU_ID);
//Toast.makeText(getApplicationContext(), currentstrin, Toast.LENGTH_LONG).show();
}
SimpleAdapter adapters = new SimpleAdapter(getActivity(), arrayTemplist,R.layout.list_item_match, new String[] {WEBSITE_MENU_ID,TAG_CAST
}, new int[] {
R.id.txtbrndnm,R.id.txtbrndcomp});
lv.setAdapter(adapters);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
Selected_Product_Listing tf = new Selected_Product_Listing();
Bundle bundle = new Bundle();
bundle.putString("prducts_name", WebsiteList.get(position).get((WEBSITE_MENU_ID)));
// bundle.putString("prducts_name", aList.get(position).get(INTEREST_ACCEPT_NAME));
tf.setArguments(bundle);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_container, tf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
// Toast.makeText(getActivity(),"lets"+ WebsiteList.get(position).get(convertToBase64(convertToBase64(WEBSITE_MENU_ID))), Toast.LENGTH_LONG).show();
}
});
lv.setOnScrollListener(new OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
{
}
}
});
return rootView;
}
public String convertToBase64(String text) {
byte[] data = null;
try {
data = text.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return Base64.encodeToString(data, Base64.DEFAULT);
}
class LoadAlbums extends AsyncTask<String, String, String> {
private JSONObject jsonObj;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(true);
pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Albums JSON: ", "> " + json);
if (json != null) {
try {
jsonObj = new JSONObject(json);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_MATCH);
String totpage=jsonObj.getString("total_page");
System.out.println("Total Page"+totpage);
String curpage=jsonObj.getString("current_page");
System.out.println("Total Page"+curpage);
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put(WEBSITE_MENU_ID,c.getString(WEBSITE_MENU_ID));
map.put(TAG_PROFILE, c.getString(TAG_PROFILE));
map.put(TAG_CAST, c.getString(TAG_CAST));
WebsiteList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all albums
pDialog.dismiss();
// updating UI from Background Thread
ListAdapter adapter = new SimpleAdapter(
getActivity(), WebsiteList,
R.layout.list_item_match, new String[] {WEBSITE_MENU_ID,TAG_CAST
}, new int[] {
R.id.txtbrndnm,R.id.txtbrndcomp});
lv.setAdapter(adapter);
}
}
EndlessAdapter
public class EndLessAdapter extends ArrayAdapter<String> {
private Context context;
private List<String> items;
private int layoutId;
public EndLessAdapter(Context context, List<String> items, int LayoutId) {
super(context,LayoutId,items);
this.context = context;
this.items = items;
this.layoutId = LayoutId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null)
convertView = ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(layoutId,parent,false);
TextView tView = (TextView)convertView.findViewById(R.id.txt);
tView.setText(items.get(position));
return convertView;
}
}
EndlessLisView
public class EndlessListView extends ListView implements OnScrollListener {
private Context context;
private View footer;
private boolean isLoading;
private EndLessListener listener;
private BaseAdapter adapter;
public EndlessListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setOnScrollListener(this);
this.context = context;
}
public EndlessListView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setOnScrollListener(this);
this.context = context;
}
public EndlessListView(Context context) {
super(context);
this.setOnScrollListener(this);
this.context = context;
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
// 4
public void addNewData() {
this.removeFooterView(footer);
// adapter.addAll(products);
adapter.notifyDataSetChanged();
isLoading = false;
}
public void setLoading()
{
isLoading = false;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
if(getAdapter() == null)
return;
if(getAdapter().getCount() == 0)
return;
int l = visibleItemCount + firstVisibleItem;
System.out.println("List View Total Item Count = "+totalItemCount+" , l = "+l+", is_loading = "+isLoading);
if(l >= totalItemCount && !isLoading){
// add footer layout
this.addFooterView(footer);
// set progress boolean
isLoading = true;
System.out.println("$$$$$$$$$ call loaddata $$$$$$$$$$$");
// call interface method to load new data
listener.loadData();
}
}
// Calling order from MainActivity
// 1
public void setLoadingView(int resId) {
footer = ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(resId, null); // footer = (View)inflater.inflate(resId, null);
this.addFooterView(footer);
System.out.println("addfooter ====######");
}
// 2
public void setListener(EndLessListener listener) {
this.listener = listener;
}
// 3
public void setAdapter(BaseAdapter adapter) {
super.setAdapter(adapter);
this.adapter = adapter;
this.removeFooterView(footer);
}
public void removeFooter(){
this.removeFooterView(footer);
}
}
You can achieve this by using the following library in Github
https://github.com/nicolasjafelle/PagingListView
Simple create your PagingAdapter and add it to com.paging.listview.PagingListView.
You have to implements the new Pagingable interface and its onLoadMoreItems() method. For example:
listView.setHasMoreItems(true);
listView.setPagingableListener(new PagingListView.Pagingable() {
#Override
public void onLoadMoreItems() {
if (pager < 3) {
new CountryAsyncTask(false).execute();
} else {
listView.onFinishLoading(false, null);
}
}
});
Finally you can use the onFinishLoading(boolean hasMoreItems, List newItems) method to update the list.
listView.onFinishLoading(true, newItems);
Also remember to use this package in your layout files:
<com.paging.listview.PagingListView
android:id="#+id/paging_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Hello here you can find the nostra library for lazy loading and then you can
implement the following example for lazzy loading
https://github.com/nostra13/Android-Universal-Image-Loader
you can achieve Lazy loading by using the below
code
Lets start the coding about the lazy loading.
MainActivity.java
package com.sunil.lazyloading;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
private Button btnlist=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnlist= (Button)findViewById(R.id.button_listview);
btnlist.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Intent intent = new Intent(this, ImageListActivity.class);
intent.putExtra("stringarrayimage", Constants.IMAGES);
startActivity(intent);
}
}
CustomAdapter.java
package com.sunil.adapter;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.sunil.lazyloading.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends BaseAdapter{
private String imageurl[]=null;
private Context context=null;
DisplayImageOptions doption=null;
private ImageLoadingListener animateFirstListener =null;
public CustomAdapter(Activity activity, String[] imageurl)
{
this.context=activity;
this.imageurl=imageurl;
doption=new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.ic_empty).showImageOnFail(R.drawable.ic_error).showStubImage(R.drawable.ic_stub).cacheInMemory(true).cacheOnDisc(true).displayer(new RoundedBitmapDisplayer(20)).build();
animateFirstListener = new AnimateFirstDisplayListener();
}
#Override
public int getCount() {
return imageurl.length;
}
#Override
public Object getItem(int arg0) {
return arg0;
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_list_row, parent, false);
holder = new ViewHolder();
holder.text = (TextView) view.findViewById(R.id.text);
holder.image = (ImageView) view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.text.setText("Item " + (position + 1));
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(imageurl[position], holder.image, doption, animateFirstListener);
return view;
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<string> displayedImages = Collections.synchronizedList(new LinkedList<string>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
private class ViewHolder {
public TextView text;
public ImageView image;
}
}
</string></string>
ImageListActivity.java
package com.sunil.lazyloading;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
MainActivity.java
package com.sunil.lazyloading;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
private Button btnlist=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnlist= (Button)findViewById(R.id.button_listview);
btnlist.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Intent intent = new Intent(this, ImageListActivity.class);
intent.putExtra("stringarrayimage", Constants.IMAGES);
startActivity(intent);
}
}
CustomAdapter.java
package com.sunil.adapter;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.sunil.lazyloading.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends BaseAdapter{
private String imageurl[]=null;
private Context context=null;
DisplayImageOptions doption=null;
private ImageLoadingListener animateFirstListener =null;
public CustomAdapter(Activity activity, String[] imageurl)
{
this.context=activity;
this.imageurl=imageurl;
doption=new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.ic_empty).showImageOnFail(R.drawable.ic_error).showStubImage(R.drawable.ic_stub).cacheInMemory(true).cacheOnDisc(true).displayer(new RoundedBitmapDisplayer(20)).build();
animateFirstListener = new AnimateFirstDisplayListener();
}
#Override
public int getCount() {
return imageurl.length;
}
#Override
public Object getItem(int arg0) {
return arg0;
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_list_row, parent, false);
holder = new ViewHolder();
holder.text = (TextView) view.findViewById(R.id.text);
holder.image = (ImageView) view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.text.setText("Item " + (position + 1));
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(imageurl[position], holder.image, doption, animateFirstListener);
return view;
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<string> displayedImages = Collections.synchronizedList(new LinkedList<string>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
private class ViewHolder {
public TextView text;
public ImageView image;
}
}
</string></string>
ImageListActivity.java
package com.sunil.lazyloading;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.sunil.adapter.CustomAdapter;
public class ImageListActivity extends Activity implements OnItemClickListener{
private ListView listview=null;
private String[] imageUrls;
protected ImageLoader imageLoader=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imagelist);
listview=(ListView)findViewById(R.id.listView_image);
imageLoader = ImageLoader.getInstance();
Bundle bundle = getIntent().getExtras();
imageUrls = bundle.getStringArray("stringarrayimage");
CustomAdapter adapter=new CustomAdapter(ImageListActivity.this, imageUrls);
listview.setAdapter(adapter);
listview.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView arg0, View arg1, int position, long arg3) {
Intent intent = new Intent(this, ImagePagerActivity.class);
intent.putExtra("imageurlpostion", imageUrls);
intent.putExtra("imagepostion", position);
startActivity(intent);
}
#Override
public void onBackPressed() {
AnimateFirstDisplayListener.displayedImages.clear();
super.onBackPressed();
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<string> displayedImages = Collections.synchronizedList(new LinkedList<string>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_clear_memory_cache:
imageLoader.clearMemoryCache();
return true;
case R.id.item_clear_disc_cache:
imageLoader.clearDiscCache();
return true;
default:
return false;
}
}
}
activity_main.xml
<button android:id="#+id/button_listview" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="ListView ImageLoad">
imagelist.xml
<listview android:id="#+id/listView_image" android:layout_height="match_parent" android:layout_width="match_parent">
</listview>
item_list_row.xml
<imageview android:adjustviewbounds="true" android:contentdescription="#string/descr_image" android:id="#+id/image" android:layout_height="72dip" android:layout_margin="3dip" android:layout_width="72dip" android:scaletype="centerCrop">
<textview android:id="#+id/text" android:layout_gravity="left|center_vertical" android:layout_height="wrap_content" android:layout_marginleft="20dip" android:layout_width="fill_parent" android:textsize="22sp">
For the Example above you need to download the library universal image loader you can download the library ... happy coding :)
you didn't use EndlessListView in your Fragment. As I looked your response, it includes pagination. So, you need to request with page number to use endless scroll.
This is just flow for Endless Listview. If your code still doesn't work, I hope you can learn sample projects after read this messages. I added only parts you need. Thanks
Endless scroll only shows limited data on listview. When user scroll down to bottom, it will get next limited data from server. So you need to add current_page paramater in your request. I don't know exactly your api.
First, you need variable for current_page which initialize with 0
You have to know when to stop. You response has total_page field for that. Save and add validation
Then you need to know when to request next page. For that,you already have codes in onScroll within EndlessListView. That code calculate and tell when user scroll down to bottom and it called
listener.loadData();
to request new data. But you still need to add listener for that. You already have
public void setListener(EndLessListener listener) {
this.listener = listener;
}
You need to create Interface with the name EndlessListener and implements in your fragment. EndlessListener Interface will include loadData() function that request to server. After that you need to add listener for the listview.
endlessListView.setListener(this);
Try Loading data when listview reaches it's end. Implement OnScrollListener in your fragment. Refer this link Android - ListView to load more items when reached end
You MUST use Paging 3 library to resolve all problems in simplest way.
ListView XMl:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/orderlistview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
/>
</LinearLayout>
OrderList class
public class OrderList {
int _orderId;
int _orderincrement_id;
String _orderstatus;
String _orderdate;
String _ordership_to;
String _ordertotal;
String _ordercurrency_symbol;
// Empty constructor
public OrderList() {
}
// constructor
public OrderList(int _orderId, int _orderincrement_id, String _orderstatus,
String _orderdate, String _ordership_to, String _ordertotal,
String _ordercurrency_symbol) {
this._orderId = _orderId;
this._orderincrement_id = _orderincrement_id;
this._orderstatus = _orderstatus;
this._orderdate = _orderdate;
this._ordership_to = _ordership_to;
this._ordertotal = _ordertotal;
this._ordercurrency_symbol = _ordercurrency_symbol;
}
public int get_orderId() {
return _orderId;
}
public void set_orderId(int _orderId) {
this._orderId = _orderId;
}
public int get_orderincrement_id() {
return _orderincrement_id;
}
public void set_orderincrement_id(int _orderincrement_id) {
this._orderincrement_id = _orderincrement_id;
}
public String get_orderstatus() {
return _orderstatus;
}
public void set_orderstatus(String _orderstatus) {
this._orderstatus = _orderstatus;
}
public String get_orderdate() {
return _orderdate;
}
public void set_orderdate(String _orderdate) {
this._orderdate = _orderdate;
}
public String get_ordership_to() {
return _ordership_to;
}
public void set_ordership_to(String _ordership_to) {
this._ordership_to = _ordership_to;
}
public String get_ordertotal() {
return _ordertotal;
}
public void set_ordertotal(String _ordertotal) {
this._ordertotal = _ordertotal;
}
public String get_ordercurrency_symbol() {
return _ordercurrency_symbol;
}
public void set_ordercurrency_symbol(String _ordercurrency_symbol) {
this._ordercurrency_symbol = _ordercurrency_symbol;
}
}
Activity
public class OrderListFragment extends Fragment {
View rootView;
ListView lv;
List<OrderList> list ;
MyListAdapter adt;
DatabaseHandler db ;
ProgressDialog progress;
SharedPreferences pref;
public OrderListFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragmentorderlist, container,
false);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
lv = (ListView) rootView.findViewById(R.id.orderlistview);
db = new DatabaseHandler(getActivity());
list = db.getAllOrderList();
if(list.size() == 0){
progress = new ProgressDialog(getActivity());
progress.setMessage("Fetching Data.....");
progress.setIndeterminate(true);
progress.setCancelable(false);
progress.show();
pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
String customer_id = pref.getString("customer_id", null);
Log.v("log_tag", "customer_id"+customer_id);
if(customer_id != null){
Log.v("log_tag", "customer_id 2332 ::: "+customer_id);
new FetchOrderListData().execute(customer_id);
}
}
adt = new MyListAdapter(getActivity());
lv.setAdapter(adt);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Bundle bundle = new Bundle();
bundle.putString("orderlist_increment_id", list.get(position).get_orderincrement_id()+"");
Fragment fragment = new OrderdetailFragment();
fragment.setArguments(bundle);
FragmentManager fragmentManager = OrderListFragment.this
.getActivity().getSupportFragmentManager();
FragmentTransaction mFragmentTransaction = fragmentManager
.beginTransaction();
mFragmentTransaction.addToBackStack(null);
mFragmentTransaction.replace(R.id.Frame_Layout, fragment)
.commit();
}
});
return rootView;
}
public class MyListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public MyListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
convertView = mInflater.inflate(R.layout.custom_orderlistdata,
null);
TextView ordernumbertxt = (TextView) convertView
.findViewById(R.id.ordernumberTxt);
TextView orderdate = (TextView) convertView
.findViewById(R.id.orderdateTxt);
TextView orderamount = (TextView) convertView
.findViewById(R.id.orderAmountTxt);
TextView orderSatusTxt = (TextView) convertView
.findViewById(R.id.orderSatusTxt);
ordernumbertxt.setText(Html.fromHtml("<b>Order Number : </b>"+list.get(position).get_orderincrement_id()+""));
orderdate.setText(list.get(position).get_orderdate());
orderSatusTxt.setText(list.get(position).get_orderstatus());
String parts = list.get(position).get_ordertotal();
double d = Double.parseDouble(parts);
double dval = roundTwoDecimals(d);
orderamount.setText(Html.fromHtml("<b>Total : </b>"+list.get(position).get_ordercurrency_symbol()+" "+dval));
return convertView;
}
public double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Double.valueOf(twoDForm.format(d));
}
}
private class FetchOrderListData extends AsyncTask<String, Void, JSONObject> {
#Override
protected void onPreExecute() {
}
#Override
protected JSONObject doInBackground(String... args) {
JSONObject listSize = null;
Integer cust_id = Integer.parseInt(args[0]);
try {
listSize = DBAda.getAllOrderListData(cust_id);
////*** call your HTTP Service over here ***////
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listSize;
}
protected void onPostExecute(JSONObject jsonObj) {
db = new DatabaseHandler(getActivity());
if (progress != null) {
progress.hide();
}
if (jsonObj == null) {
return;
}
JSONArray json;
try {
json = jsonObj.getJSONArray("records");
for (int i = 0; i < json.length(); i++) {
JSONObject jobj;
try {
jobj = json.getJSONObject(i);
int order_id = Integer.parseInt(jobj.getString("order_id").toString());
int order_IncrementId = Integer.parseInt(jobj.getString("increment_id").toString());
String orderStatus = jobj.getString("status");
String orderdate = jobj.getString("date");
String ordershipto = jobj.getString("ship_to");
String ordertotal = jobj.getString("order_total");
String ordersymbol = jobj.getString("currency_symbol");
//db.addWishlistItem(new WishList(entity_id,quentity,comment,name,short_description,thumbnails,itemId));
db.addOrderListItem(new OrderList(order_id, order_IncrementId, orderStatus, orderdate, ordershipto, ordertotal, ordersymbol));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
lv = (ListView) rootView.findViewById(R.id.orderlistview);
db = new DatabaseHandler(getActivity());
list = db.getAllOrderList();
adt = new MyListAdapter(getActivity());
lv.setAdapter(adt);
}
}
}
I need help implementing my app. There are different activities. On one activity, a list view is shown, then if the user clicks on a row, another list view activity is shown.
The list view activities may need a variable that is used as param to a URL to retrieve JSON data to feed the list view. I will try to explain it better.
Activity 1: ListView with objects retrieve from JSON (no need for URL param). User clicks on row and opens Activity 2 ( a variable is passed from activity 1 to activity 2).
Activity 2: ListView with objects retrieve from JSON, URL includes param (variable passed from A1 to A2). List view objects are shown.
Now the user clicks on back button (hardware button). Activity 1 list view objects shown.
If the user clicks again on the same row at A1 as before, then A2 doesn't show anything.
If you need me to show my code, no problem...but I need more an explanation to the behaviour rather than code examples. Thank you
EDIT HERE:
ACTIVITY 1 LISTVIEW ADAPTER
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
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.RelativeLayout;
import android.widget.TextView;
public class DondeEsta_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 DondeEsta_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 id_categoria_donde_esta_textView;
TextView nombre_categoria_donde_esta_textView;
ImageView imagen_categoria_donde_esta;
TextView tipo_menu;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.dondeesta_listview_item, parent, false);
// Get the position
resultp = data.get(position);
RelativeLayout myLayout = (RelativeLayout) itemView.findViewById(R.id.milayout);
if (position % 2 == 1) {
myLayout.setBackgroundResource(R.color.fondo);
//lugar_evento.setBackgroundResource(R.color.fondo);
} else {
myLayout.setBackgroundResource(R.color.blanco);
//titulo_evento.setBackgroundResource(R.color.blanco);
//lugar_evento.setBackgroundResource(R.color.blanco);
}
String tipo_de_menu = resultp.get(DondeEsta_MainActivity.TIPO_MENU);
String id_categoria_donde_esta =resultp.get(DondeEsta_MainActivity.ID_CATEGORIA_DONDE_ESTA);
// Locate the TextViews in listview_item.xml
nombre_categoria_donde_esta_textView = (TextView) itemView.findViewById(R.id.textView1);
imagen_categoria_donde_esta = (ImageView) itemView.findViewById(R.id.imageView1);
nombre_categoria_donde_esta_textView.setText (resultp.get(DondeEsta_MainActivity.NOMBRE_CATEGORIA_DONDE_ESTA));
imageLoader.DisplayImage(resultp.get(DondeEsta_MainActivity.IMAGEN_CATEGORIA_DONDE_ESTA), imagen_categoria_donde_esta);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
String tipo_de_menu = resultp.get(DondeEsta_MainActivity.TIPO_MENU);
Log.i("TIPO DE MENU =", tipo_de_menu);
if (tipo_de_menu.equals("1")){
Log.i("PULSADO =", tipo_de_menu);
//TIPO 1
String idPrueba = resultp.get(DondeEsta_MainActivity.ID_CATEGORIA_DONDE_ESTA);
System.out.println("la id en DONDEESTA_LV ANTES DE PASARLA A T1 ++++++++++++++++++ ES: " + idPrueba);
Intent intent = new Intent(context, DondeEsta_T1_MainActivity.class);
intent.putExtra("idPrueba", idPrueba);
context.startActivity(intent);
}
else
//TIPO 2
if (tipo_de_menu.equals("2")){
Log.i("PULSADO =", tipo_de_menu);
//TIPO 2
String idPrueba = resultp.get(DondeEsta_MainActivity.ID_CATEGORIA_DONDE_ESTA);
System.out.println("la id en DONDEESTA_LV ANTES DE PASARLA A T1 ++++++++++++++++++ ES: " + idPrueba);
Intent intent = new Intent(context, DondeEsta_T2_MainActivity.class);
intent.putExtra("idPrueba", idPrueba);
context.startActivity(intent);
}
else {
Intent intent = new Intent(context, DondeEsta_SingleItemView.class);
}
}
});
return itemView;
}
}
ACTIVITY 2 MAIN ACTIVITY
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;
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.util.Log;
import android.widget.ListView;
public class DondeEsta_T1_MainActivity extends Activity {
// Declare Variables
private static final String TAG_NAME = "nombreCategoria";
private static final String TAG_ID = "idPrueba";
private String name = "Categoria";
private String id = "id";
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
DondeEsta_T1_ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String ID_DES= "id_des";
static String TITULO_DES = "titulo_des";
static String CATEGORIAS_DES = "categoria_des";
static String LUGAR_DES = "lugar_des";
static String LATITUD_DES = "latitud_des";
static String LONGITUD_DES = "longitud_des";
static String IMAGEN_DES = "imagen_des";
static String DESCRIPCION_DES = "descripcion_des";
static String WEB_DES = "web_des";
static String MAIL_DES = "mail_des";
static String TEL_DES = "tel_des";
static String LUGAR_CORTO = "lugar_corto";
static String idPrueba = "idPrueba";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("MVASCO", "context is null!");
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
name = in.getStringExtra(TAG_NAME);
id = in.getStringExtra(TAG_ID);
idPrueba =in.getStringExtra(idPrueba);
setContentView(R.layout.dondeesta_t1_listview_main);
// Execute DownloadJSON AsyncTask
//new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
// Log.v("categoria para pasar a la URL", id_categoria_donde_esta);
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://..URL hidden.../casajuventud/app_php_files/recuperar_categorias_donde_esta_t1.php?cat="+idPrueba);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("Categorias");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("id_des", jsonobject.getString("id_des"));
map.put("titulo_des", jsonobject.getString("titulo_des"));
map.put("categoria_des", jsonobject.getString("categoria_des"));
map.put("lugar_des", jsonobject.getString("lugar_des"));
map.put("latitud_des", jsonobject.getString("latitud_des"));
map.put("longitud_des", jsonobject.getString("longitud_des"));
map.put("descripcion_des", jsonobject.getString("descripcion_des"));
map.put("web_des", jsonobject.getString("web_des"));
map.put("mail_des", jsonobject.getString("mail_des"));
map.put("imagen_des", "http://www.solinpromex.com/casajuventud/sitios/"+jsonobject.getString("imagen_des"));
map.put("tel_des", jsonobject.getString("tel_des"));
map.put("lugar_corto", jsonobject.getString("lugar_corto"));
// Set the JSON Objects into the array
arraylist.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
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new DondeEsta_T1_ListViewAdapter(DondeEsta_T1_MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
new DownloadJSON().execute();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
}
ACTIVITY 2 LISTVIEWADAPTER
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
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.RelativeLayout;
import android.widget.TextView;
public class DondeEsta_T1_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 DondeEsta_T1_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 id_des;
TextView titulo_des;
TextView categoria_des;
TextView lugar_des;
TextView latitud_des;
TextView longitud_des;
ImageView imagen_des;
TextView descripcion_des;
TextView web_des;
TextView tel_des;
TextView lugar_corto;
TextView mail_des;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.dondeesta_t1_listview_item, parent, false);
// Get the position
resultp = data.get(position);
RelativeLayout myLayout = (RelativeLayout) itemView.findViewById(R.id.milayout);
if (position % 2 == 1) {
myLayout.setBackgroundResource(R.color.fondo);
//lugar_evento.setBackgroundResource(R.color.fondo);
} else {
myLayout.setBackgroundResource(R.color.blanco);
//titulo_evento.setBackgroundResource(R.color.blanco);
//lugar_evento.setBackgroundResource(R.color.blanco);
}
String tipo_de_menu = resultp.get(DondeEsta_MainActivity.TIPO_MENU);
// Locate the TextViews in listview_item.xml
titulo_des = (TextView) itemView.findViewById(R.id.textView1);
lugar_corto = (TextView) itemView.findViewById(R.id.textView2);
titulo_des.setText (resultp.get(DondeEsta_T1_MainActivity.TITULO_DES));
lugar_corto.setText (resultp.get(DondeEsta_T1_MainActivity.LUGAR_CORTO));
// imageLoader.DisplayImage(resultp.get(DondeEsta_MainActivity.IMAGEN_CATEGORIA_DONDE_ESTA), imagen_categoria_donde_esta);
// 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, DondeEsta_T1_SingleItemView.class);
// Pass all data rank
intent.putExtra("titulo_des", resultp.get(DondeEsta_T1_MainActivity.TITULO_DES));
intent.putExtra("lugar_des", resultp.get(DondeEsta_T1_MainActivity.LUGAR_DES));
intent.putExtra("latitud_des", resultp.get(DondeEsta_T1_MainActivity.LATITUD_DES));
intent.putExtra("longitud_des", resultp.get(DondeEsta_T1_MainActivity.LONGITUD_DES));
intent.putExtra("imagen_des", resultp.get(DondeEsta_T1_MainActivity.IMAGEN_DES));
intent.putExtra("descripcion_des", resultp.get(DondeEsta_T1_MainActivity.DESCRIPCION_DES));
intent.putExtra("web_des", resultp.get(DondeEsta_T1_MainActivity.WEB_DES));
intent.putExtra("tel_des", resultp.get(DondeEsta_T1_MainActivity.TEL_DES));
intent.putExtra("mail_des", resultp.get(DondeEsta_T1_MainActivity.MAIL_DES));
intent.putExtra("lugar_corto", resultp.get(DondeEsta_T1_MainActivity.LUGAR_CORTO));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
just put
#Override
public void onBackPressed(){
finish();
}
somewhere inside second Activity.
also after idPrueba =in.getStringExtra(idPrueba); you might try in.removeExtra("idPrueba");
and the last: why idPrueba is static? code key as other variable, static final, and get your passed value to another variable. when you starting second Activity for the first time you fetching newly arrived varriable and assigning it to key variable. this value is static, so second call of Activity have previosly overwritten key (not "idPrueba", but value of previously passed variable under "idPrueba" key). probably this is your issue
for this code the easiest way is to remove static before String idPrueba = "idPrueba"; but I suggest you to separate key and value variables. also check setOnItemClickListener method, more convenient
I've got a functioning Universal Image Loader that I'm trying to switch to grabbing the image URLs from JSON rather than the Constants Class that it normally uses. I've created a JSON Parsing Class that outputs an ArrayList called galleryArrList. But I can't figure out how to implement my JSON Parsing class and also how to modify the Adapter class in the UILGrid class to accept the galleryArrList String. Here are the Classes:
UILGrid Class:
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.mysite.wcbc.UKVPConstants.Extra;
public class UILGrid extends AbsListViewBaseActivity {
String[] imageUrls;
DisplayImageOptions options;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.uil_grid);
Bundle bundle = getIntent().getExtras();
imageUrls = bundle.getStringArray(Extra.IMAGES);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error).cacheInMemory(true)
.cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565).build();
listView = (GridView) findViewById(R.id.uil_gridview);
((GridView) listView).setAdapter(new ImageAdapter());
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
startImagePagerActivity(position);
}
});
}
private void startImagePagerActivity(int position) {
Intent intent = new Intent(this, CVP2.class); // ---- Change here
intent.putExtra(Extra.IMAGES, imageUrls);
intent.putExtra(Extra.IMAGE_POSITION, position);
startActivity(intent);
}
public class ImageAdapter extends BaseAdapter {
#Override
public int getCount() {
return imageUrls.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ImageView imageView;
if (convertView == null) {
imageView = (ImageView) getLayoutInflater().inflate(
R.layout.uil_grid_item, parent, false);
} else {
imageView = (ImageView) convertView;
}
imageLoader.displayImage(imageUrls[position], imageView, options);
return imageView;
}
}
}
my UILJSONParse Class:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
public class UILJSONParse extends AsyncTask<String, String, JSONObject> {
// url to make request
private static String url = "http://www.mysite.com/apps/wcbc/galleryuil.txt";
// Hashmap for ListView
// ArrayList<HashMap<String, String>> arraylist;
ArrayList<HashMap<String, String>> galleryArrList = new ArrayList<HashMap<String, String>>();
// JSON Node names
private static final String TAG_GALLERY = "gallery";
private static final String TAG_GALLERYURL = "galleryurl";
private static final String TAG_ID = "id";
private static final String TAG_GALLERYDESCR = "gallerydescr";
// gallery JSONArray
JSONArray JSArrGallery = null;
#Override
protected JSONObject doInBackground(String... arg0) {
// Creating JSON Parser instance
JGrid4Adapter jParser = new JGrid4Adapter();
// getting JSON string from URL
JSONObject jsonOb = jParser.getJSONFromUrl(url);
return jsonOb;
}
#Override
protected void onPostExecute(JSONObject jsonOb) {
try {
JSArrGallery = jsonOb.getJSONArray(TAG_GALLERY);
// looping through All gallery images
for (int i = 0; i < JSArrGallery.length(); i++) {
JSONObject galleryJO = JSArrGallery.getJSONObject(i);
String idStr = galleryJO.getString(TAG_ID);
String urlStr = galleryJO.getString(TAG_GALLERYURL);
String descrStr = galleryJO.getString(TAG_GALLERYDESCR);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, idStr);
map.put(TAG_GALLERYURL, urlStr);
map.put(TAG_GALLERYDESCR, descrStr);
// adding HashMap map to ArrayList galleryArrList, defined
// above
galleryArrList.add(map);
}// -- END for loop
} catch (JSONException e) {
e.printStackTrace();
}// --- END Try
}// --- END onPostExecute
}// --- END UILJSONParse Class
I've figured this out since asking the question. I have a Button Interface Activity where an AsyncTask is called that grabs the JSON data when a button is clicked. The AysncTask then bundles the data and sends it to my Gallery Grid Class. The AsyncTask is calling the above JSON Parsing Class. So here's the code:
// --- artwork button
cartoon_BTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
jsonFileStr = "artwork_json";
new ArtworkJSON().execute();
}
});
// --- end artwork button
private class ArtworkJSON extends AsyncTask<Void, Void, Void> {
JSONObject jsonobject;
String TAG_ID = "id";
String TAG_DESCR = "artworkdescr";
String TAG_MEDIUM = "artworkmedium";
String TAG_PRICE = "artworkprice";
String TAG_URL = "artworkurl";
ArrayList<HashMap<String, String>> hashArraylist;
ArrayList<String> urlArrayList;
ArrayList<String> idArrayList;
ArrayList<String> descrArrayList;
ArrayList<String> mediumArrayList;
ArrayList<String> priceArrayList;
String[] idStrArray, urlStrArray, descrStrArray, mediumStrArray,
priceStrArray;
String urlPathStr = "http://www.mysite.com/"
+ jsonFileStr + ".txt";
JSONArray JSArrArtwork = null;
String idStr, urlStr, descrStr, mediumStr, priceStr;
ProgressDialog loadImagesDia;
Intent bundleIn;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
loadImagesDia = new ProgressDialog(Main_Interface.this);
loadImagesDia.setMessage("Loading Images...");
loadImagesDia.setIndeterminate(false);
// Show progressdialog
loadImagesDia.show();
}
#Override
protected Void doInBackground(Void... params) {
hashArraylist = new ArrayList<HashMap<String, String>>();//
// Retrieve JSON Objects from the given URL address
jsonobject = JSONforGallery.getJSONfromURL(urlPathStr);
try {
// Locate the array name in JSON
JSArrArtwork = jsonobject.getJSONArray("artwork");
idArrayList = new ArrayList<String>();
urlArrayList = new ArrayList<String>();
descrArrayList = new ArrayList<String>();
mediumArrayList = new ArrayList<String>();
priceArrayList = new ArrayList<String>();
for (int i = 0; i < JSArrArtwork.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();//
JSONObject artworkJO = JSArrArtwork.getJSONObject(i);
map.put("id", artworkJO.getString(TAG_ID));//
map.put("url", artworkJO.getString(TAG_URL));//
map.put("descr", artworkJO.getString(TAG_DESCR));//
map.put("medium", artworkJO.getString(TAG_MEDIUM));//
map.put("price", artworkJO.getString(TAG_PRICE));//
idStr = artworkJO.getString(TAG_ID);
urlStr = artworkJO.getString(TAG_URL);
descrStr = artworkJO.getString(TAG_DESCR);
mediumStr = artworkJO.getString(TAG_MEDIUM);
priceStr = artworkJO.getString(TAG_PRICE);
hashArraylist.add(map);//
idArrayList.add(idStr);
urlArrayList.add(urlStr);
descrArrayList.add(descrStr);
mediumArrayList.add(mediumStr);
priceArrayList.add(priceStr);
idStrArray = idArrayList.toArray(new String[idArrayList
.size()]);
urlStrArray = urlArrayList.toArray(new String[urlArrayList
.size()]);
descrStrArray = descrArrayList
.toArray(new String[descrArrayList.size()]);
mediumStrArray = mediumArrayList
.toArray(new String[mediumArrayList.size()]);
priceStrArray = priceArrayList
.toArray(new String[priceArrayList.size()]);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
loadImagesDia.dismiss();
bundleIn = new Intent("com.veedabugmedia.ktg.UILGRID");
bundleIn.putExtra("idStrArrayKey", idStrArray);
bundleIn.putExtra("hashARKey", hashArraylist);
bundleIn.putExtra("urlStrArrayKey", urlStrArray);
bundleIn.putExtra("descrStrArrayKey", descrStrArray);
bundleIn.putExtra("mediumStrArrayKey", mediumStrArray);
bundleIn.putExtra("priceStrArrayKey", priceStrArray);
startActivity(bundleIn);
}
}
My updated UILGrid Activity:
public class UILGrid extends AbsListViewBaseActivity {
String[] idStr, imageUrls, descrStrGrid, mediumStrGrid, priceStrGrid;
DisplayImageOptions options;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.uil_grid);
// Retrieve data from About_Interface on item click event
Intent getBundsIn = getIntent();
idStr = getBundsIn.getStringArrayExtra("idStrArrayKey");
imageUrls = getBundsIn.getStringArrayExtra("urlStrArrayKey");
descrStrGrid = getBundsIn.getStringArrayExtra("descrStrArrayKey");
mediumStrGrid = getBundsIn.getStringArrayExtra("mediumStrArrayKey");
priceStrGrid = getBundsIn.getStringArrayExtra("priceStrArrayKey");
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error).cacheInMemory(true)
.cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565).build();
listView = (GridView) findViewById(R.id.uil_gridview);
((GridView) listView).setAdapter(new ImageAdapter());
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
startImagePagerActivity(position);
}
});
}// --- END onCreate
private void startImagePagerActivity(int position) {
Intent pagerIn = new Intent(this, UILPager.class);
pagerIn.putExtra("pagerUrlStrKey", imageUrls);
pagerIn.putExtra("pagerDescrStrKey", descrStrGrid);
pagerIn.putExtra("pagerMediumStrKey", mediumStrGrid);
pagerIn.putExtra("pagerPriceStrKey", priceStrGrid);
pagerIn.putExtra("pagerPositionKey", position);
startActivity(pagerIn);
}
public class ImageAdapter extends BaseAdapter {
#Override
public int getCount() {
return imageUrls.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ImageView imageView;
if (convertView == null) {
imageView = (ImageView) getLayoutInflater().inflate(
R.layout.uil_grid_item, parent, false);
} else {
imageView = (ImageView) convertView;
}
imageLoader.displayImage(imageUrls[position], imageView, options);
return imageView;
}
}
#Override
protected void onPause() {
super.onPause();
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
UILGrid.this.finish();
}
}
I have an Activity with GridView, with images in it. The images are parsed from the SD card of the device. Once the Activity starts, images are downloaded to the SD card using AsyncTask.
The problem is that this GridView does not get updated when images are downloaded. I want this GridView to be updated if more images are added to the directory (i.e. if more images are downloaded). I have tried notifyDataSetChanged() and invalidateViews(), however they are not helping.
Here is my code for the MainActivity, Image adapter and AsyncTask. Please try to show me where I made the mistake.
MainActivity:
ImageAdapter ia = new ImageAdapter(this);
GridView gridView;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
gridView = (GridView) findViewById(R.id.grid_view);
// Instance of ImageAdapter Class
ImageAdapter iAdapter = new ImageAdapter(this);
gridView.setAdapter(iAdapter);
iAdapter.notifyDataSetChanged();
gridView.invalidateViews();
new ImageDownlader(AndroidGridLayoutActivity.this, this).execute(downloadUrl);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// Sending image id to FullScreenActivity
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
// passing array index
i.putExtra("id", position);
startActivity(i);
}
});
getView() of Image Adapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageBitmap(getImageByIndex(imageThumbnails, position));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(155, 155));
return imageView;
}
ImageDownlader:
class ImageDownlader extends AsyncTask<String, Void, Void> {
private Context context;
public ImageDownlader(Context c){
context = c;
}
Sync s = new Sync();
#Override
protected Void doInBackground(String... param) {
// this is where images are downloaded to SD card
saveToSD ();
return null;
}
#Override
protected void onPreExecute() {
Log.i("Async-Example", "onPreExecute Called");
}
protected void onPostExecute()
{
Log.i("Async-Example", "onPostExecute Called");
}
The first, you should download Image from URL and return it.
import java.io.InputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
public 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);
}
}
The second, create an Adapter
import java.util.List;
import vn.mve.obj.Video;
import vn.mve.util.DownloadImageTask;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import vn.mve.e4u.Detail;
import vn.mve.e4u.R;
public class VideoAdapter extends BaseAdapter {
private List<Video> list;
private Context context;
private LayoutInflater inflater;
public VideoAdapter(Context context, List<Video> list) {
this.context = context;
this.list = list;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = inflater.inflate(R.layout.layout_video_gridview, parent, false);
ImageView iv_thumb = (ImageView) view.findViewById(R.id.iv_thumb);
new DownloadImageTask(iv_thumb).execute(list.get(position).getThumbnail());
TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
tv_title.setText(list.get(position).getTitle());
LinearLayout item = (LinearLayout) view.findViewById(R.id.item);
item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, Detail.class);
intent.putExtra("ID", list.get(position).getId());
context.startActivity(intent);
}
});
return view;
}
}
Right here:
new DownloadImageTask(iv_thumb).execute(list.get(position).getThumbnail());
You can Create an Instance of DownloadImageTask, after that you can get an Image like that:
imageTask = new DownloadImageTask(iv_thumb).execute(list.get(position).getThumbnail());
Bitmap myImage = imageTask.get(); // Please put in try-catch
The last, in MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Video> list = null;
MVideo mVideo = new MVideo(getApplicationContext());
list = mVideo.getList(VideoType.GET_ALL);
VideoAdapter adapter = new VideoAdapter(this, list);
if (list != null) {
GridView gvVideo = (GridView) findViewById(R.id.gv_video);
gvVideo.setAdapter(adapter);
}
}
Hope this will help you!