I'm passing id form FirstFragment to SecondFragment. I need that I'd to send POST request to web service to retrieve JSON, which I need to create content of SecondFragment. SecondFragment is ListView with custom layout. I'm adding that layout with my custom adapter class (MyAdapter). For JSON I also have AsyncTask class (GetCategoryTas) The problem is that the SecondFragment is created before service give me result back. So content is always blank. How can I fix this.
FirstFragment:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Bundle bundle = new Bundle();
bundle.putString("id", menuList.get(position).getAlias());
categoryPage = new FragmentCategoryPage();
categoryPage.setArguments(bundle);
transaction = manager.beginTransaction();
transaction.replace(R.id.mainContainer, categoryPage, "CategoryPage");
transaction.addToBackStack("CategoryPage");
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.commit();
}
SecondFragment:
public class FragmentCategoryPage extends Fragment implements OnItemClickListener {
private ListView lvCategory;
private List<NameValuePair> pair;
private ArrayList<ItemCategory> itemCatList = new ArrayList<ItemCategory>();
private ItemCategory itemCat;
private MyAdapter myAdapter;
private Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_category, container, false);
context = getActivity();
String id = getArguments().getString("id");
pair = new ArrayList<NameValuePair>();
pair.add(new BasicNameValuePair("category", id));
new GetCategoryTask().execute();
lvCategory = (ListView) view.findViewById(R.id.lvCategory);
myAdapter = new MyAdapter();
lvCategory.setAdapter(myAdapter);
lvCategory.setOnItemClickListener(this);
return view;
}
// Creating own adapter for categories
class MyAdapter extends BaseAdapter {
#Override
public View getView(final int pos, View convertView, ViewGroup parent) {
View row = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.item_layout_category, parent, false);
} else {
row = convertView;
}
TextView tvCatTitle = (TextView) row.findViewById(R.id.tvCategoryTitle);
TextView tvCatDate = (TextView) row.findViewById(R.id.tvCategoryDate);
ImageView ivCatImage = (ImageView) row.findViewById(R.id.ivCategoryImage);
return row;
}
#Override
public int getCount() { return itemCatList.size(); }
#Override
public Object getItem(int pos) { return null; }
#Override
public long getItemId(int pos) { return 0; }
}
public class GetCategoryTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Variables.URL_CATEGORY);
httpPost.setEntity(new UrlEncodedFormEntity(pair));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String data = EntityUtils.toString(httpEntity);
int status = httpResponse.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_OK) {
JSONArray jArray = new JSONArray(data);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jRealObject = jArray.getJSONObject(i);
itemCat = new ItemCategory();
itemCat.setId(jRealObject.get("id").toString());
itemCat.setTitle(jRealObject.get("title").toString());
itemCat.setImage_name(jRealObject.get("image_name").toString());
itemCatList.add(itemCat);
}
return true;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if(result == false) {
Toast.makeText(context, Variables.ERROR_MESSAGE, Toast.LENGTH_SHORT).show();
}
}
}
}
How can I fix this problem?
You should refresh your adapter in onPostExecute() by calling;
myAdapter.notifyDataSetChanged();
I dont see anywhere in your code that you have connected your listview with the itemCatList. And you should do anything you wanna do with your listview in onPostExecute, not in onCreate, so you could be sure that the list exists in that point as AsyncTask runs on its own thread
in onPostExecute
lv = (ListView) findViewById(R.id.your_list_view_id);
List<String> your_array_list = new ArrayList<String>();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
your_array_list );
lv.setAdapter(arrayAdapter);
Related
I have a listview in Fragment Home and I want when Someone click on list item them new activity will open and data will pass to new activity and set to a text view. But nothing is happening when i click on list item
here is my Complete code of onItemClickListner
public class Home extends Fragment {
ListView listView;
PostAdapter adapter;
TextView userId;
ArrayList<Post> postArrayList;
//private SwipeRefreshLayout swipeRefreshLayout;
DBHandler handler;
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_post, container, false);
listView = (ListView) view.findViewById(R.id.listview);
ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnected()){
new DataFetcherTask().execute();
}else{
Toast.makeText(getActivity(), "Internet Error", Toast.LENGTH_LONG).show();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
userId = (TextView)view.findViewById(R.id.row_userid);
Intent i = new Intent(getActivity(), PostView.class);
i.putExtra("userid", userId.getText().toString());
startActivity(i);
Toast.makeText(getActivity(),"hello",Toast.LENGTH_LONG).show();
}
});
return view;
}
private class DataFetcherTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... args) {
String serverData = null;// String object to store fetched data from server
// Http Request Code start
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://xyz.lt/json.php");
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
serverData = EntityUtils.toString(httpEntity);
Log.d("response", serverData);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Http Request Code end
// Json Parsing Code Start
try {
postArrayList = new ArrayList<Post>();
JSONObject jsonObject = new JSONObject(serverData);
JSONArray jsonArray = jsonObject.getJSONArray("post");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectPOST = jsonArray.getJSONObject(i);
String post_id = jsonObjectPOST.getString("post_id");
String user_id = jsonObjectPOST.getString("user_id");
String user_name = jsonObjectPOST.getString("user_name");
String post_title = jsonObjectPOST.getString("post_title");
String likes = jsonObjectPOST.getString("likes");
String post_cat = jsonObjectPOST.getString("post_cat");
String post_time = jsonObjectPOST.getString("post_time");
Post post = new Post();
post.setPost_id(post_id);
post.setUser_id(user_id);
post.setUser_name(user_name);
post.setPost_title(post_title);
post.setLikes(likes);
post.setPost_cat(post_cat);
post.setPost_time(post_time);
handler.addPost(post);// Inserting into DB
}
} catch (JSONException e) {
e.printStackTrace();
}
//Json Parsing code end
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
ArrayList<Post> postList = handler.getAllPost();
adapter = new PostAdapter(getActivity(), postList);
listView.setAdapter(adapter);
}
}
#Override
public void onResume() {
super.onResume();
new DataFetcherTask().execute();
ArrayList<Post> postList = handler.getAllPost();
adapter = new PostAdapter(getActivity(), postList);
listView.setAdapter(adapter);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new DBHandler(getActivity());
new DataFetcherTask().execute();
}
}
I made an custom list item with images + textview + Image Buttons. I need just post_id then all the data will be fetched from sqlite using that text. Textview is initialized in PostAdapter where data is connected to list view.
after click this intent will open
public class PostView extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_view);
TextView textView = (TextView) findViewById(R.id.textView3);
Intent intent = getIntent();
if (intent!=null) {
String stringData= intent.getStringExtra("userid");
textView.setText(stringData);
}
}
}
now just need to steup click listener on listview which perform his task. Thank you for help in advance.
Use this to send data,
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getActivity(), PostView.class);
TextView userId = (TextView) view.findViewById(R.id.row_userid);
intent.putExtra("row_userid", userId.getText().toString());
startActivity(i);
}
And retrieve it like this,
String row_userid = getIntent().getStringExtra("row_userid");
Send data like this
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getActivity(), PostView.class);
TextView userId = (TextView) view.findViewById(R.id.row_userid);
i.putExtra("userid", userId.getText().toString());
startActivity(i);
}
Get data like this in PostView
Intent intent = getIntent();
if (intent!=null) {
String stringData= intent.getStringExtra("userid");
}
Just add android:focusable="false" in your ImageButton in xml layout file. After that your ListView click listner will work
When you use
userId = (TextView)view.findViewById(R.id.row_userid);
You are using the view inside lister, rather you should be using this.view .
I have created an activity to get and show data to a custom list view.
Now I have changed this to fragment but onItemclick does not work.
SiteNews.java
public class SiteNews extends Fragment implements OnTabChangeListener,
OnPageChangeListener {
private TabHost tabHost;
private ViewPager viewPager;
private FragmentPagerNewsAdapter fragmentPagerNewsAdapter;
int i = 0;
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.tabs_news_layout, container, false);
// put tabhost here:
// ***************************** part 1
// ***************************************************
i++;
// init tabhost
this.initializeTabHost(savedInstanceState);
// init ViewPager
this.initializeViewPager();
// ***************************** part 1
// ***************************************************
return v;
}
private void initializeViewPager() {
List<Fragment> fragmentsnews = new Vector<Fragment>();
fragmentsnews.add(new FragmentAllNews());
fragmentsnews.add(new FragmentUnreadNews());
this.fragmentPagerNewsAdapter = new FragmentPagerNewsAdapter(
getChildFragmentManager(), fragmentsnews);
this.viewPager = (ViewPager) v.findViewById(R.id.viewPagernews);
this.viewPager.setAdapter(this.fragmentPagerNewsAdapter);
this.viewPager.setOnPageChangeListener(this);
}
// fake content for tabhost
class FakeContent implements TabContentFactory {
private final Context mContext;
public FakeContent(Context context) {
mContext = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(mContext);
v.setMinimumHeight(0);
v.setMinimumWidth(0);
return v;
}
}
private void initializeTabHost(Bundle args) {
tabHost = (TabHost) v.findViewById(android.R.id.tabhost);
tabHost.setup();
for (int i = 1; i <= 2; i++) {
TabHost.TabSpec tabSpec;
tabSpec = tabHost.newTabSpec("Tab " + i);
tabSpec.setIndicator("Tab " + i);
tabSpec.setContent(new FakeContent(getActivity()));
tabHost.addTab(tabSpec);
}
tabHost.setOnTabChangedListener(this);
}
#Override
public void onTabChanged(String tabId) {
int pos = this.tabHost.getCurrentTab();
this.viewPager.setCurrentItem(pos);
HorizontalScrollView hScrollView = (HorizontalScrollView) v
.findViewById(R.id.hScrollViewnews);
View tabView = tabHost.getCurrentTabView();
int scrollPos = tabView.getLeft()
- (hScrollView.getWidth() - tabView.getWidth()) / 2;
hScrollView.smoothScrollTo(scrollPos, 0);
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
this.tabHost.setCurrentTab(position);
}
}
FragmentAllnews.java
public class FragmentAllNews extends Fragment implements View.OnClickListener {
ViewGroup v;
ListView list;
CustomAdapterAllNews adapter;
JSONObject json_data;
JSONArray jArray;
NewsGetData newsGetData;
ArrayList<String> id, title_news, text_news, cat_id, status;
String data, url, msg, check, readnumber, ACTION_SCAN, contents;
ArrayList<News> newsha;
News n;
int sizearray;
Resources res;
ArrayList<News> items;
News ne;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = (ViewGroup) inflater.inflate(R.layout.tabfragmentallnews,
container, false);
list = (ListView) v.findViewById(R.id.listallnews);
res = getResources();
createarray();
/* items = new ArrayList<News>();
for (int k = 0; k < 25; k++) {
ne = new News();
ne.setTitle_news("title_news " + String.valueOf(k));
ne.setText_news("text_news " + String.valueOf(k));
ne.setCat_id(k);
ne.setStatus(k);
items.add(ne);
}*/
ReadData task1 = new ReadData();
task1.execute(new String[] { "url address" });
return v;
}
private void createarray() {
id = new ArrayList<String>();
title_news = new ArrayList<String>();
text_news = new ArrayList<String>();
cat_id = new ArrayList<String>();
status = new ArrayList<String>();
id.clear();
title_news.clear();
text_news.clear();
cat_id.clear();
status.clear();
}
private class ReadData extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPreExecute() {
dialog.setMessage("Reading Data...");
dialog.show();
}
String text = "";
ArrayList<String> list1;
#Override
protected Boolean doInBackground(String... urls) {
url = "php url address";
InputStream is1;
for (String url1 : urls) {
// Read from web to InputStream
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// HttpPost post = new HttpPost(url1);
HttpResponse response = client.execute(post);
is1 = response.getEntity().getContent();
} catch (ClientProtocolException e) {
Toast.makeText(getActivity(), e.toString(),
Toast.LENGTH_LONG).show();
return false;
} catch (IOException e) {
Toast.makeText(getActivity(), e.toString(),
Toast.LENGTH_LONG).show();
return false;
}
// end of Read from web to InputStream
// Convert from InputStream to String Text
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(is1,
"iso-8859-1"), 8);
String line = null;
while ((line = reader.readLine()) != null) {
text += line + "\n";
}
is1.close();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// end of Convert from InputStream to String Text
// Convert from Text to JSON and add to ArrayList list1
list1 = new ArrayList<String>();
try {
JSONArray jArray = new JSONArray(text);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonData = jArray.getJSONObject(i);
list1.add(jsonData.getString("title_news") + " - "
+ jsonData.getString("text_news"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// end of Convert from Text to JSON and add to ArrayList list1
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
if (result == true) {
// add list1 to ArrayAdapter
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(
getActivity(), android.R.layout.simple_list_item_1,
list1);
// set adapter into listStudent
// list.setAdapter(adapter1);
Toast.makeText(getActivity(), text, Toast.LENGTH_LONG).show();
data = text;
newsha = parseJSON3(data);
adddata(newsha);
} else {
Toast.makeText(getActivity(), "Error", Toast.LENGTH_LONG)
.show();
}
dialog.dismiss();
}
}
/*
* #Override public void onItemClick(AdapterView<?> parent, View
* clickedView, int pos, long id) { TextView tv1 = (TextView)clickedView;
* int commaIndex = tv1.getText().toString().indexOf(","); String st_id =
* tv1.getText().toString().substring(0, commaIndex);
*
* Intent in = new Intent(this, EditDataActivity.class);
* in.putExtra("st_id", st_id); startActivity(in);
*
* }
*/
public void onItemClick(int mPosition) {
try {
News tempValues = (News) newsha.get(mPosition);
Toast.makeText(getActivity(), tempValues.getText_news(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// Toast.makeText(CustomListView,"no", Toast.LENGTH_LONG).show();
}
}
public ArrayList<News> parseJSON3(String result) {
ArrayList<News> userha = new ArrayList<News>();
try {
jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
n = new News();
n.setId(json_data.getInt("id"));
id.add(String.valueOf(json_data.getInt("id")));
n.setTitle_news(json_data.getString("title_news"));
title_news.add(json_data.getString("title_news"));
n.setText_news(json_data.getString("text_news"));
text_news.add(json_data.getString("text_news"));
n.setCat_id(json_data.getInt("cat_id"));
cat_id.add(String.valueOf(json_data.getInt("cat_id")));
n.setStatus(json_data.getInt("status"));
status.add(String.valueOf(json_data.getInt("status")));
userha.add(n);
}
sizearray = text_news.size();
if (sizearray <= 0) {
Toast.makeText(getActivity(), "get data error",
Toast.LENGTH_LONG).show();
} else {
}
} catch (JSONException e) {
// toast(9);
}
return userha;
}
private void adddata(ArrayList<News> newsha2) {
adapter = new CustomAdapterAllNews(getActivity(), newsha2, newsha2, res);
list.setAdapter(adapter);
}
#Override
public void onClick(View v) {
}
}
CustomAdapterAllNews.java
public class CustomAdapterAllNews extends BaseAdapter implements OnClickListener {
/*********** Declare Used Variables *********/
private Activity activitynews;
private ArrayList datanews;
private static LayoutInflater inflaternews=null;
public Resources resnews;
News tempValuesnews=null;
int i=0;
TableLayout tableLayout1news;
private List<News> worldpopulationlistnews = null;
private ArrayList<News> arraylistnews;
/************* CustomAdapter Constructor *****************/
public CustomAdapterAllNews(Activity a, ArrayList d, List<News> worldpopulationlist, Resources resLocal) {
/********** Take passed values **********/
activitynews = a;
datanews=d;
resnews = resLocal;
this.arraylistnews = new ArrayList<News>();
this.worldpopulationlistnews = worldpopulationlist;
this.arraylistnews.addAll(worldpopulationlist);
/*********** Layout inflator to call external xml layout () **********************/
inflaternews = (LayoutInflater)activitynews.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if(datanews.size()<=0)
return 1;
return datanews.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder to contain inflated xml file elements ***********/
public static class ViewHolder{
public TextView text;
public TextView text1;
public ImageView image;
}
/*********** Depends upon data size called for each row , Create each ListView row ***********/
#SuppressLint("InflateParams")
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
/********** Inflate tabitem.xml file for each row ( Defined below ) ************/
vi = inflaternews.inflate(R.layout.list_news, null);
/******** View Holder Object to contain tabitem.xml file elements ************/
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.textlistnews);
holder.text1=(TextView)vi.findViewById(R.id.text1listnews);
holder.image=(ImageView)vi.findViewById(R.id.imagelistnews);
/************ Set holder with LayoutInflater ************/
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
if(datanews.size()<=0)
{
holder.text.setText("No Data");
holder.text1.setText("نتیجه یافت نشد");
holder.image.setImageResource(resnews.getIdentifier("com.iranvizhe:drawable/"+"image00",null,null));
}
else
{
/***** Get each Model object from Arraylist ********/
tempValuesnews=null;
tempValuesnews = (News) datanews.get(position);
/************ Set Model values in Holder elements ***********/
holder.text.setText(tempValuesnews.getTitle_news());
holder.text1.setText(tempValuesnews.getText_news());
holder.image.setImageResource(resnews.getIdentifier("com.iranvizhe:drawable/image0",null,null));
/******** Set Item Click Listner for LayoutInflater for each row ***********/
vi.setOnClickListener(new OnItemClickListener(position));
}
return vi;
}
#Override
public void onClick(View v) {
Log.v("CustomAdapter", "=====Row button clicked");
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
// FragmentAllNews sct = (FragmentAllNews)activitynews;
// Tab1Fragment sct = (Tab1Fragment)activity;
// sct.onItemClick(mPosition);
}
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlistnews.clear();
if (charText.length() == 0) {
worldpopulationlistnews.addAll(arraylistnews);
}
else
{
for (News wp : arraylistnews)
{
if (wp.getTitle_news().toLowerCase(Locale.getDefault()).contains(charText)
| wp.getText_news().toLowerCase(Locale.getDefault()).contains(charText))
{
worldpopulationlistnews.add(wp);
}
}
}
notifyDataSetChanged();
}
}
When I put this code:
// FragmentAllNews sct = (FragmentAllNews)activitynews;
// Tab1Fragment sct = (Tab1Fragment)activity;
// sct.onItemClick(mPosition);
on click does not work for me and I need on click in list view.
Don't use v.setOnclicklistener() in adapter, better use in fragment only as below
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
try {
News tempValues = (News) newsha.get(mPosition);
Toast.makeText(getActivity(), tempValues.getText_news(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// Toast.makeText(CustomListView,"no", Toast.LENGTH_LONG).show();
}
}
});
In my application i used custom list view adapter. In the list view item i added another layout. because in my service one order have any number of order items. For showing the order items i added the order item layout below to custom list view item.it is working fine. but when scroll the list view the data is changed.
adapter class:
public class PreviousDataAdapter extends BaseAdapter {
ArrayList<PreviousOrderData> bpData;
private ArrayList<PreviousOrderData> arraylist;
ArrayList<OrderItemData> opData;
private ArrayList<OrderItemData> arraylist1;
private Activity activity;
private LayoutInflater inflater;
String g_orderid;
DatabaseHandler db;
SharedPreferences m_sharedPreference;
SharedPreferences.Editor m_editor;
ArrayList<String> circless = new ArrayList<String>();
public PreviousDataAdapter(Activity activity, ArrayList<PreviousOrderData> bpData,ArrayList<OrderItemData> opdata) {
// TODO Auto-generated constructor stub
this.activity = activity;
this.bpData = bpData;
this.opData=opdata;//k?
// this.opData=bpData.get()//opdata;
inflater = LayoutInflater.from(activity);
db = new DatabaseHandler(activity);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return bpData.size();
}
#Override
public Object getItem(int location) {
// TODO Auto-generated method stub
return bpData.get(location);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private int lastPosition = -1;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Typeface custom_regular = Typeface.createFromAsset(activity.getAssets(),
"fonts/OpenSans-Regular.ttf");
m_sharedPreference = activity.getSharedPreferences("save_details", activity.MODE_PRIVATE);
m_editor = m_sharedPreference.edit();
//String[] months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
//final View view;
final ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.previousorders_listitem, null);
viewHolder.date = (TextView) convertView.findViewById(R.id.date);
viewHolder.orderid = (TextView) convertView.findViewById(R.id.orderid);
viewHolder.amount = (TextView) convertView.findViewById(R.id.amount);
viewHolder.status = (TextView) convertView.findViewById(R.id.status);
viewHolder.ordersinfo=(LinearLayout)convertView.findViewById(R.id.previousorders);
viewHolder.date .setTypeface(custom_regular);
viewHolder.orderid.setTypeface(custom_regular);
viewHolder.amount.setTypeface(custom_regular);
viewHolder.status.setTypeface(custom_regular);
viewHolder.ll_individuvalitem = (LinearLayout) convertView.findViewById(R.id.ll_individuvalitem);
//convertView = view;
convertView.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.date.setText(bpData.get(position).getDate());
viewHolder.orderid.setText(bpData.get(position).getOrdername());
viewHolder. amount.setText("Rs."+bpData.get(position).getAmount());
viewHolder. status.setText(bpData.get(position).getStatus());
viewHolder.ordersinfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
g_orderid =bpData.get(position).getOrderid();
Log.v("TAG_ORDERIDADAPTER",""+g_orderid);
new GetReorder().execute(WebUrl.RechargeServiceURL+"APP_Reorder");
}
});
//Log.d("size:",opData.size()+"");
if( opData!= null && opData.size() >0){opData.clear();}
opData = bpData.get(position).getOrderItemDataList();//
if(opData.size()>0){
viewHolder.ll_individuvalitem.removeAllViews();
for (int i = 0; i < opData.size(); i++){
// Log.v("TAG Number loop",""+opData.get(i).getNumber());
View itemview = inflater.inflate(R.layout.previousorders_list_single_items, null);
TextView Number = (TextView)itemview.findViewById(R.id.Number);
TextView RechargeAmount = (TextView)itemview.findViewById(R.id.RechargeAmount);
TextView Rechargestatus = (TextView)itemview.findViewById(R.id.Rechargestatus);
Number.setTypeface(custom_regular);
RechargeAmount.setTypeface(custom_regular);
Rechargestatus.setTypeface(custom_regular);
Number.setText(opData.get(i).getNumber());
RechargeAmount.setText("Rs."+opData.get(i).getRechargeAmount());
Rechargestatus.setText(opData.get(i).getRechargestatus());
viewHolder.ll_individuvalitem.addView(itemview);
}
}
return convertView;
}
class ViewHolder {
TextView date, tx_month, orderid, amount,status;
LinearLayout ll_individuvalitem,ordersinfo;
}
private class GetReorder extends AsyncTask<String, Void, JSONObject> {
/*String mJourneyDate;
public GetData(String pJourneyDate) {
this.mJourneyDate = pJourneyDate;
}*/
#Override
protected void onPreExecute() {
super.onPreExecute();
// pDialog = ProgressDialog.show(getActivity(), "", "");
}
#Override
protected JSONObject doInBackground(String... params) {
String response;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(4);
nameValuePair.add(new BasicNameValuePair("OrderID", g_orderid));
nameValuePair.add(new BasicNameValuePair("DeviceID", m_sharedPreference.getString("deviceId","")));
nameValuePair.add(new BasicNameValuePair("PlatformID", "3"));
nameValuePair.add(new BasicNameValuePair("UserUniqueID", m_sharedPreference.getString("useruid","")));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse responce = httpclient.execute(httppost);
HttpEntity httpEntity = responce.getEntity();
response = EntityUtils.toString(httpEntity);
Log.d("response is", response);
return new JSONObject(response);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject result) {
String Status;
super.onPostExecute(result);
// Log.v("TAG_RESULT",""+result);
if (result != null) {
try {
Intent intent= new Intent(activity, Payment_Actiivity.class);
intent.putExtra("jsonfrompayment",result.toString());
Log.v("TAG_JSONPAY",""+result.toString());
activity.startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(activity, "something went wrong", Toast.LENGTH_LONG).show();
}
}
}
}
In your adapter class override these two methods
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
Note: For recyclerview just method getItemViewType(int position) will work.
I had the same issue then below link resolved my problem ;
https://stackoverflow.com/a/36738935/3341089
Basically, you should specify your item types then reconfigure your adapter via getItemViewType(int position) and getViewTypeCount() override methods.
If you look into above link, you will get it.
you are using two arrays - "bpData" and "opData" and you only reset if under specific conditions with "opData".
This is a bad design. You need one array - if "opData" is dependent on "bpData" then make it a variable of "bpData".
Or else write something to synchronize the two. Otherwise, you do not know how the display will work.
Still i am populating all JSON data into ListView, but now i want to populate (records into ListView) based on visibility, when user scrolls I want to show progess bar for 5 seconds and then want to populate more records (those will be visible to user) and so on...
I don't want to populate all data into ListView for the first time !
MainActivity.java:
public class MainActivity extends Activity {
ArrayList<Main> arrayList;
MainAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrayList = new ArrayList<Main>();
new JSONAsyncTask().execute("....");
ListView listview = (ListView)findViewById(R.id.list);
adapter = new MainAdapter(getApplicationContext(), R.layout.row, arrayList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), arrayList.get(position).getTitle(), Toast.LENGTH_LONG).show();
}
});
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Main main = new Main();
main.setTitle(object.getString("title"));
Log.v("title:", object.getString("title"));
arrayList.add(main);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
MainAdapter.java:
public class MainAdapter extends BaseAdapter {
ArrayList<Main> arrayList;
LayoutInflater layoutInflater;
int resource;
ViewHolder viewHolder;
public MainAdapter(Context context, int resource, ArrayList<Main> arrayList) {
this.layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.resource = resource;
this.arrayList = arrayList;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View view = convertView;
if (view == null) {
viewHolder = new ViewHolder();
view = layoutInflater.inflate(resource, null);
viewHolder.tvName = (TextView) view.findViewById(R.id.tvName);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.tvName.setText(arrayList.get(position).getTitle());
return view;
}
static class ViewHolder {
public TextView tvName;
}
}
You can try using this library (Android-Infinite-Scroll-Listview)
I've used it before and it's easy to work with.
I currently have a program that can parse a JSONArray and put each item into a listview. But if you add something to the JSONArray the listview doesn't update until you run the app again. So how would I go about being able to update the listview when new items are added to the JSONArray. Here is the code I have that parses the JSONArray:
public class jarray extends Activity {
ArrayList<Actors> actorsList;
ActorAdapter adapter;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jarray);
actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute("http://bisonsoftware.us/hhs/messages.json");
ListView listview = (ListView) findViewById(R.id.list);
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
listview.setAdapter(adapter);
button = (Button)findViewById(R.id.button);
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(jarray.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("messages");
for (int i = 0; i < jarray.length(); i++) {
Actors actor = new Actors();
String message = jarray.getString(i);
actor.setName(message);
//actorsList.add(actor);
adapter.add(actor);
}
return true;
}
//------------------>>
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if (result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
If you need any more of my code or just need some more explanation feel free to ask. Could really use some help on this, thanks.
Here is the ActorAdapter code:
public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
#Override
public void add(Actors object) {
super.add(object);
notifyDataSetChanged();
}
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.tvName = (TextView) v.findViewById(R.id.tvName);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.tvName.setText(actorList.get(position).getName());
return v;
}
static class ViewHolder {
public TextView tvName;
}
}
Instead of adding directly to the ArrayList, try adding it from your adapter.
You need to instantaite your ActorAdapter before running your AsyncTask
sample:
setContentView(R.layout.activity_jarray);
actorsList = new ArrayList<Actors>();
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
ListView listview = (ListView) findViewById(R.id.list);
listview.setAdapter(adapter);
new JSONAsyncTask().execute("http://bisonsoftware.us/hhs/messages.json");
button = (Button)findViewById(R.id.button);
When you add items to the adapter call the add method of the adapter not your arrayList
change this:
actorsList.add(actor);
to:
adapter.add(actor);
Add this in you ActorAdapter adapter:
#Override
public void add(Actors object) {
super.add(object);
notifyDataSetChanged();
}
change you oncreate into this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jarray);
actorsList = new ArrayList<Actors>();
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
ListView listview = (ListView) findViewById(R.id.list);
listview.setAdapter(adapter);
new JSONAsyncTask().execute("http://bisonsoftware.us/hhs/messages.json");
button = (Button)findViewById(R.id.button);
}
The way you update a listview is by remaking the adapter with the updated information, setting the listadapter and then calling NotifyDataSetChanged(). This tells the device to refresh the layout.
ListView listview = (ListView) findViewById(R.id.list);
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
listview.setAdapter(adapter);
adapter.NotifyDataSetChanged();