Listview adapter bugging when refreshing list (loading new details) - android

I have an awards section where I load data from my server.
I'm pulling 8 by 8 awards from server and loading them in my ListView. Awards can be sold and in my adapter I have a checker where if quantity < 1 there will be a bar over Image that will notify user that award is sold.
There is lazy load where user can swipe to load more details by increasing index, so server can determine which 8 awards should he return. 1 for first 8, 2 for second 8 etc.
Problem is when I scroll to first sold award, ListView gets weird and all awards get that sold bar over their images. This is the code from activity:
public class AwardListFragment extends Fragment { int offset = 0;
int size = 8;
private int ID;
private boolean _isAwardsLoaded = false;
private SwipyRefreshLayout swipyRefreshLayout;
private ProgressDialog progressBar;
private ArrayList<Awards> listAwards;
ListView awardlist;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.rewards_section, parent, false);
awardlist = (ListView) rootView.findViewById(R.id.awardlist);
awardlist.setItemsCanFocus(true);
listAwards = new ArrayList<>();
swipyRefreshLayout = (SwipyRefreshLayout) rootView.findViewById(R.id.swipe_section_swipe);
awardlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getActivity(), AwardDetailsScreen.class);
ID = listAwards.get(position).getId();
Bundle bundle = new Bundle();
bundle.putInt("ID", ID);
intent.putExtras(bundle);
startActivity(intent);
}
});
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
}
public void showlist() {
progressBar = new ProgressDialog(getActivity());
progressBar.setMessage("Pls Wait...");
progressBar.show();
final int firstitemposition = 0;
final int currentposition = awardlist.getFirstVisiblePosition();
NetworkSDK.getInstance().getAwards(size, offset, new Callback<List<Awards>>() {
#Override
public void onResponse(Call<List<Awards>> call, Response<List<Awards>> response) {
if (response.code() == 401) {
Intent intent = new Intent(getContext(), MainPreLogin.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
SharedData.getInstance().removeString("token");
} else {
if (response.isSuccess()) {
if (response.body().size() == 0) {
Toast.makeText(getContext(), "All awards loaded", Toast.LENGTH_SHORT).show();
progressBar.setCancelable(false);
progressBar.dismiss();
} else
for (int i = 0; i < response.body().size(); i++)
listAwards.add(response.body().get(i));
AwardsAdapter awardsAdapter = new AwardsAdapter(listAwards);
awardlist.setAdapter(awardsAdapter);
awardsAdapter.notifyDataSetChanged();
awardlist.setSelectionFromTop(currentposition, firstitemposition);
}
progressBar.setCancelable(false);
progressBar.dismiss();
}
}
#Override
public void onFailure(Call<List<Awards>> call, Throwable t) {
Toast.makeText(getContext(), R.string.errorNoconnection, Toast.LENGTH_LONG).show();
progressBar.dismiss();
}
});
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && !_isAwardsLoaded) {
swipyRefreshLayout.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh(SwipyRefreshLayoutDirection direction) {
if (direction == SwipyRefreshLayoutDirection.BOTTOM) {
offset++;
swipyRefreshLayout.setRefreshing(false);
showlist();
}
}
showlist();
});
}
}
}
This is my adapter.
public class AwardsAdapter extends BaseAdapter {
ArrayList<Awards> awards;
public AwardsAdapter(ArrayList<Awards> awards) {
this.awards = awards;
}
public void clearData() {
// clear the data
awards.clear();
}
#Override
public int getCount() {
return awards.size();
}
#Override
public Object getItem(int position) {
return awards.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
Integer identity;
ViewHolder viewHolder = null;
if (convertView == null) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.award_item, parent, false);
viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
} else {
view = convertView;
viewHolder = (ViewHolder) view.getTag();
}
Awards awards = (Awards) getItem(position);
if (awards != null) {
identity = awards.getId();
viewHolder.name.setText(awards.getName().toUpperCase());
viewHolder.price.setText("Money amount: " + awards.getPriceAmount().toString() );
viewHolder.points.setText("Points amount :" + awards.getCreditAmount().toString());
if (awards.getImagePath().isEmpty())
Picasso.with(view.getContext()).load(R.drawable.placeholder).fit().centerCrop().into(viewHolder.picture);
else
Picasso.with(view.getContext()).load(awards.getImagePath()).fit().centerCrop().into(viewHolder.picture);
if (awards.getQuantity()<1)
Picasso.with(view.getContext()).load(R.drawable.sold).into(viewHolder.checker);
else
if (awards.getIsVip())
Picasso.with(view.getContext()).load(R.drawable.vip).into(viewHolder.checker);
}
return view;
}
private class ViewHolder {
TextView name;
TextView price;
TextView points;
ImageView picture;
ImageView checker;
public ViewHolder(View view) {
this.name = (TextView) view.findViewById(R.id.award_name);
this.price = (TextView) view.findViewById(R.id.award_price);
this.picture = (ImageView) view.findViewById(R.id.award_picture);
this.points = (TextView) view.findViewById(R.id.award_points);
this.checker=(ImageView)view.findViewById(R.id.checker);
}
}
}

