I am using AsyncTask in my fragment for loading a list of data by Json. After clicking each list items this list fragment is replaced by details fragment containing details information. Then in new fragment (details fragment) user presses back button. Then again list fragment starts.
The problem is that Asynctask reloads again to fetch list items. I don't want this. I want to show previously loaded list. Here is the code:
public class MainList extends Fragment {
public MainList(){}
ArrayList<Country> countryList = new ArrayList<Country>();
Country country;
Button btnLoadMore;
ListView listView;
JSONParser jsonParser = new JSONParser();
public static String received_id;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
int current_page = 0;
int last_item;
int total_items = 32;
boolean continue_loading = true;
boolean loadingMore = false;
View footerView;
public ImageLoader_Json imageLoader;
int currentPosition = 0;
MyCustomAdapter dataAdapter = null;
private static String url_all_products_LoadMore = "http://www.hitel.ir/FarsiPlanet/Apps.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_RATE = "rate";
private static final String TAG_RATINGCOUNT = "ratingcount";
private static final String TAG_SHORT_DESCRIPTION = "short_description";
// products JSONArray
JSONArray products = null;
String Category;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.items_list, container, false);
Category = getArguments().getString("category");
footerView= ((LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.loading_footer, null,false);
listView = (ListView) rootView.findViewById(R.id.listView1);
listView.addFooterView(footerView);
imageLoader = new ImageLoader_Json(getActivity().getApplicationContext());
displayListView();
return rootView;
}
private void displayListView() {
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(getActivity(),
R.layout.country_info, countryList);
listView.setOnScrollListener(new OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if((lastInScreen == totalItemCount) && !(loadingMore)){
new loadMoreListView().execute();
}
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
final String pid = ((TextView) view.findViewById(R.id.pid)).getText().toString();
Bundle data = new Bundle();
data.putString(TAG_PID, pid);
data.putString("TAG_Category", Category);
Fragment fragment = new Details_Restaurant();
FragmentManager fm = getFragmentManager();
fragment.setArguments(data);
fm.beginTransaction().replace(R.id.frame_container, fragment).addToBackStack("f_02").commit();
}
});
listView.setAdapter(dataAdapter);
listView.setSelectionFromTop(currentPosition, 0);
}
private class MyCustomAdapter extends ArrayAdapter<Country> {
private ArrayList<Country> countryList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Country> countryList) {
super(context, textViewResourceId, countryList);
this.countryList = new ArrayList<Country>();
this.countryList.addAll(countryList);
}
private class ViewHolder {
TextView code;
TextView name;
RatingBar rate;
TextView ratingcount;
TextView short_description;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.country_info, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.ratingcount = (TextView) convertView.findViewById(R.id.ratingCount);
holder.short_description = (TextView) convertView.findViewById(R.id.short_description);
holder.rate = (RatingBar) convertView.findViewById(R.id.ratingBar1);
holder.code = (TextView) convertView.findViewById(R.id.pid);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Country country = countryList.get(position);
holder.name.setText(country.getName());
holder.ratingcount.setText(country.getRatingCount());
holder.short_description.setText(country.getShort_description());
holder.rate.setRating(country.getRate());
holder.code.setText(country.getCode());
return convertView;
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
class loadMoreListView extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
/*
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("درحال دريافت اطلاعات...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show(); */
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
String firts_item = Integer.toString(current_page*10);
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", firts_item));
params.add(new BasicNameValuePair("category", Category));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_all_products_LoadMore, "GET", params);
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
Float rate = (float) c.getInt(TAG_RATE);
String ratingcount = c.getString(TAG_RATINGCOUNT);
String short_description = c.getString(TAG_SHORT_DESCRIPTION);
country = new Country(id,name,rate,ratingcount,short_description,"","");
countryList.add(country);
}
}
else{
continue_loading = false;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
current_page += 1;
if (continue_loading) {
currentPosition = listView.getFirstVisiblePosition();
dataAdapter.notifyDataSetChanged();
displayListView();
loadingMore = false;
} else {
listView.removeFooterView(footerView);
}
}
}
}
Here you need to include #Override before calling onScrollStateChanged and onScroll
listView.setOnScrollListener(new OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if((lastInScreen == totalItemCount) && !(loadingMore)){
new loadMoreListView().execute();
}
}
});
when you perform the replace() action on the fragment, you are removing the list fragment , thus when tapping back, you are replacing the details fragment with your listfragment which invokes onCreateView() as part of the fragments lifecycle.
I would try to either keep a static booelan set to true when the asynctask's onPostExecute() ends, so the next time the list fragment's onCreateView() will be invoked , you would check the value of the flag and if set to true will not execute the task, but just set the adapter with the old static data.
Related
I am getting response from server and display it using listview and it works fine,now what I am trying is i added autocompletetextview to search items by name,but when i run my app it crashes and showing errors..i already ask this
Tab1Activity.java
public class Tab1Activity extends ListActivity{
private ProgressDialog pDialog;
JSONArray Product=null;
private ListView listview;
ArrayList<HashMap<String,String>> aList;
ArrayList<HashMap<String, String>> arrayTemplist;
private static String PRODUCT_URL = "";
private static final String PRODUCT_DATA="Product";
private static final String PRODUCT_ID="productid";
private static final String PRODUCT_NAME="product_name";
private static final String PRODUCT_CODE="skucode";
private static final String PRODUCT_IMAGE="product_photo";
private static final String PRODUCT_WEIGHT="weight";
private static final String PRODUCT_SALERATE="sale_rate";
//private static final String PRODUCT_LOCATION="weight";
private CustomAdapterTabone adapter;
private TextView noacpt;
private AutoCompleteTextView inputSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view_tabone);
//noacpt=(TextView)findViewById(R.id.no_acceptedlist);
/*String strtext = getIntent().getStringExtra("id");
System.out.println("<<<<<<<< id : " + strtext);*/
final ListView listview = (ListView)findViewById(android.R.id.list);
//listview.setSelector( R.drawable.list_selector);
//listview.setSelector(R.drawable.listselector);
new LoadAlbums().execute();
aList = new ArrayList<HashMap<String, String>>();
final ListView lv = getListView();
inputSearch = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
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 < aList.size(); i++)
{
String currentString =aList.get(i).get(Tab1Activity.PRODUCT_NAME);
if (currentString.toLowerCase().startsWith(searchString ))
{
arrayTemplist.add(aList.get(i));
}
}
for (int i = 0; i < arrayTemplist.size(); i++)
{
String currentstrin = arrayTemplist.get(i).get(Tab1Activity.PRODUCT_NAME);
//Toast.makeText(getApplicationContext(), currentstrin, Toast.LENGTH_LONG).show();
}
adapter=new CustomAdapterTabone(getApplicationContext(), arrayTemplist);
listview.setAdapter(adapter);
/* SimpleAdapter adapters = new SimpleAdapter(Tab1Activity.this, arrayTemplist,R.layout.list_item_tabone, new String[] { PRODUCT_NAME
}, new int[] {
R.id.txtpronameacptedlist});
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
}
});
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = new Intent(getApplicationContext(), AllProductDetails.class);
intent.putExtra("productid", aList.get(position).get(PRODUCT_ID));
startActivity(intent);
}
class LoadAlbums extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Tab1Activity.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(true);
// pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(false);
pDialog.show();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(PRODUCT_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
Product = jsonObj.getJSONArray(PRODUCT_DATA);
for (int i = 0; i < Product.length(); i++) {
JSONObject c = Product.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(PRODUCT_ID, c.getString(PRODUCT_ID));
map.put(PRODUCT_NAME,c.getString(PRODUCT_NAME));
map.put(PRODUCT_CODE, c.getString(PRODUCT_CODE));
map.put(PRODUCT_IMAGE, c.getString(PRODUCT_IMAGE));
map.put(PRODUCT_WEIGHT, c.getString(PRODUCT_WEIGHT));
map.put(PRODUCT_SALERATE, c.getString(PRODUCT_SALERATE)+getResources().getString(R.string.rupee));
// map.put(INTEREST_ACCEPT_LOCATION, c.getString(INTEREST_ACCEPT_LOCATION));
// adding HashList to ArrayList
data.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return data;
}
protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
// dismiss the dialog after getting all albums
if (pDialog.isShowing())
pDialog.dismiss();
// updating UI from Background Thread
aList = new ArrayList<HashMap<String, String>>();
aList.addAll(result);
adapter = new CustomAdapterTabone(getApplicationContext(),result);
setListAdapter(adapter);
aList.addAll(result);
adapter.notifyDataSetChanged();
}
}
CustomAdapter
public class CustomAdapterTabone extends BaseAdapter{
private Context context;
private ArrayList<HashMap<String,String>> listData;
private AQuery aQuery;
private static final String TAG_NAME="product_name";
private static final String TAG_PROFILE="skucode";
private static final String TAG_IMAGE="product_photo";
private static final String TAG_CAST="weight";
private static final String TAG_AGE="sale_rate";
// private static final String TAG_LOCATION="weight";
public CustomAdapterTabone(Context context,ArrayList<HashMap<String,String>> listData) {
this.context = context;
this.listData=listData;
aQuery = new AQuery(this.context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.list_item_tabone, null);
holder.propic = (ImageView) convertView.findViewById(R.id.propicaccept);
holder.txtproname = (TextView) convertView.findViewById(R.id.txtpronameacptedlist);
holder.txtproid = (TextView) convertView.findViewById(R.id.txtproidacptedlist);
holder.txtprofilecast = (TextView) convertView.findViewById(R.id.txtprofilecastacptedlist);
holder.txtprofileage = (TextView) convertView.findViewById(R.id.txtprofileageacptedlist);
// holder.txtprofileplace = (TextView) convertView.findViewById(R.id.txtprofileplaceacptedlist);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtproname.setText(listData.get(position).get(TAG_NAME));
holder.txtproid.setText(listData.get(position).get(TAG_PROFILE));
holder.txtprofilecast.setText(listData.get(position).get(TAG_CAST));
holder.txtprofileage.setText(listData.get(position).get(TAG_AGE));
//holder.txtprofileplace.setText(listData.get(position).get(TAG_LOCATION));
aQuery.id(holder.propic).image(listData.get(position).get(TAG_IMAGE),true,true,0,R.drawable.ic_launcher);
// image parameter : 1 : memory cache,2:file cache,3:target width,4:fallback image
return convertView;
}
class ViewHolder{
ImageView propic;
TextView txtproname;
TextView txtproid;
TextView txtprofilecast;
TextView txtprofileage;
TextView txtprofileplace;
}
}
First create a custom adapter implements filterable:
public class MyFilterableAdapter extends BaseAdapter implements Filterable {
private Context context;
private List<String> items;
private List<String> filteredItems;
private ItemFilter mFilter = new ItemFilter();
public MyFilterableAdapter(Context context, List<String> items) {
//super(context, R.layout.your_row, items);
this.context = context;
this.items = items;
this.filteredItems = items;
}
#Override
public int getCount() {
return filteredItems.size();
}
#Override
public Object getItem(int position) {
return filteredItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row_search_merchant, parent, false);
viewHolder = new ViewHolder();
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
String location = filteredItems.get(position);
if (!location.isEmpty() || viewHolder != null) {
viewHolder.tvTitle.setText(location);
}
return convertView;
}
public static class ViewHolder {
TextView tvTitle;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
int count = items.size();
final List<String> tempItems = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
if (items.get(i).toLowerCase().contains(filterString)) {
tempItems.add(items.get(i));
}
}
results.values = tempItems;
results.count = tempItems.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredItems = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
public Filter getFilter() {
return mFilter;
}
}
And than create a textwatcher
public class MyTextWatcher implements TextWatcher {
private MyCustomAdapter lAdapter;
public MyTextWatcher(MyCustomAdapter lAdapter) {
this.lAdapter = lAdapter;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
lAdapter.getFilter().filter(s.toString().toLowerCase());
}
}
And finally add your TextWatcher to your Search Edit Text:
final MyCustomAdapter lAdapter = new MyCustomAdapter(context, items);
EditText etSearch = (EditText) view.findViewById(R.id.et_search);
etSearch.addTextChangedListener(new SearchTextWatcher(lAdapter));
I hope this'll help you.
I'm newbie Android Programming. I have Fragment which shows on Listview and now, i want Listview load more item when list ends. But data is not appending. I need help !
My code :
public class InfoTeacherFragment extends Fragment {
private String URL = "http://scv.udn.vn/dhdn/trdhsp/page/";
ProgressDialog pDialog;
Context mContext;
Vector<ArrayList<String>> data;
ArrayList<String> Name;
ArrayList<String> School;
ArrayList<String> Link;
ArrayList<String> Icon;
ListView lvItem;
DisplayImageOptions options;
ImageLoader imageloader;
View mFooterView;
InfoTeacher adapter;
ProgressBar loading;
int CurrentPage = 1;
int visibleThreshold = 3;
int startPage = 1;
boolean loadingMore = false;
public InfoTeacherFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_mission)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error).cacheInMemory(true)
.cacheOnDisk(true).considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565).build();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.teacherinfo_layout,
container, false);
mContext = container.getContext();
lvItem = (ListView) rootView.findViewById(R.id.lvTeacher);
lvItem.setOnScrollListener(new EndlessScrollListener() {
#Override
public void onLoadMore(int page, int totalItemsCount) {
CurrentPage++;
customLoadMoreDataFromApi(CurrentPage);
Toast.makeText(mContext, "EndlessScrollListener",
Toast.LENGTH_SHORT).show();
}
});
imageloader = ImageLoader.getInstance();
imageloader.init(ImageLoaderConfiguration.createDefault(mContext));
if (Utils.isOnline(mContext) == true
&& Utils.KEY_CHECK_SUCCESS.equals("SUCCESS")) {
new LoadData().execute(URL + startPage);
lvItem.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view,
int position, long id) {
Intent intent = new Intent(mContext, NewsItemView.class);
if (Link != null) {
intent.putExtra("URL", Link.get(position));
startActivity(intent);
}
}
});
} else if (Utils.isOnline(mContext) == true
&& Utils.KEY_CHECK_SUCCESS.equals("FAIL")) {
Utils.MyToast(Utils.KEYWORK_ERROR[0], R.drawable.warning_icon,
mContext, false);
}
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
AnimateFirstDisplayListener.displayedImages.clear();
}
class LoadData extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
pDialog = ProgressDialog.show(mContext, "", Utils.KEYWORK_ERROR[2]);
data = new Vector<ArrayList<String>>();
Name = new ArrayList<String>();
School = new ArrayList<String>();
Link = new ArrayList<String>();
Icon = new ArrayList<String>();
super.onPreExecute();
}
#Override
protected String doInBackground(String... URL) {
data = Utils.getInformationTeacher(URL[0]);
if (!(data.isEmpty())) {
return Utils.KEY_CHECK_SUCCESS;
} else {
return Utils.KEY_CHECK_FAIL;
}
}
#Override
protected void onPostExecute(String result) {
if (result.equals(Utils.KEY_CHECK_SUCCESS)) {
pDialog.dismiss();
Name = data.get(0);
School = data.get(1);
Icon = data.get(2);
Link = data.get(3);
adapter = new InfoTeacher(mContext, Name, School, Icon);
lvItem.setAdapter(adapter);
} else if (result.equals(Utils.KEY_CHECK_FAIL)) {
pDialog.dismiss();
Utils.MyToast(Utils.KEYWORK_ERROR[0], R.drawable.warning_icon,
mContext, false);
}
super.onPostExecute(result);
}
}
class InfoTeacher extends BaseAdapter {
private ArrayList<String> Icon = new ArrayList<String>();
private ArrayList<String> Name = new ArrayList<String>();
private ArrayList<String> School = new ArrayList<String>();
private LayoutInflater inflater;
ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
public InfoTeacher(Context context, ArrayList<String> Name,
ArrayList<String> School, ArrayList<String> Icon) {
this.Name = Name;
this.Icon = Icon;
this.School = School;
Collections.reverse(Name);
Collections.reverse(School);
Collections.reverse(Icon);
inflater = LayoutInflater.from(getActivity());
}
#Override
public int getCount() {
return Name.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup arg2) {
View rowView = view;
ViewHolder holder;
if (rowView == null) {
holder = new ViewHolder();
rowView = inflater
.inflate(R.layout.teacher_layout, arg2, false);
holder.Name = (TextView) rowView
.findViewById(R.id.tv_NameTeacher);
holder.School = (TextView) rowView.findViewById(R.id.tv_School);
holder.ic_naviga = (ImageView) rowView
.findViewById(R.id.ivNaviga);
holder.icon = (ImageView) rowView
.findViewById(R.id.iv_IconTeacher);
rowView.setTag(holder);
} else
holder = (ViewHolder) view.getTag();
final String mIcon = Icon.get(position);
holder.Name.setText(Name.get(position).toString());
holder.School.setText(School.get(position).toString());
ImageLoader.getInstance().displayImage(mIcon, holder.icon, options,
animateFirstListener);
return rowView;
}
}
static class ViewHolder {
ImageView icon;
TextView Name;
TextView School;
ImageView ic_naviga;
}
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);
}
}
}
}
public void customLoadMoreDataFromApi(int page) {
new LoadData().execute(URL + page);
adapter.notifyDataSetChanged();
// This method probably sends out a network request and appends new data
// items to your adapter.
// Use the offset value and add it as a parameter to your API request to
// retrieve paginated data.
// Deserialize API response and then construct new objects to append to
// the adapter
}
class LoadMoreItemsList extends
AsyncTask<Void, Void, Vector<ArrayList<String>>> {
private LoadMoreItemsList() {
loadingMore = true;
mFooterView = LayoutInflater.from(mContext).inflate(
R.layout.loading_view, null);
}
#Override
protected void onPreExecute() {
lvItem.addFooterView(mFooterView);
lvItem.setAdapter(adapter);
super.onPreExecute();
}
#Override
protected Vector<ArrayList<String>> doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Vector<ArrayList<String>> result) {
super.onPostExecute(result);
}
}
}
Function Utils.Utils.getInformationTeacher(URL[0]) :
public static Vector<ArrayList<String>> getInformationTeacher(String url) {
Vector<ArrayList<String>> data = new Vector<ArrayList<String>>();
ArrayList<String> Name = new ArrayList<String>();
ArrayList<String> School = new ArrayList<String>();
ArrayList<String> Link = new ArrayList<String>();
ArrayList<String> Icon = new ArrayList<String>();
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
Document doc = Jsoup.connect(url).timeout(10 * 300).get();
Charset.forName("UTF-8");
doc.outputSettings().escapeMode(EscapeMode.xhtml);
Elements eles = doc.select("div#Thu tbody a.linkheader");
Elements elesIcon = doc.select("div#Thu img[src]");
int i = 0;
for (Element element : eles) {
i++;
String fillinfo = element.ownText();
String link = element.attr("href");
if (i % 2 == 0) {
School.add(fillinfo);
} else {
Name.add(fillinfo);
Link.add(link);
}
}
for (Element icon : elesIcon) {
String hrefIcon = icon.attr("src");
Icon.add(hrefIcon);
}
data.add(Name);
data.add(School);
data.add(Icon);
data.add(Link);
} catch (IOException e) {
return data;
}
}
return data;
}
And Finally : abstract EndlessScrollListener
package android.readnews.support;
import android.util.Log;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
public abstract class EndlessScrollListener implements OnScrollListener {
// The minimum amount of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 5;
// The current offset index of data you have loaded
private int currentPage = 0;
// The total number of items in the dataset after the last load
private int previousTotalItemCount = 0;
// True if we are still waiting for the last set of data to load.
private boolean loading = true;
// Sets the starting page index
private int startingPageIndex = 0;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
public EndlessScrollListener(int visibleThreshold, int startPage) {
this.visibleThreshold = visibleThreshold;
this.startingPageIndex = startPage;
this.currentPage = startPage;
}
// This happens many times a second during a scroll, so be wary of the code
// you place here.
// We are given a few useful parameters to help us work out if we need to
// load some more data,
// but first we check if we are waiting for the previous load to finish.
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// If the total item count is zero and the previous isn't, assume the
// list is invalidated and should be reset back to initial state
if (totalItemCount < previousTotalItemCount) {
Log.i("abc", "ABC + totalItemCount < previousTotalItemCount");
this.currentPage = this.startingPageIndex;
this.previousTotalItemCount = totalItemCount;
if (totalItemCount == 0) {
this.loading = true;
}
}
// If it’s still loading, we check to see if the dataset count has
// changed, if so we conclude it has finished loading and update the
// current page
// number and total item count.
if (loading && (totalItemCount > previousTotalItemCount)) {
Log.i("abc", "ABC + totalItemCount > previousTotalItemCount");
loading = false;
previousTotalItemCount = totalItemCount;
currentPage++;
}
// If it isn’t currently loading, we check to see if we have breached
// the visibleThreshold and need to reload more data.
// If we do need to reload some more data, we execute onLoadMore to
// fetch the data.
if (!loading
&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
Log.i("abc", "ABC + !loading");
onLoadMore(currentPage + 1, totalItemCount);
loading = true;
}
}
// Defines the process for actually loading more data based on page
public abstract void onLoadMore(int page, int totalItemsCount);
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// Don't take any action on changed
}
}
I want load more 7 pages
In your LoadData AsyncTask, in onPostExecute, you always re-create the adapter with new data received, so it does not append the existing data.
What you need to do is add a method to InfoTeacher adapter to append new items to your existing data, and then call that method from onPostExecute if the adapter already exists (adapter != null).
I have a listview in fragment. It loads data from Json. After clicking list items a fragment transaction begins (replace). By pressing back button (in new fragment) again list fragment appears but the problem is that:
1: It loads again Asynctask (that I don't want it).
2. It adds new items on top of the former items in the list. You can say duplication in listview items happens. Each time I click listview item abd then return back to listview fragment it adds the same items to the end of the list. My code is this:
public class Followed extends Fragment {
public Followed(){}
ArrayList<Country> countryList = new ArrayList<Country>();
Country country;
ListView listView;
JSONParser jsonParser = new JSONParser();
public static String received_id;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
MyCustomAdapter dataAdapter = null;
ProgressDialog pDialog;
int success;
private static String url_all_followed = "http://www.hitel.ir/FarsiPlanet/Followed.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_RATE = "rate";
private static final String TAG_RATINGCOUNT = "ratingcount";
private static final String TAG_SHORT_DESCRIPTION = "short_description";
// products JSONArray
JSONArray products = null;
String Category;
String username;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.items_list, container, false);
loadSavedPreferences();
listView = (ListView) rootView.findViewById(R.id.listView1);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
final String pid = ((TextView) view.findViewById(R.id.pid)).getText().toString();
Bundle data = new Bundle();
data.putString(TAG_PID, pid);
data.putString("TAG_Category", "restaurant");
Fragment fragment = new Details_Restaurant();
FragmentManager fm = getFragmentManager();
fragment.setArguments(data);
fm.beginTransaction().replace(R.id.frame_container, fragment).addToBackStack("f_02asda").commit();
}
});
new loadMoreListView().execute();
return rootView;
}
private class MyCustomAdapter extends ArrayAdapter<Country> {
private ArrayList<Country> countryList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Country> countryList) {
super(context, textViewResourceId, countryList);
this.countryList = new ArrayList<Country>();
this.countryList.addAll(countryList);
}
private class ViewHolder {
TextView code;
TextView name;
RatingBar rate;
TextView ratingcount;
TextView short_description;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.country_info, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.ratingcount = (TextView) convertView.findViewById(R.id.ratingCount);
holder.short_description = (TextView) convertView.findViewById(R.id.short_description);
holder.rate = (RatingBar) convertView.findViewById(R.id.ratingBar1);
holder.code = (TextView) convertView.findViewById(R.id.pid);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Country country = countryList.get(position);
holder.name.setText(country.getName());
holder.ratingcount.setText(country.getRatingCount());
holder.short_description.setText(country.getShort_description());
holder.rate.setRating(country.getRate());
holder.code.setText(country.getCode());
return convertView;
}
}
class loadMoreListView extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("درحال دريافت اطلاعات...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "sajad"));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_all_followed, "GET", params);
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
Float rate = (float) c.getInt(TAG_RATE);
String ratingcount = c.getString(TAG_RATINGCOUNT);
String short_description = c.getString(TAG_SHORT_DESCRIPTION);
country = new Country(id,name,rate,ratingcount,short_description,"","");
countryList.add(country);
}
}
else{
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
if (success == 0) {
Toast.makeText(getActivity(), "هیچ موردی یافت نشد!", Toast.LENGTH_SHORT).show();
}
pDialog.dismiss();
dataAdapter = new MyCustomAdapter(getActivity(),
R.layout.country_info, countryList);
listView.setAdapter(dataAdapter);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
private void loadSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getActivity());
username = sharedPreferences.getString("username", "");
}
}
Alright. Found duplication problem. I just cleared adapter after clicking list items.
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
final String pid = ((TextView) view.findViewById(R.id.pid)).getText().toString();
Bundle data = new Bundle();
data.putString(TAG_PID, pid);
data.putString("TAG_Category", "restaurant");
Fragment fragment = new Details_Restaurant();
FragmentManager fm = getFragmentManager();
fragment.setArguments(data);
fm.beginTransaction().replace(R.id.frame_container, fragment).addToBackStack("f_02asda").commit();
dataAdapter.clear();
}
});
My listview doesn't show exact placement of images on its individual custom adapters. I am trying to load the images using AsyncTask. Sometimes the images duplicates and I don't have any idea why. Here is my ArrayAdapter code:
public class NewsPromoAdapter extends ArrayAdapter<NewsPromosDTO> {
private final Context context;
List<NewsPromosDTO> npList;
LayoutInflater inflater;
Bitmap src;
public NewsPromoAdapter(Context context, List<NewsPromosDTO> npList) {
super(context, R.layout.news_and_promos, npList);
this.context = context;
this.npList = npList;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public static class ViewHolder {
TextView nameText;
TextView date1Text;
ImageView imageView;
ProgressBar prg;
LoadImage loadImg;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.news_and_promos, parent,
false);
holder = new ViewHolder();
holder.nameText = (TextView) convertView
.findViewById(R.id.newspromo_name);
holder.date1Text = (TextView) convertView
.findViewById(R.id.newspromo_date);
holder.imageView = (ImageView) convertView
.findViewById(R.id.newspromo_imageView);
holder.prg = (ProgressBar) convertView
.findViewById(R.id.progressBar1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
holder.loadImg.cancel(true);
}
if (!(npList.get(position).getName().equals(""))) {
holder.nameText.setVisibility(View.VISIBLE);
holder.nameText.setText(npList.get(position).getName());
} else {
holder.nameText.setVisibility(View.GONE);
}
if (!(npList.get(position).getDate().equals(""))) {
holder.date1Text.setVisibility(View.VISIBLE);
holder.date1Text.setText(npList.get(position).getDate());
} else {
holder.date1Text.setVisibility(View.GONE);
}
if (!(npList.get(position).getImageURL().equals(""))) {
holder.imageView.setVisibility(View.VISIBLE);
holder.loadImg = new LoadImage(holder.imageView, npList.get(
position).getImageURL(), holder);
holder.loadImg.execute();
} else {
holder.imageView.setVisibility(View.GONE);
holder.prg.setVisibility(View.GONE);
}
return convertView;
}
class LoadImage extends AsyncTask<Object, Void, Bitmap> {
ViewHolder viewH;
private ImageView imv;
private String url;
public LoadImage(ImageView imv, String imageURL, ViewHolder viewH) {
this.imv = imv;
this.url = imageURL;
this.viewH = viewH;
}
#Override
protected Bitmap doInBackground(Object... params) {
BitmapFromURL bmpURL = new BitmapFromURL();
src = bmpURL.getBitmapFromURL(url);
return src;
}
#Override
protected void onPostExecute(Bitmap result) {
// imv.setImageBitmap(result);
// viewH.prg.setVisibility(View.GONE);
viewH.prg.setVisibility(View.GONE);
imv.setImageBitmap(result);
}
}
}
Here is the Activity that handles the ADAPTER. I am implementing the Endless listview approach that some big sites uses. Like Facebook, Twitter, etc..New Items loaded into the listview when scrolling into the bottom. I am not sure if I did it well.
public class ListNewsPromoActivity extends Activity {
List<NewsPromosDTO> npList;
String url, user_email;
Bundle extras;
int user_points;
List<Integer> npIDs;
private ProgressDialog progressDialog;
BitmapFromURL bmpURL;
JSONArray users = null;
String TAG_ID = "id";
String TAG_NAME = "name";
String TAG_PHOTO = "photo";
String TAG_DATE = "date";
String TAG_DESC = "description";
ListView list;
NewsPromoAdapter newsAdapter;
boolean loadingMore = false;
private Runnable returnRes;
int itemsPerPage = 3;
int currentIndex = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.news_promo_listview);
list = (ListView) findViewById(R.id.mainView);
extras = getIntent().getExtras();
if (extras != null) {
user_points = extras.getInt("user_points");
user_email = extras.getString("user_email");
}
url = getString(R.string.app_url_news_promos);
npIDs = new ArrayList<Integer>();
npList = new ArrayList<NewsPromosDTO>();
View footerView = ((LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.footer, null, false);
newsAdapter = new NewsPromoAdapter(ListNewsPromoActivity.this, npList);
list.addFooterView(footerView);
list.setAdapter(newsAdapter);
list.setOnScrollListener(new OnScrollListener() {
// useless here, skip!
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// what is the bottom item that is visible
int lastInScreen = firstVisibleItem + visibleItemCount;
// is the bottom item visible & not loading more already ? Load
if ((lastInScreen == totalItemCount) && !(loadingMore)) {
Thread thread = new Thread(null, getRunnable());
thread.start();
}
}
});
// Runnable to load the items
// Since we cant update our UI from a thread this Runnable takes care of
// that!
returnRes = new Runnable() {
#Override
public void run() {
// Loop thru the new items and add them to the adapter
for (NewsPromosDTO np : npList) {
System.out.println(np.getName() + " andito ako!!");
newsAdapter.add(np);
}
newsAdapter.notifyDataSetChanged();
// Done loading more.
loadingMore = false;
}
};
}
protected class loadNewsPromo extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(Void... params) {
// Creating JSON Parser instance
loadingMore = true;
JSONParser jParser = new JSONParser();
JSONObject json;
if (jParser.checkServer(url)) {
try {
// Getting Array of UserNews
json = jParser.getJSONFromUrl(url);
users = json.getJSONArray(user_email);
// looping through All UserNews
for (int i = currentIndex; i < itemsPerPage; i++) {
if (itemsPerPage == i) {
// currentIndex--;
break;
} else {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
NewsPromosDTO npDTO = new NewsPromosDTO();
npDTO.setImageURL(c.getString(TAG_PHOTO));
npDTO.setId(c.getInt(TAG_ID));
npDTO.setName(c.getString(TAG_NAME));
npDTO.setDate(c.getString(TAG_DATE));
npDTO.setDescription(c.getString(TAG_DESC));
npList.add(npDTO);
currentIndex++;
}
}
} catch (JSONException e) {
e.printStackTrace();
return null;
} finally {
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) { //
// progressDialog.dismiss();
loadingMore = false;
list();
}
}
public void list() {
// add the footer before adding the adapter, else the footer will not
// load!
View footerView = ((LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.footer, null, false);
newsAdapter = new NewsPromoAdapter(ListNewsPromoActivity.this, npList);
list.addFooterView(footerView);
list.setAdapter(newsAdapter);
}
public Runnable getRunnable() {
Runnable loadMoreListItems = new Runnable() {
#Override
public void run() {
// Set flag so we cant load new items 2 at the same time
loadingMore = true;
// Reset the array that holds the new items
// Simulate a delay, delete this on a production environment!
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
// Get 15 new listitems
JSONParser jParser = new JSONParser();
JSONObject json;
npList = new ArrayList<NewsPromosDTO>();
if (jParser.checkServer(url)) {
try {
// Getting Array of Contacts
json = jParser.getJSONFromUrl(url);
users = json.getJSONArray(user_email);
// looping through All Contacts
// if (itemsPerPage > users.length() - currentIndex) {
// itemsPerPage = users.length();
// }
npList = new ArrayList<NewsPromosDTO>();
System.out.println(users.length() + " Laman ng users");
int counter = 0;
for (int i = currentIndex; i < users.length(); i++) {
if (itemsPerPage == counter) {
break;
} else {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
NewsPromosDTO npDTO = new NewsPromosDTO();
npDTO.setImageURL(c.getString(TAG_PHOTO));
npDTO.setId(c.getInt(TAG_ID));
npDTO.setName(c.getString(TAG_NAME));
npDTO.setDate(c.getString(TAG_DATE));
npDTO.setDescription(c.getString(TAG_DESC));
npList.add(npDTO);
currentIndex++;
}
counter++;
}
} catch (JSONException e) {
e.printStackTrace();
} finally {
}
}
// Done! now continue on the UI thread
runOnUiThread(returnRes);
}
};
return loadMoreListItems;
}
}
Below is my code which displays data in listview which is parses from json.
I want to start new activity when the user clicks on any item in the list.
I followed this url http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ and this is the json file http://api.androidhive.info/contacts/
How to start a new activity when a user clicks on any item in listview and pass the remaining json values as parameters?
Now my listview shows only names but i want to pass the remaining items, such as email, gender & mobile to the other activity.
"id": "c200",
"name": "Ravi Tamada",
"email": "ravi#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
public class NewsRowAdapter extends ArrayAdapter<Item> {
private Activity activity;
private List<Item> items;
private Item objBean;
private int row;
Context context;
public NewsRowAdapter(Activity act, int resource, List<Item> arrayList) {
super(act, resource, arrayList);
this.activity = act;
this.row = resource;
this.items = arrayList;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(row, null);
holder = new ViewHolder();
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
if ((items == null) || ((position + 1) > items.size()))
return view;
objBean = items.get(position);
holder.tvName = (TextView) view.findViewById(R.id.txtText);
if (holder.tvName != null && null != objBean.getName()
&& objBean.getName().trim().length() > 0) {
holder.tvName.setText(Html.fromHtml(objBean.getName()));
Intent intent=new Intent(context,TodayLunch.class);
intent.putExtra("name", Html.fromHtml(objBean.getName()));
context.startService(intent);
}
return view;
}
public class ViewHolder {
public TextView tvName, tvCity, tvBDate, tvGender, tvAge;
}
}
package com.schoollunchapp;
public class SeletecDayofweek extends Activity implements OnItemClickListener {
private static final String rssFeed = "http://192.168.2.100/jsonparsing.txt";
private static final String ARRAY_NAME = "student";
private static final String ID = "id";
private static final String NAME = "name";
private static final String CITY = "dish";
private static final String GENDER = "Gender";
private static final String AGE = "age";
private static final String BIRTH_DATE = "birthdate";
ListView listMainMenu;
List<Item> arrayOfList;
//MainMenuAdapter mma;
NewsRowAdapter objAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.selectdayofweek);
listMainMenu = (ListView) findViewById(R.id.listMainMenu2);
listMainMenu.setOnItemClickListener(this);
arrayOfList = new ArrayList<Item>();
if (URLUtils.isNetworkAvailable(SeletecDayofweek.this)) {
new MyTask().execute(rssFeed);
} else {
showToast("No Network Connection!!!");
}
}
// My AsyncTask start...
class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SeletecDayofweek.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
return URLUtils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
if (null == result || result.length() == 0) {
showToast("No data found from web!!!");
SeletecDayofweek.this.finish();
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray =
mainJson.getJSONArray(ARRAY_NAME);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject objJson =
jsonArray.getJSONObject(i);
Item objItem = new Item();
objItem.setId(objJson.getInt(ID));
objItem.setName(objJson.getString(NAME));
objItem.setCity(objJson.getString(CITY));
objItem.setGender(objJson.getString(GENDER));
objItem.setAge(objJson.getInt(AGE));
objItem.setBirthdate(objJson.getString(BIRTH_DATE));
arrayOfList.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
setAdapterToListview();
}
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// showDeleteDialog(position);
}
public void setAdapterToListview() {
objAdapter = new NewsRowAdapter(SeletecDayofweek.this,
R.layout.main_menu_item,
arrayOfList);
listMainMenu.setAdapter(objAdapter);
}
public void showToast(String msg) {
Toast.makeText(SeletecDayofweek.this, msg, Toast.LENGTH_LONG).show();
}
}
create array list like this
public ArrayList<String> Id = new ArrayList<String>();
public ArrayList<String> Name = new ArrayList<String>();
public ArrayList<String> Gender= new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject objJson = jsonArray.getJSONObject(i);
// here you can get id,name,city...
Id.add(objJson.getInt("id"));
Name.add(objJson.getString("name"));
Gender.add(objJson.getString("Gender"));
//You need to use this code in the class where you have the view ,
// list item click
List_View.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Intent i = new Intent(this, abc.class);
// here arg2 is argument of onitemclick method
// this will pick the same item from array list that is clicked on list view
i.putExtra("key_name" , Id.get(arg2));
i.putExtra("key_name" , Name.get(arg2));
i.putExtra("key_name" , Gender.get(arg2));
startActivity(i);
}
});
can see this also
http://www.ezzylearning.com/tutorial.aspx?tid=1351248
and
http://www.bogotobogo.com/Android/android6ListViewSpinnerGridViewGallery.php
You start an activty with startActivity(intent);
You set the OnClickListner on your ListView which is not included in your code so Im implying:
OnItemClickListener listener = new OnItemClickListener (){
#Override
onItemClick(AdapterView<?> parent, View view, int position, long id){
String name = ((TextView) view.findViewById(R.id.txtText)).getText();
Intent intent = new Intent(context,WhatEverYouWant.class);
intent.putExtra("name",name);
startActivity(intent);
}
}
ListView listView = getView().findViewById(R.id.listview);
listView.setOnItemClickListener (listener);
I thing you shold put objJson.getString(NAME); after onItemClick...... to take the clicked item string name not other item