I am writing an app that displays a grid of images stored on a local database using GridView. I implemented the deleteSelectedImage method triggered by a button which deletes a given image of the grid in the database. The deletion works, but I cannot get my GridView to refresh by itself... If I close the activity and then open it again, the changes are visible.
Here's my code :
The activity :
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
public class GalleryShowActivity extends AppCompatActivity {
private final String DEBUG_TAG = "GalleryShowActivity";
private DatabaseHandler db;
private Cursor c;
private ImageAdapter mBaseAdapter;
private TextView selectedImageText;
private GridView mGridView;
// currently selected position in the grid
private int mSelectedPos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery_show);
db = new DatabaseHandler(this);
c = db.getCursorOnAllImages(this);
mBaseAdapter = new ImageAdapter(this, c, db);
mSelectedPos = -1;
selectedImageText = (TextView) findViewById(R.id.selectedImageText);
selectedImageText.setText("Selected image : NONE");
mGridView = (GridView) findViewById(R.id.gridview);
mGridView.setAdapter(mBaseAdapter);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Log.d(DEBUG_TAG, "IMAGE CLICKED");
// click selects an image (can be changed later)
mSelectedPos = position;
selectedImageText.setText("Selected image : " + (position + 1));
}
});
}
public void deleteSelectedImage(View view) {
boolean exists = c.moveToPosition(mSelectedPos);
if (exists) {
boolean success = db.deletePointedPicture(c, this);
if (success) {
Log.d(DEBUG_TAG, "DELETE SUCCESS");
mBaseAdapter.notifyDataSetChanged();
// display a success message...
}
} else {
// display an error...
}
}
}
And here is the code for the ImageAdapter class :
package ch.epfl.sweng.project;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
class ImageAdapter extends BaseAdapter {
private Context mContext;
private Cursor mCursor;
private DatabaseHandler mHandler;
ImageAdapter(Context context, Cursor cursor, DatabaseHandler handler) {
mContext = context;
mCursor = cursor;
mHandler = handler;
}
#Override
public int getCount() {
return mCursor.getCount();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int rowHeight = 200;
int rowWidth = 300;
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(rowWidth, rowHeight));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
Bitmap bm = mHandler.getImageByIndex(mCursor, position);
imageView.setImageBitmap(bm);
imageView.setVisibility(View.VISIBLE);
return imageView;
}
}
I also tried this :
mBaseAdapter = new ImageAdapter(this, c, db);
mGridView.setAdapter(mBaseAdapter);
Instead of :
mBaseAdapter.notifyDataSetChanged();
But it did not work.
You are implementing it wrong. Even after deletion data in cursor will be same. Data in cursor is only updated when onCreate() is again called. Either update the cursor on deleteSelectedImage method after deleting the data and then call notifyDataSetChanged or try to pass list instead of cursor in constructor and while deleting, delete data from list as well as database and then call notifyDataSetChanged.
Hello I am newbie to android and working on a list-view demo,I recently found a weird behavior of list-view when i scroll it down it forcefully comes upside,Can anybody tell me what should be the reason behind this behavior.I am posting my code here.
activity
package one.tusk.stush.fragments;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.company.stush.R;
import java.util.List;
import one.tusk.stush.SearchPostActivity;
import one.tusk.stush.adapters.TimelineAdapter;
import one.tusk.stush.connect.Post;
import one.tusk.stush.loaders.SearchPostsLoader;
import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;
public class SearchPostsFragment extends BaseFragment implements LoaderManager.LoaderCallbacks<List<Post>>, OnRefreshListener, OnScrollListener {
public static android.widget.PopupMenu popupMenu;
private int index = -1;
private int top = 0;
TimelineAdapter mTimelineAdapter;
SearchPostsLoader mTimelineLoader;
PullToRefreshLayout mPullToRefreshLayout;
ListView mListViewTimeline;
ProgressBar mProgressBarLoading;
TextView mTextViewNoItems;
ImageView im;
Menu mm;
int total;
int lastPosition;
int lastTop;
String search;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
search = getArguments().getString("search");
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_timeline_other, container, false);
setHasOptionsMenu(false);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
public void onResume () {
super.onResume();
getActivity().invalidateOptionsMenu();
mListViewTimeline.setSelectionFromTop(
lastPosition,
lastTop
);
// if(index!=-1){
// mListViewTimeline.setSelectionFromTop(index, top);
// }
setHasOptionsMenu(false);
}
#Override
public void onStop() {
super.onStop();
lastPosition = mListViewTimeline.getFirstVisiblePosition();
View v = mListViewTimeline.getChildAt(0);
lastTop = (v == null) ? 0 : v.getTop();
// lastPosition = mListViewTimeline.getSelectedItemPosition();
// int lastPositionInGroup = lastPosition - mListViewTimeline.getFirstVisiblePosition();
// lastTop = mListViewTimeline.getChildAt( lastPositionInGroup ).getTop();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
getActivity().getMenuInflater().inflate(R.menu.search_post, menu);
//MenuItem refreshItem = menu.findItem(R.id.action_edit);
//refreshItem.setVisible(true);
//inflater.inflate(R.menu.fragment_profile_menu, menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.search22) {
// Log.d("MyApp", "action bar clicked");
Intent intent = new Intent(getActivity(), SearchPostActivity.class);
intent.putExtra("View_mode", true);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
total = 0;
mPullToRefreshLayout = (PullToRefreshLayout) getActivity().findViewById(R.id.ptr_layout);
ActionBarPullToRefresh.from(getActivity()).allChildrenArePullable().listener(this).setup(mPullToRefreshLayout);
mProgressBarLoading = (ProgressBar) getActivity().findViewById(R.id.progressBarLoading);
mTextViewNoItems = (TextView) getActivity().findViewById(R.id.textViewNoItems);
mTimelineAdapter = new TimelineAdapter(getActivity());
mListViewTimeline = (ListView) getActivity().findViewById(R.id.listViewTimeline);
mListViewTimeline.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
mListViewTimeline.setEmptyView(mProgressBarLoading);
mListViewTimeline.setAdapter(mTimelineAdapter);
mListViewTimeline.setOnScrollListener(this);
// mListViewTimeline.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
mListViewTimeline.setVerticalScrollBarEnabled(false);
getLoaderManager().initLoader(0, null, this);
}
#Override
public Loader<List<Post>> onCreateLoader(int id, Bundle args) {
mTimelineLoader = new SearchPostsLoader(getActivity(), mListViewTimeline, search);
setHasOptionsMenu(false);
return mTimelineLoader;
}
#Override
public void onLoadFinished(Loader<List<Post>> arg0, List<Post> data) {
mTimelineAdapter.setData(data);
mTimelineAdapter.notifyDataSetChanged();
mPullToRefreshLayout.setRefreshComplete();
mTextViewNoItems.setVisibility(View.VISIBLE);
mProgressBarLoading.setVisibility(View.INVISIBLE);
mListViewTimeline.setEmptyView(mTextViewNoItems);
}
#Override
public void onLoaderReset(Loader<List<Post>> arg0) {
mTimelineAdapter.setData(null);
setHasOptionsMenu(false);
}
#Override
public void onRefreshStarted(View view) {
getLoaderManager().destroyLoader(0);
getLoaderManager().initLoader(0, null, this);
mTextViewNoItems.setVisibility(View.INVISIBLE);
mProgressBarLoading.setVisibility(View.VISIBLE);
mListViewTimeline.setEmptyView(mProgressBarLoading);
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount >= totalItemCount && visibleItemCount != 0) {
if (mTimelineLoader.loadMore() && !mTimelineLoader.loading()) {
total = totalItemCount - 1;
lastPosition = view.getFirstVisiblePosition();
View v = view.getChildAt(0);
lastTop = (v == null) ? 0 : v.getTop();
mTimelineLoader.onContentChanged();
}
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
public void searchPost(String query)
{
search = query;
lastPosition = 0;
lastTop = 0;
mTimelineAdapter.clear();
// mTimelineLoader.loadInBackground();
Log.d("12","UPDATE");
getLoaderManager().restartLoader(0, null, this);
}
}
Adapter
package one.tusk.stush.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import com.company.stush.R;
import java.util.List;
import one.tusk.stush.connect.Post;
import one.tusk.stush.views.PostListItem;
public class TimelineAdapter extends ArrayAdapter<Post> {
private final LayoutInflater mInflater;
public TimelineAdapter(Context context) {
super(context, R.layout.list_item_post);
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setData(List<Post> data) {
setNotifyOnChange(true);
clear();
if (data != null) {
addAll(data);
notifyDataSetChanged();
}
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Post post = getItem(position);
PostListItem view;
if (convertView == null) {
view = (PostListItem) mInflater.inflate(R.layout.list_item_post, parent, false);
} else {
view = (PostListItem) convertView;
}
view.setPost(post);
notifyDataSetChanged();
return view;
}
}
You can try this,
Change your code
if(results.size() > 0){
SearchAdapter searchAdapter = new SearchAdapter(SearchActivity.this);
searchAdapter.setData(results);
mListViewSearchUsers.setAdapter(searchAdapter);
textNotFound.setVisibility(View.GONE);
}else {
textNotFound.setVisibility(View.VISIBLE);
textNotFound.setText("No users found");
}
to
if(results.size() > 0){
SearchAdapter searchAdapter = new SearchAdapter(SearchActivity.this);
if (searchAdapter== null) {
searchAdapter.setData(results);
mListViewSearchUsers.setAdapter(searchAdapter);
} else {
searchAdapter.setData(results);
mListViewSearchUsers.notifyDatasetChange();
}
textNotFound.setVisibility(View.GONE);
}else {
textNotFound.setVisibility(View.VISIBLE);
textNotFound.setText("No users found");
}
Change some code in adapter (comment some code)
public void setData(List<User> data) {
// clear();
if (data != null) {
addAll(data);
// notifyDataSetChanged();
}
}
Update:(problem resolved by comments this line)
mListViewTimeline.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
I hope this will help you.
I got a source code about GridView.
But, I confused why some code were error.
These are the code. I got error on OnClick Method in MainActivity. Is here anyone help me? Thanks
public void onItemClick(AdapterView <? > AdapterView, View View, int Int, long Long) {
AdapterView = ((ImageItem) imageItems.get(Int)).getTitle();
toDetail(Int, AdapterView);
}
});
I want to each item that when it clicked shown the detailed image and text. I also get code like this but when I clicked "GingerBread" item, it goes to first item ("Astro")
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
ImageItem item = (ImageItem) parent.getItemAtPosition(position);
//Create intent
Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
// intent.putExtra("android.intent.extra.TEXT", Integer.parseInt(getIntent().getStringExtra("android.intent.extra.TEXT")));
intent.putExtra("title", item.getTitle());
//Start details activity
startActivity(intent);
overridePendingTransition(R.anim.home_detail_entry, R.anim.home_detail_exit);
}
});
MainActivity.java
package com.acer.gridview;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends Activity {
public static String[] bitmapName = {
"Astro", "Bender", "Cupcake", "Donut", "Eclair",
"Froyo", "Gingerbread", "HoneyComb"
};
public static int[] bitmapId = {
R.drawable.Astro, R.drawable.Bender, R.drawable.Cupcake, R.drawable.Eclair,
R.drawable.Froyo, R.drawable.Gingerbread, R.drawable.HoneyComb
};
private GridViewAdapter gridAdapter;
private GridView gridView;
ArrayList < ImageItem > imageItems;
private ArrayList < ImageItem > getData() {
imageItems = new ArrayList();
BitmapFactory.Options localOptions = new BitmapFactory.Options();
localOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
int i = 0;
for (;;) {
if (i > 7) {
return imageItems;
}
Bitmap localBitmap = BitmapFactory.decodeResource(getResources(), bitmapId[i], localOptions);
imageItems.add(new ImageItem(localBitmap, bitmapName[i]));
i += 1;
}
}
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_grid);
gridView = (GridView) findViewById(R.id.gridView);
gridAdapter = new GridViewAdapter(this, R.layout.row_grid, getData());
gridView.setAdapter(gridAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView <? > AdapterView, View View, int Int, long Long) {
////////////This code shown error///////////////////
AdapterView = ((ImageItem) imageItems.get(Int)).getTitle();
toDetail(Int, AdapterView);
////////////This code shown error///////////////////
}
});
}
public void toDetail(int Int, String String) {
Intent localIntent = new Intent(this, DetailActivity.class);
localIntent.putExtra("android.intent.extra.TEXT", Integer.toString(Int));
localIntent.putExtra("title", String);
startActivity(localIntent);
}
/**
* A placeholder fragment containing a simple view.
*/
private boolean ActionBar(final Intent aIntent) {
try {
startActivity(aIntent);
return true;
} catch (ActivityNotFoundException e) {
return false;
}
}
public void showDialog() {
LayoutInflater inflater = getLayoutInflater();
View localView = inflater.inflate(R.layout.help_dialog, null);
((ImageView) localView.findViewById(R.id.imageView1)).setImageResource(R.drawable.makhrojulhuruf);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(localView);
builder.show();
}
#
Override
public boolean onCreateOptionsMenu(Menu menu) {}
#
Override
public boolean onOptionsItemSelected(MenuItem item) {
}
}
GridViewAdapter.java
package com.acer.gridview;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Acer on 08/02/2016.
*/
public class GridViewAdapter extends ArrayAdapter<ImageItem> {
private Context context;
private int layoutResourceId;
private ArrayList<ImageItem> data = new ArrayList();
public GridViewAdapter(Context context, int layoutResourceId, ArrayList<ImageItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.imageTitle = (TextView) row.findViewById(R.id.text);
holder.image = (ImageView) row.findViewById(R.id.image);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
ImageItem item = (ImageItem) data.get(position);
holder.imageTitle.setText(item.getTitle());
holder.image.setImageBitmap(item.getImage());
return row;
}
static class ViewHolder {
TextView imageTitle;
ImageView image;
}
}
ImageItem.java
package com.acer.gridview;
import android.graphics.Bitmap;
/**
* Created by Acer on 08/02/2016.
*/
public class ImageItem {
private Bitmap image;
private String title;
public ImageItem(Bitmap Bitmap, String String)
{
setImage(Bitmap);
setTitle(String);
}
public Bitmap getImage()
{
return this.image;
}
public String getTitle()
{
return this.title;
}
public void setImage(Bitmap Bitmap)
{
this.image = Bitmap;
}
public void setTitle(String String)
{
this.title = String;
}
}
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);
}
}
}
here I have a String array of rootCategoryID and a String categoryID.
On my custom ListView I want to pass different IDs for each of the rows.
But I can't make it work! Here's my code:
package ir.zabardast.onlinemarket;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class Main extends ListActivity {
String[] rootCategoryName = new String[6];
String[] rootCategoryImage = new String[6];
String[] rootCategoryID = new String[6];
int categoryCount;
String categoryID = "0";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(true){
setContentView(R.layout.activity_main);
HandleXML hxml = new HandleXML();
String url = "http://karakaal.com/market/category.xml";
String object = "category";
hxml.fetchXML(url, object);
while(hxml.parsingComplete);
categoryCount = hxml.getCategories().size();
for (int i = 0; i < categoryCount; i++) {
if(hxml.getCategories().get(i).getParentId() == 0){
rootCategoryName[i] = hxml.getCategories().get(i).getName();
}
}
for (int i = 0; i < categoryCount; i++) {
if(hxml.getCategories().get(i).getParentId() == 0){
rootCategoryImage[i] = hxml.getCategories().get(i).getImage();
}
}
for (int i = 0; i < categoryCount; i++) {
if(hxml.getCategories().get(i).getParentId() == 0){
rootCategoryImage[i] = hxml.getCategories().get(i).getId();
}
}
setListAdapter(new MyAdapter(this,
android.R.layout.simple_list_item_1,
R.id.listName,
rootCategoryName));
ListView listView = getListView();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View view, int i, long l) {
Intent intent = new Intent(Main.this, CategoryList.class);
intent.putExtra("categoryID", categoryID);
startActivity(intent);
}
});
} else if (!checkWifi()) {
setContentView(R.layout.wifi_check);
}
}
private class MyAdapter extends ArrayAdapter<String>{
public MyAdapter(Context context, int resource, int textViewResourceId,
String[] rootCategoryName) {
super(context, resource, textViewResourceId, rootCategoryName);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list, parent, false);
String[] products = rootCategoryName;
ImageView iv = (ImageView) row.findViewById(R.id.listImage);
TextView tv = (TextView) row.findViewById(R.id.listName);
tv.setText(products[position]);
int loader = R.drawable.ic_launcher;
ImageLoader imgLoader = new ImageLoader(getApplicationContext());
String baseURL = "http://karakaal.com/market/";
imgLoader.DisplayImage(baseURL + rootCategoryImage[position], loader, iv);
categoryID = rootCategoryID[position];
return row;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean checkWifi()
{
ConnectivityManager conman = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
boolean wifi = conman.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
if (wifi)
return true;
else
return false;
}
}
As you can see I use a variable to set categoryID in my private class
I want to pass rootCategoryID of each row by an Intent to the next activity when each row is clicked
you can get categoryID by position of ListView clicked
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View view, int i, long l) {
Intent intent = new Intent(Main.this, CategoryList.class);
intent.putExtra("categoryID", rootCategoryID[i]);//here CategoryId
startActivity(intent);
}
});