In your adapter's getView(), you have this piece of code:
if (awards.getQuantity()<1)
Picasso.with(view.getContext()).load(R.drawable.sold).into(viewHolder.checker);
else
if (awards.getIsVip())
Picasso.with(view.getContext()).load(R.drawable.vip).into(viewHolder.checker);
Change it to something like this (it depends on how you want to show/hide your view. As it stands, you're not handling the case where you need to hide it!):
if (awards.getQuantity()<1) {
Picasso.with(view.getContext()).load(R.drawable.sold).into(viewHolder.checker);
}
else {
// hide viewHolder.checker here
}
if (awards.getIsVip()) {
Picasso.with(view.getContext()).load(R.drawable.vip).into(viewHolder.checker);
}
Note: As a general piece of advice, always use curly brackets to avoid such bugs and confusion.

Related

Listview add item one at a time

I have a listview and a button in my main activity and three layout ressource files (right.xml, mid.xml and left.xml [They're relative layout]).
I want to make an arrayList (with strings and drawable (images)) and each time I push the button in main.xml the first content of the arrayList will appear at the bottom of the screen (either left, mid or right --> depend of the order of the arrayList) and when I click again the next item (string or drawable) will appear beneath it, pushing it in an upward motion.
UPDATE
I made a Model and an Adapter
Here is the model
public class ModelC1 {
public String C1Name;
public String C1Text;
public int id;
public boolean isSend;
public ModelC1(String C1Name, String C1Text, int id, boolean isSend){
this.id = id;
this.C1Name = C1Name;
this.C1Text = C1Text;
this.isSend = isSend;
}
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getC1Name() {
return C1Name;
}
public void setC1Name(String C1Name){
this.C1Name = C1Name;
}
public String getC1Text() {
return C1Text;
}
public void setC1Text (String C1Text){
this.C1Text = C1Text ;
}
public boolean isSend() {
return isSend;
}
public void setIsSend(boolean send){
isSend = send;
}
Here is the Adapter
public class AdapterC1 extends BaseAdapter {
private List<ModelC1> listChat;
private LayoutInflater inflater;
private Context context;
public AdapterC1(List<ModelC1> listChat, Context context){
this.listChat = listChat;
this.context = context;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return listChat.size();
}
#Override
public Object getItem(int i) {
return listChat.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
View vi = convertView;
if(convertView == null ){
if(listChat.get(i).isSend() == 0)
vi=inflater.inflate(R.layout.list_send,null);
else if ((listChat.get(i).isSend() == 1))
vi=inflater.inflate(R.layout.list_recv,null);
else if ((listChat.get(i).isSend() == 2))
vi=inflater.inflate(R.layout.list_mid,null);
}else{
if(listChat.get(i).isSend() == 0)
vi=inflater.inflate(R.layout.list_send,null);
else if ((listChat.get(i).isSend() == 1))
vi=inflater.inflate(R.layout.list_recv,null);
else if ((listChat.get(i).isSend() == 2))
vi=inflater.inflate(R.layout.list_mid,null);
}
if(listChat.get(i).isSend() !=0 || listChat.get(i).isSend() !=1 || listChat.get(i).isSend() !=2 ){
BubbleTextView bubbleTextView = (BubbleTextView) vi.findViewById(R.id.bubbleChat);
if(bubbleTextView != null)
bubbleTextView.setText(listChat.get(i).C1Text);
TextView nameTextView = (TextView) vi.findViewById(R.id.nameChat);
if(nameTextView != null)
nameTextView.setText(listChat.get(i).C1Name);
}else{
vi=inflater.inflate(R.layout.list_mid,null);
BubbleTextView bubbleTextView = (BubbleTextView) vi.findViewById(R.id.bubbleChat);
bubbleTextView.setText("THE END");
}
return vi;
}
And here is the activity
public class Chat1 extends AppCompatActivity {
private static final String TAG = "Chat1";
private AdapterC1 adapter;
private List<ModelC1> listChat = new ArrayList<>();
private int count = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat1);
RecyclerView chatContent1 = findViewById(R.id.chatContent1);
}
private ModelC1 setUpMessage(){
Log.d(TAG, "setUpMessage: Exec");
return();
}
///OnClick of the button in the activity_chat1.xml
public void nextClicked1(View view) {
Log.d(TAG, "nextClicked: Is Clicked");
///After the limit of the arraylist is reached
final int limit = 40;
if(count == limit){
Log.d(TAG, "nextClicked: Limit Reached");
Intent i = new Intent(Chat1.this, MainActivity.class);
startActivity(i);
}else{
///Call the list
loadList(null);
}
}
///Load the list of arrays?
public void loadList(View view){
ModelC1 chat = setUpMessage();
listChat.add(chat);
///The ID of the recycleview in the activity_chat1.xml
final RecyclerView recyclerview = findViewById(R.id.chatContent1);
///The adapter
final AdapterC1 adapter = new AdapterC1(listChat, this);
///Make the recyclerview always scroll
///the adapter
///recyclerview.setAdapter(adapter);
}
My questions are now how do I make the ArrayList (containing strings and drawables) and how to link the ArrayList to make it appear one by one when I click on the button ?
As for the ArrayList, will soemthing like that works ?
private List<List<String>> textChat1 = new ArrayList<List<String>>();
ArrayList<String> textChat1 = new ArrayList<String>();
textChat1.add("This is message 1");
textChat1.add("This is message 2");
textChat1.add("This is message 2");
addresses.add(textChat1);
How can I add images and how to say which strings inflate which layout (left, mid or right) ?
You can do your job like this: in your Adapter's getView method ,
#Override
public View getView(int position, View convertView, ViewGroup container) {
if (convertView == null) {
if (position == 1) {
convertView = getLayoutInflater().inflate(R.layout.left, container, false);
} else if (position == 2) {
convertView = getLayoutInflater().inflate(R.layout.mid, container, false);
} else {
convertView = getLayoutInflater().inflate(R.layout.right, container, false);
}
}
//your code here
return convertView;
}
This will do your job, but, I suggest you to use Recyclerview because it's more efficient and better in terms of looks as well as memory management.

Getting focus of EditText inside RecyclerView

I'm implementing an application in which user can store Debit Cards and later they can use it by just entering the CVV number of the same card. I have used RecyclerView for all the items(Debit Cards) stored by the user. Everything is working fine, view is rendering all good and I have used LinearLayoutManager to show Horizontal scroll.
Now the problem which I am facing is whenever I try to enter CVV of any card as soon as I click on it the view gets shifted towards the last item of the list of Stored Cards, So if I'm having three cards stored in my list and I try to enter CVV for the first one the view is shifting directly to the third card but the focus remains on the first cards EditText. I don't know what's going on with the same. I'm sharing some code part for the same.
Setting adapter and defining horizontal scroll :-
recyclerAdapter = new RecyclerStoredCardAdapter(mContext, storedCards);
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
storedCardListRecycler.setLayoutManager(layoutManager);
storedCardListRecycler.setVisibility(View.VISIBLE);
storedCardListRecycler.setAdapter(recyclerAdapter);
Sharing the screenshots with this so it will get clear. Any help would be appreciable. Thanks.
I have did this using ListView not with RecyclerView
But you can do with RecyclerView also.
Here is my used class demo.
SettingItemListViewAdapter.java
/**
* Created by vishalchhodwani on 18/10/16.
*/
public class SettingItemListViewAdapter extends BaseAdapter {
private final String TAG = "SettingItemListViewAdapter";
Context context;
List<SettingListViewItem> settingItemList;
OnMyClickListeners onMyClickListeners;
MyDatabaseAdapter myDatabaseAdapter;
public SettingItemListViewAdapter(Context context, List<SettingListViewItem> settingItemList) {
this.context = context;
this.settingItemList = settingItemList;
myDatabaseAdapter = new MyDatabaseAdapter(context);
}
public void setMyClickListener(OnMyClickListeners onMyClickListeners) {
this.onMyClickListeners = onMyClickListeners;
}
#Override
public int getCount() {
return settingItemList.size();
}
#Override
public Object getItem(int position) {
return settingItemList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.setting_listview_item, parent, false);
holder.settingListViewForm = (RelativeLayout) convertView.findViewById(R.id.settingListViewItem_form1);
holder.vrijeTekst = (EditText) convertView.findViewById(R.id.settingListViewItem_ed_virje_row1);
holder.kenteken = (EditText) convertView.findViewById(R.id.settingListViewItem_ed_kenketen_row1);
holder.checkRow = (ImageView) convertView.findViewById(R.id.settingListViewItem_check_row1);
holder.deleteRow = (ImageView) convertView.findViewById(R.id.settingListViewItem_deleteRow);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.vrijeTekst.setText(settingItemList.get(position).getItemVrijeTekst());
holder.kenteken.setText(settingItemList.get(position).getItemKenteken());
boolean isSelected = settingItemList.get(position).isItemSelected();
holder.checkRow.setImageResource(isSelected ? R.drawable.checked : R.drawable.uncheked);
holder.vrijeTekst.setTag(position);
holder.vrijeTekst.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(final View v, boolean hasFocus) {
try {
if (!hasFocus) {
if (settingItemList.size() > 0) {
int position = (int) v.getTag();
EditText Caption = (EditText) v;
settingItemList.get(position).setItemVrijeTekst(Caption.getText().toString());
}
} else {
EditText caption = (EditText) v;
caption.setCursorVisible(true);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
holder.kenteken.setTag(position);
holder.kenteken.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(final View v, boolean hasFocus) {
try {
if (!hasFocus) {
if (settingItemList.size() > 0) {
int position = (int) v.getTag();
EditText Caption = (EditText) v;
settingItemList.get(position).setItemKenteken(Caption.getText().toString());
}
} else {
EditText caption = (EditText) v;
caption.setCursorVisible(true);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
holder.checkRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (myDatabaseAdapter.isAvailableInTable(settingItemList.get(position).getItemId()))
onMyClickListeners.onSelectButtonClicked(position);
}
});
holder.deleteRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onMyClickListeners.onDeleteItemButtonClicked(position);
}
});
if (getCount() == position + 1) {
holder.vrijeTekst.requestFocus();
holder.vrijeTekst.performClick();
}
return convertView;
}
public static class ViewHolder {
RelativeLayout settingListViewForm;
EditText vrijeTekst, kenteken;
ImageView checkRow, deleteRow;
}
}
SettingN_New.java (It is a fragment)
public class SettingN_New extends Fragment implements OnClickListener, OnMyClickListeners {
private final String TAG = "SettingN_New";
Context context;
private TextView tv_demo;
ToggleButton togglebtn_save;
Button btn_save, btn_add;
ListView settingItemListView;
List<SettingListViewItem> settingItemList;
SettingItemListViewAdapter settingItemListViewAdapter;
MyDatabaseAdapter myDatabaseAdapter;
TinyDB loginpref;
boolean isNewRowAdded = true;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//This line of code will stay focus on selected edittext in list
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
ActionBar bar = getActivity().getActionBar();
bar.show();
View rootView = inflater.inflate(R.layout.setting_new, container, false);
initializeViews(rootView);
setUI();
getListOfItems();
return rootView;
}
private void setUI() {
try {
if (loginpref.getBoolean(ConstantLib.PREF_AUTO_LOGIN)) {
togglebtn_save.setChecked(true);
} else {
togglebtn_save.setChecked(false);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
private void initializeViews(View rootView) {
context = getActivity();
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View headerView = inflater.inflate(R.layout.setting_listview_header, null);
btn_save = (Button) headerView.findViewById(R.id.btn_save);
btn_add = (Button) headerView.findViewById(R.id.btn_add);
togglebtn_save = (ToggleButton) headerView.findViewById(R.id.togglebtn_save);
tv_demo = (TextView) headerView.findViewById(R.id.tv_demo);
settingItemList = new ArrayList<>();
settingItemListView = (ListView) rootView.findViewById(R.id.setting_listView);
settingItemListView.setClickable(true);
settingItemListView.refreshDrawableState();
settingItemListView.addHeaderView(headerView);
settingItemListView.setItemsCanFocus(true);
settingItemListViewAdapter = new SettingItemListViewAdapter(context, settingItemList);
settingItemListViewAdapter.setMyClickListener(this);
settingItemListView.setAdapter(settingItemListViewAdapter);
myDatabaseAdapter = new MyDatabaseAdapter(context);
loginpref = new TinyDB(getActivity());
btn_save.setOnClickListener(this);
btn_add.setOnClickListener(this);
tv_demo.setOnClickListener(this);
togglebtn_save.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
loginpref.putBoolean(ConstantLib.PREF_AUTO_LOGIN, isChecked);
}
});
}
private void getListOfItems() {
settingItemList.clear();
settingItemList.addAll(myDatabaseAdapter.getAllData());
if (settingItemList.size() == 0) {
isNewRowAdded = true;
SettingListViewItem settingListViewItem = new SettingListViewItem();
settingListViewItem.setItemId(settingItemList.size() + "");
settingListViewItem.setItemVrijeTekst("");
settingListViewItem.setItemKenteken("");
settingListViewItem.setItemSelected(false);
settingItemList.add(settingListViewItem);
} else {
isNewRowAdded = false;
}
notifyDataSetChanged();
}
private void hideKeyboard() {
// Check if no view has focus:
View view = getActivity().getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_save:
clearFocus();
hideKeyboard();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (isValidationSuccess())
saveAllData();
}
}, 200);
break;
case R.id.btn_add:
addAnotherRow();
break;
case R.id.tv_demo:
clickedOnTvDemo();
break;
}
}
private void clickedOnTvDemo() {
try {
Intent i = new Intent(getActivity(), Setting_exp_activity.class);
startActivity(i);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
private boolean isValidationSuccess() {
Log.e(TAG, "isValidationSuccess() called : settingItemList.size()==" + settingItemList.size());
for (int i = 0; i < settingItemList.size(); i++) {
if (settingItemList.get(i).getItemVrijeTekst().equalsIgnoreCase("") || settingItemList.get(i).getItemKenteken().equalsIgnoreCase("")) {
showToast("Veld mag niet leeg zijn");// showToast("Fields should not be empty!!");
return false;
}
}
return true;
}
private void saveAllData() {
Log.e(TAG, "saveAllData() called");
myDatabaseAdapter.clearTable();
for (int i = 0; i < settingItemList.size(); i++) {
isNewRowAdded = false;
SettingListViewItem settingListViewItem = new SettingListViewItem();
settingListViewItem.setItemId(i + "");
settingListViewItem.setItemVrijeTekst(settingItemList.get(i).getItemVrijeTekst());
settingListViewItem.setItemKenteken(settingItemList.get(i).getItemKenteken());
settingListViewItem.setItemSelected(settingItemList.get(i).isItemSelected());
myDatabaseAdapter.insertDataToTable(settingListViewItem);
}
DialogUtils.showInfoDialog(getActivity(),
"Instellingen opgeslagen");
}
private void addAnotherRow() {
Log.e(TAG, "addAnotherRow() called");
if (settingItemList.size() > 0 && !isNewRowAdded) {
if (!settingItemList.get(settingItemList.size() - 1).getItemVrijeTekst().equalsIgnoreCase("") && !settingItemList.get(settingItemList.size() - 1).getItemKenteken().equalsIgnoreCase("")) {
isNewRowAdded = true;
Log.e(TAG, "addAnotherRow() called check 1");
SettingListViewItem settingListViewItem = new SettingListViewItem();
settingListViewItem.setItemId(settingItemList.size() + "");
settingListViewItem.setItemVrijeTekst("");
settingListViewItem.setItemKenteken("");
settingListViewItem.setItemSelected(false);
settingItemList.add(settingListViewItem);
notifyDataSetChanged();
} else {
Log.e(TAG, "addAnotherRow() called check 2");
showToast("Al toegevoegd");// showToast("Already Added!!");
}
} else {
if (!isNewRowAdded) {
isNewRowAdded = true;
Log.e(TAG, "addAnotherRow() called check 3");
SettingListViewItem settingListViewItem = new SettingListViewItem();
settingListViewItem.setItemId("0");
settingListViewItem.setItemVrijeTekst("");
settingListViewItem.setItemKenteken("");
settingListViewItem.setItemSelected(false);
settingItemList.add(settingListViewItem);
notifyDataSetChanged();
} else {
Log.e(TAG, "addAnotherRow() called check 4");
showToast("Al toegevoegd");// showToast("Already Added!!");
}
}
settingItemListView.setSelection(settingItemList.size());
Log.e(TAG, "addAnotherRow() called check 5");
Log.e(TAG, "after settingItemList.size()==" + settingItemList.size());
}
#Override
public void onDeleteItemButtonClicked(int position) {
Log.e(TAG, "onDeleteItemButtonClicked() position==" + position);
if (myDatabaseAdapter.getAllData().size() > 0)
showAlertForDeleteItem(position);
else
showToast("Er is geen item te verwijderen"); // showToast("No item to Delete");
}
#Override
public void onSelectButtonClicked(int position) {
Log.e(TAG, "onSelectButtonClicked() position==" + position);
for (int i = 0; i < settingItemList.size(); i++) {
Log.e(TAG, "onSelectButtonClicked() called check 3");
settingItemList.get(i).setItemSelected(false);
}
settingItemList.get(position).setItemSelected(true);
notifyDataSetChanged();
}
private void showAlertForDeleteItem(final int position) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setMessage("Weet je zeker dat je dit item wilt wissen?");//alertDialog.setMessage("Are you sure you want to delete this item?");
// ja==yes
alertDialog.setPositiveButton("Ja", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
myDatabaseAdapter.deleteTableRow(settingItemList.get(position).getItemId() + "");
settingItemList.remove(position);
settingItemListViewAdapter.notifyDataSetChanged();
if (settingItemList.size() == position + 1) {
isNewRowAdded = false;
}
if (settingItemList.size() == 0) {
isNewRowAdded = false;
addAnotherRow();
}
}
});
//Annuleer==cancel
alertDialog.setNegativeButton("Annuleer", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
private void notifyDataSetChanged() {
settingItemListViewAdapter.notifyDataSetChanged();
}
private void showToast(String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
public void clearFocus() {
if (getActivity().getWindow().getCurrentFocus() != null) {
getActivity().getWindow().getCurrentFocus().clearFocus();
}
}
}
I am giving you my whole class. why? Because it will give you more understanding that how I used it with ListView.
Test it and Let me know. :)
Note
This line of code is very important - getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
Not able to reproduce this issue. Let me know if the following code does what you are facing. If not, can provide more feedback if you share you Adapter's Code.
MainActivity.java
public class MainActivity
extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
MyAdapter adapter = new MyAdapter();
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
recyclerView.setAdapter(adapter);
}
}
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_ite, parent);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((EditText)((MyViewHolder)holder).mBinding.findViewById(R.id.editText)).setHint(position + " ");
}
#Override
public int getItemCount() {
return 100;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
View mBinding;
public MyViewHolder(View binding) {
super(binding);
this.mBinding = binding;
}
}
}
The 2xml layouts:
<EditText
android:id="#+id/editText"
android:layout_height="200dp"
android:layout_width="300dp"/>
</android.support.v7.widget.CardView>
My main_activity.xml is as follows:
<RelativeLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_height="wrap_content"
android:layout_width="match_parent"/>
</RelativeLayout>
As you can see this is the simplest case. Let me know if I missed anything.

How to replace the baseadapter value and how to stop the pagination loading in android filter screen?

I have worked with the concept of filter that have to filter the job from job list based on skills and some list or there.
https://postimg.org/image/g3p1z6lbd/ - DashBoard Fragment.
About DashBoardFragment:
Contains job list view.
Dash Filter Button. - which redirect to the Filter screen.
public class DashBoardRefactor extends Fragment {
public static ProgressDialog progress;
public static List<DashListModel> dashRowList1 = new ArrayList<DashListModel>();
public static View footerView;
// #Bind(R.id.dashListView)
public static ListView dashListView;
int preCount = 2, scroll_Inc = 10, lastCount;
boolean flag = true;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dashboard_fragment, container, false);
ButterKnife.bind(this, v);
setHasOptionsMenu(true);
progress = new ProgressDialog(getActivity());
dashListView = (ListView) v.findViewById(R.id.dashListView);
footerView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dashboard_list_footer, null, false);
dashListView.addFooterView(footerView);
footerView.setVisibility(View.GONE);
dashRowList1.clear();
dashboardViewTask();
dashListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("onItemClick", "onItemClick <---- ");
Intent toPositionDetail = new Intent(getActivity(), PositionDetailScreenRefactor.class);
toPositionDetail.putExtra("id", dashRowList1.get(position).getDashId());
startActivity(toPositionDetail);
getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
}
});
final int totalJobCount = SessionStores.gettotalJobList(getActivity());
Log.e("totalJobCount", "totalJobCount----" + totalJobCount);
dashListView.setOnScrollListener(new EndlessScrollListener(getActivity(), dashListView, footerView));
return v;
}
public void dashboardViewTask() {
progress.setMessage("Please Wait. It is Loading..job orders....");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
progress.show();
// footerView.setVisibility(View.VISIBLE);
Map<String, String> params = new HashMap<String, String>();
Log.e("candidate_id", "candidate_id---->" + SessionStores.getBullHornId(getActivity()));
params.put("candidate_id", SessionStores.getBullHornId(getActivity()));
params.put("page", "1");
new DashBoardTask(getActivity(), params, dashListView, footerView);
// progress.dismiss();
}
#Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
if (menu != null) {
menu.removeItem(R.id.menu_notify);
}
inflater.inflate(R.menu.menu_options, menu);
MenuItem item = menu.findItem(R.id.menu_filter);
item.setVisible(true);
getActivity().invalidateOptionsMenu();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.his__menu_accept:
Toast.makeText(getActivity(), "clicked dashboard menu accept", Toast.LENGTH_LONG).show();
return true;
case R.id.menu_filter:
// click evnt for filter
Toast.makeText(getActivity(), "clicked dashboard filter", Toast.LENGTH_LONG).show();
Intent filter_intent = new Intent(getActivity(), DashBoardFilterScreen.class);
startActivity(filter_intent);
getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onPause() {
super.onPause();
// dashboardViewTask();
}}
DashBoardTask:
public class DashBoardTask {
public DashBoardTask(Context context, Map<String, String> params, ListView dashListView, View footerView) {
this.context = context;
Log.e("context ", "DashBoardTask: " + context);
this.dashListView = dashListView;
this.params = params;
this.footerView = footerView;
ResponseTask();
}
private void ResponseTask() {
new ServerResponse(ApiClass.getApiUrl(Constants.DASHBOARD_VIEW)).getJSONObjectfromURL(ServerResponse.RequestType.POST, params, authorizationKey, context, "", new VolleyResponseListener() {
#Override
public void onError(String message) {
if (DashBoardRefactor.progress.isShowing()) {
DashBoardRefactor.progress.dismiss();
}
}
#Override
public void onResponse(String response) {
//Getting Response and Assign into model Class
int currentPosition = dashListView.getFirstVisiblePosition();
dashListAdapter = new DashListAdapter(context, DashBoardRefactor.dashRowList1, dashListView);
dashListView.setAdapter(dashListAdapter);
((BaseAdapter) dashListAdapter).notifyDataSetChanged();
if (currentPosition != 0) {
// Setting new scroll position
dashListView.setSelectionFromTop(currentPosition + 1, 0);
}
if (footerView.isShown()) {
footerView.setVisibility(View.GONE);
}
//progress.dismiss();
if (DashBoardRefactor.progress.isShowing()) {
try {
DashBoardRefactor.progress.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
DashListAdapter:
________________
public class DashListAdapter extends BaseAdapter {
public static ListView dashListView;
Context c;
private LayoutInflater inflater;
private List<DashListModel> dashRowList;
public DashListAdapter(Context c, List<DashListModel> dashRowList, ListView dashListView) {
this.c = c;
this.dashListView = dashListView;
this.dashRowList = dashRowList;
}
#Override
public int getCount() {
return this.dashRowList.size();
}
#Override
public Object getItem(int position) {
return dashRowList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder dashHolder;
if (inflater == null)
inflater = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.dashboard_jobdetails_list, null);
Log.e("get pos", "get pooooossss---->" + dashRowList.get(position));
final DashListModel dashModel = dashRowList.get(position);
dashHolder = new ViewHolder(convertView);
//Assign the value into screen
dashHolder.dash_company_name.setText(dashModel.getDashCompanyName());
}
the above code for displaying dashboard fragment list.
https://postimg.org/image/nqvp1dud9/ - This link is FilterScreen
By using this image if i filter the job based on the designed UI detail. That should replace into the DashboadFragment list The result should display into the DashBoard Fragment. How can I add pagination on Filter screen the same which have in DashBoardFragment.

Android:Receive Array of Objects and display in listView

Hello to all android folks over there!!
I want to get list of objects from web service and want to display them in list view.Now i am able to fetch those values and collected them in arraylist.But i am facing problem to display them in list view.below is my code.
Using everyones suggestion ,i solved my problem.Thats the spirit of android buddies.I am pasting my answer in UPDATED block.Hope it will be helpful in future.
UPDATED
public class TabFragment2 extends android.support.v4.app.Fragment {
ListView FacultyList;
View rootView;
LinearLayout courseEmptyLayout;
FacultyListAdapter facultyListAdapter;
String feedbackresult,programtype,programname;
Boolean FeedBackResponse;
String FacultiesList[];
public ArrayList<Faculty> facultylist = new ArrayList<Faculty>();
SharedPreferences pref;
FacultyListAdapter adapter;
SessionSetting session;
public TabFragment2(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = getActivity().getSharedPreferences("prefbook", getActivity().MODE_PRIVATE);
programtype = pref.getString("programtype", "NOTHINGpref");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_studenttab2, container, false);
session = new SessionSetting(getActivity());
new FacultySyncerBg().execute("");
courseEmptyLayout = (LinearLayout) rootView.findViewById(R.id.feedback_empty_layout);
FacultyList = (ListView) rootView.findViewById(R.id.feedback_list);
facultyListAdapter = new FacultyListAdapter(getActivity());
FacultyList.setEmptyView(rootView.findViewById(R.id.feedback_list));
FacultyList.setAdapter(facultyListAdapter);
return rootView;
}
public class FacultyListAdapter extends BaseAdapter {
private final Context context;
public FacultyListAdapter(Context context) {
this.context = context;
if (!facultylist.isEmpty())
courseEmptyLayout.setVisibility(LinearLayout.GONE);
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder TabviewHolder;
if (convertView == null) {
TabviewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_feedback,
parent, false);
TabviewHolder.FacultyName = (TextView) convertView.findViewById(R.id.FacultyName);//facultyname
TabviewHolder.rating = (RatingBar) convertView.findViewById(R.id.rating);//rating starts
TabviewHolder.Submit = (Button) convertView.findViewById(R.id.btnSubmit);
// Save the holder with the view
convertView.setTag(TabviewHolder);
} else {
TabviewHolder = (ViewHolder) convertView.getTag();
}
final Faculty mFac = facultylist.get(position);//*****************************NOTICE
TabviewHolder.FacultyName.setText(mFac.getEmployeename());
// TabviewHolder.ModuleName.setText(mFac.getSubject());
TabviewHolder.rating.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
feedbackresult =String.valueOf(rating);
}
});
return convertView;
}
#Override
public int getCount() {
return facultylist.size();
}
#Override
public Object getItem(int position) {return facultylist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
static class ViewHolder {
TextView FacultyName;
RatingBar rating;
Button Submit;
}
private class FacultySyncerBg extends AsyncTask<String, Integer, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog= ProgressDialog.show(getActivity(), "Faculty Feedback!","Fetching Faculty List", true);
}
#Override
protected Void doInBackground(String... params) {
//CALLING WEBSERVICE
Faculty(programtype);
return null;
}
#Override
protected void onPostExecute(Void result) {
/*if (FacultyList.getAdapter() != null) {
if (FacultyList.getAdapter().getCount() == 0) {
FacultyList.setAdapter(facultyListAdapter);
} else
{
facultyListAdapter.notifyDataSetChanged();
}
} else {
FacultyList.setAdapter(facultyListAdapter);
}
progressDialog.dismiss();*/
if (!facultylist.isEmpty()) {
// FacultyList.setVisibiltity(View.VISIBLE) ;
courseEmptyLayout.setVisibility(LinearLayout.GONE);
if (FacultyList.getAdapter() != null)
{
if (FacultyList.getAdapter().getCount() == 0)
{
FacultyList.setAdapter(facultyListAdapter);
}
else
{
facultyListAdapter.notifyDataSetChanged();
}
}
else
{
FacultyList.setAdapter(facultyListAdapter);
}
}else
{
courseEmptyLayout.setVisibility(LinearLayout.VISIBLE);
// FacultyList.setVisibiltity(View.GONE) ;
}
progressDialog.dismiss();
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && isResumed()) {
new FacultySyncerBg().execute("");
}
}//end*
//**************************WEBSERVICE CODE***********************************
public void Faculty(String programtype)
{
String URL ="http://detelearning.cloudapp.net/det_skill_webservice/service.php?wsdl";
String METHOD_NAMEFACULTY = "getUserInfo";
String NAMESPACEFAC="http://localhost", SOAPACTIONFAC="http://detelearning.cloudapp.net/det_skill_webservice/service.php/getUserInfo";
String faculty[]=new String[4];//changeit
String webprogramtype="flag";
String programname="DESHPANDE SUSANDHI ELECTRICIAN FELLOWSHIP";
// Create request
SoapObject request = new SoapObject(NAMESPACEFAC, METHOD_NAMEFACULTY);
request.addProperty("fellowshipname", programname);
// Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
// Set output SOAP object
envelope.setOutputSoapObject(request);
// Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
//my code Calling Soap Action
androidHttpTransport.call(SOAPACTIONFAC, envelope);
// ArrayList<Faculty> facultylist = new ArrayList<Faculty>();
java.util.Vector<SoapObject> rs = (java.util.Vector<SoapObject>) envelope.getResponse();
if (rs != null)
{
for (SoapObject cs : rs)
{
Faculty rp = new Faculty();
rp.setEmployeename(cs.getProperty(0).toString());//program name
rp.setEmployeeid(cs.getProperty(1).toString());//employee name
facultylist.add(rp);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
if (lstView.getAdapter() != null) {
if (lstView.getAdapter().getCount() == 0) {
lstView.setAdapter(finalAdapter);
} else {
finalAdapter.notifyDataSetChanged();
}
} else {
lstView.setAdapter(finalAdapter);
}
and setVisibiltity(View.VISIBLE)for listview
Put this code here
#Override
protected void onPostExecute(Void result) {
if (!facultylist.isEmpty()) {
FacultyList.setVisibiltity(View.VISIBLE) ;
courseEmptyLayout.setVisibility(LinearLayout.GONE);
if (FacultyList.getAdapter() != null) {
if (FacultyList.getAdapter().getCount() == 0) {
FacultyList.setAdapter(facultyListAdapter);
} else {
facultyListAdapter.notifyDataSetChanged();
}
} else {
FacultyList.setAdapter(facultyListAdapter);
}
}else{
courseEmptyLayout.setVisibility(LinearLayout.VISIBLE);
FacultyList.setVisibiltity(View.GONE) ;
}
progressDialog.dismiss();
}
you can try this:
this is the adapter class code.
public class CustomTaskHistory extends ArrayAdapter<String> {
private Activity context;
ArrayList<String> listTasks = new ArrayList<String>();
String fetchRefID;
StringBuilder responseOutput;
ProgressDialog progress;
String resultOutput;
public String getFetchRefID() {
return fetchRefID;
}
public void setFetchRefID(String fetchRefID) {
this.fetchRefID = fetchRefID;
}
public CustomTaskHistory(Activity context, ArrayList<String> listTasks) {
super(context, R.layout.content_main, listTasks);
this.context = context;
this.listTasks = listTasks;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_task_history, null, true);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
LinearLayout linearLayout = (LinearLayout) listViewItem.findViewById(R.id.firstLayout);
//System.out.println("client_id" + _clientID);
//TextView textViewDesc = (TextView) listViewItem.findViewById(R.id.textViewDesc);
//ImageView image = (ImageView) listViewItem.findViewById(R.id.imageView);
if (position % 2 != 0) {
linearLayout.setBackgroundResource(R.color.sky_blue);
} else {
linearLayout.setBackgroundResource(R.color.white);
}
textViewName.setText(listTasks.get(position));
return listViewItem;
}
}
and now in the parent class you must have already added a list view in your xml file so now display code for it is below:
CustomTaskHistory customList = new CustomTaskHistory(TaskHistory.this, task_history_name);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(customList);
you can also perform any action on clicking cells of listview.If needed code for it is below add just below the above code:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent nextScreen2 = new Intent(getApplicationContext(), SubscribeProgrammes.class);
nextScreen2.putExtra("CLIENT_ID", _clientID);
nextScreen2.putExtra("REFERENCE_ID", reference_IDs.get(i));
startActivity(nextScreen2);
Toast.makeText(getApplicationContext(), "You Clicked " + task_list.get(i), Toast.LENGTH_SHORT).show();
}
});

listview hide on orientation change android

I am using custom list view inside fragment(From Api). on orientation change data is still in array list and also list view get notified but it hides when screen rotates.
here is the code:
public class FragNotice extends Fragment implements View.OnClickListener {
ListAdapter listAdapter;
ListView listView;
EditText editTextNotice;
private Button btnSearch;
private Button btnClear;
private int incre = 1;
private boolean boolScroll = true;
public FragNotice() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(getActivity()));
setRetainInstance(true);
search(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return init(inflater.inflate(R.layout.notice_activity, container, false));
}
private View init(View view) {
editTextNotice = (EditText) view.findViewById(R.id.editTextNotice);
btnSearch = (Button) view.findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(this);
btnClear = (Button) view.findViewById(R.id.btnClear);
btnClear.setOnClickListener(this);
listView = (ListView) view.findViewById(R.id.listViewNotice);
listView.setOnScrollListener(onScrollListener());
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (listAdapter==null) {
listAdapter=new ListAdapter(getActivity(), new ArrayList<ListRowItem>());
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
}
AsyncRequest.OnAsyncRequestComplete onAsyncRequestComplete = new AsyncRequest
.OnAsyncRequestComplete() {
#Override
public void asyncResponse(String response, int apiKey) {
switch (apiKey) {
case 1:
listView(response);
break;
}
}
};
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnClear) {
incre = 1;
boolScroll = true;
editTextNotice.setText(null);
if (listAdapter != null)
listAdapter.clear();
search(true);
} else if (v.getId() == R.id.btnSearch) {
String std = editTextNotice.getText().toString();
if (std.trim().length() > 1) {
incre = 1;
boolScroll = true;
if (listAdapter != null)
listAdapter.clear();
try {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService
(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(new View(getActivity()).getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
} catch (Exception e) {
// TODO: handle exception
}
search(false);
} else
Toast.makeText(getActivity(),
"Please enter atleast two character.", Toast.LENGTH_LONG)
.show();
}
}
class ListAdapter extends ArrayAdapter<ListRowItem> {
private final Context context;
public ListAdapter(Context asyncTask, java.util.List<ListRowItem> items) {
super(asyncTask, R.layout.notice_listitem, items);
this.context = asyncTask;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
final ListRowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.notice_listitem, parent, false);
holder = new ViewHolder();
holder.txtSno = (TextView) convertView.findViewById(R.id.txtSno);
holder.txtNoticePublishDate = (TextView) convertView.findViewById(R.id
.txtNoticePublishDate);
holder.btnView = (Button) convertView.findViewById(R.id.btnView);
holder.txtNoticeDescription = (TextView) convertView.findViewById(R.id
.txtNoticeDescription);
holder.txtNoticeName = (TextView) convertView.findViewById(R.id.txtNoticeName);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtSno.setText(String.valueOf(position + 1));
holder.txtNoticeDescription.setText(new AppUtility().TitleCase(rowItem.getDescription
()));
holder.txtNoticeName.setText(new AppUtility().TitleCase(rowItem.getFileTitle()));
try {
holder.txtNoticePublishDate.setText(String.valueOf((new SimpleDateFormat("dd MMM " +
"yyyy HH:mm:ss", Locale.US)).format((new SimpleDateFormat
("yyyy-MM-dd'T'HH:mm:ss", Locale.US)).parse(rowItem.getUpdateDate()))));
} catch (ParseException e) {
holder.txtNoticePublishDate.setText(new AppUtility().TitleCase(rowItem
.getUpdateDate()));
}
holder.btnView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return convertView;
}
/*private view holder class*/
private class ViewHolder {
TextView txtSno;
TextView txtNoticeName;
TextView txtNoticeDescription;
TextView txtNoticePublishDate;
Button btnView;
}
}
class ListRowItem {
private final String FileTitle;
private final String Description;
private final String ContentType;
private final int DocumentUploadID;
private final String UpdateDate;
ListRowItem() {
this.FileTitle = "";
this.Description = "";
this.ContentType = "";
this.DocumentUploadID = 0;
this.UpdateDate = "";
}
ListRowItem(String fileTitle, String description, String contentType, int
documentUploadID, String updateDate) {
this.FileTitle = fileTitle;
this.Description = description;
this.ContentType = contentType;
this.DocumentUploadID = documentUploadID;
this.UpdateDate = updateDate;
}
public String getFileTitle() {
return FileTitle;
}
public int getDocumentUploadID() {
return DocumentUploadID;
}
public String getUpdateDate() {
return UpdateDate;
}
public String getDescription() {
return Description;
}
public String getContentType() {
return ContentType;
}
}
private void listView(String response) {
try {
ArrayList<ListRowItem> lstItem;
if(listAdapter==null){
Type listType = new TypeToken<ArrayList<ListRowItem>>() {
}.getType();
lstItem = new Gson().fromJson(response, listType);
listAdapter = new ListAdapter(getActivity(), lstItem);
} else {
Type listType = new TypeToken<ArrayList<ListRowItem>>() {
}.getType();
lstItem = new Gson().fromJson(response, listType);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
listAdapter.addAll(lstItem);
} else {
for (ListRowItem items : lstItem) {
listAdapter.add(items);
}
}
}
if (listAdapter != null)
listAdapter.notifyDataSetChanged();
} catch (Exception e) {
}
}
private AbsListView.OnScrollListener onScrollListener() {
return new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int threshold = 5;
int count = listView.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (listView.getLastVisiblePosition() >= count - threshold) {
if (boolScroll) {
if (editTextNotice.getText().toString().trim().length() > 0)
search(false);
else
search(true);
}
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
}
};
}
private void search(boolean bool) {
String URL;
if (bool) {
URL = new SqLite(getActivity()).returnDefaultURI() + "notice/0/" + incre;
incre = incre + 1;
} else {
URL = new SqLite(getActivity()).returnDefaultURI() + "notice/" +
editTextNotice.getText().toString().trim() + "/" + incre;
incre = incre + 1;
}
AsyncRequest asyncRequest;
if (incre > 2)
asyncRequest = new AsyncRequest(onAsyncRequestComplete, getActivity(), "GET", null,
null, 1);
else
asyncRequest = new AsyncRequest(onAsyncRequestComplete, getActivity(), "GET", null,
"Fetching data", 1);
asyncRequest.execute(URL);
}
}
You need to load the data into the ListView again. You are binding the ListView to an adapter, you need to do it in onConfigurationChanged() method.
When orientation changes the activity reloads again.So you have to override onConfigurationChanged method.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
//Your Code Here
}
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//Your Code Here
}
}
create a directory layout-land in the resources copy the your .xml file there align and set the Edittext and Button according to landscape layout .may be it solved your problem if the listview doest not get enough space to show in landscape layout
In onViewCreated(View view, Bundle savedInstanceState) method above you are setting new empty arraylist every time. So the previous items which are loaded are removed from adapter even though it is retained by setRetainInstance(true)
So you should have a Field that holds the arraylist and pass that field to adapter
private ArrayList<ListRowItem> listItems = new ArrayList<>()
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (listAdapter==null) {
listAdapter=new ListAdapter(getActivity(), listItems);//pass the Arraylist here
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
}
Then in private void listView(String response) method, add items to that listview created above as
listItems = new Gson().fromJson(response, listType);
listAdapter.notifyDataSetChanged();

Categories

Resources