How do Refresh List View when adding new elements - android

What i am doing is showing a list view and reload its data when list is Moved to last Element.
Its working fine but the problem is when it reloads it went back to the top element in list. I want List to be stayed at same position and append new Elements below it.
Here is what i am doing
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount == totalItemCount
&& totalItemCount != 0) {
if (flag_loading == false) {
flag_loading = true;
toast("Last view");
loadMorePost();
}
}
}
private void loadMorePost() {
page_no = page_no + 1;
String url = "api/post/index/page_no/" + page_no;
syncManager.sendToServer(url, null, this);
}
if (action.equals("index") && controller.equals("post")) {
if (status) {
//postItemsList.clear();
JSONArray postArray = jsonObject.getJSONArray("post_list");
if (postArray.length() <= 0) {
toast("No Post Available");
} else {
for (int i = 0; i < postArray.length(); i++) {
JSONObject obj = postArray.getJSONObject(i);
ItemsAllPost data = new ItemsAllPost();
data.user_first_name = obj
.getString("User_first_name");
data.user_address = obj.getString("User_address");
data.user_post_count = obj
.getString("user_post_count");
data.description = obj
.getString("post_description");
data.category_id = obj.getString("category_id");
data.create_user_id = obj
.getString("create_user_id");
data.post_image = obj.getString("post_image");
data.user_ph_no = obj.getString("User_ph_no");
data.user_long = obj.getString("User_long");
data.date = obj.getString("date");
data.post_fav = obj.getString("post_fav");
data.amount = obj.getString("amount");
data.id = obj.getString("id");
data.category_title = obj
.getString("category_title");
data.time_period = obj.getString("time_period");
data.is_private = obj.getString("is_private");
data.fav_count = obj.getString("fav_count");
JSONArray imagesarry = obj
.getJSONArray("post_image");
data.imgList = new String[imagesarry.length()];
for (int j = 0; j < imagesarry.length(); j++) {
data.imgList[j] = imagesarry.getString(j);
}
data.view_count = obj.getString("view_count");
data.user_email = obj.getString("User_email");
data.user_lat = obj.getString("User_lat");
data.title = obj.getString("post_title");
postItemsList.add(data);
}
inflateList(postItemsList);
}
}
}
private void inflateList(ArrayList<ItemsAllPost> postItemsList) {
if (postItemsList.size() > 0) {
adapter = new AllPostAdapter((BaseActivity) activity,
postItemsList, userDataFrag);
allpostsLV.setAdapter(adapter);
adapter.notifyDataSetChanged();
} else {
// do nothing
}
}
Any Help
What should i do
Thanks in Advance

using one List to store your data :
private List<ItemsAllPost> datas;
init your adapter only one when the first time you get data :
adapter = new AllPostAdapter((BaseActivity) activity,
postItemsList, datas);
when you load more data finish just add all extra data to : datas
datas.addAll(moredataList);
and only need to call :
adapter.notifyDataSetChanged();
I cant see where postItemsList is declared so I guess you made it like the : datas variable so you can only call : adapter.notifyDataSetChanged(); but don't re-init your adapter.

try this
add this code where you get your updated data and also adapter : adapter.notifyDataSetChanged();

remove these lines :
private void inflateList(ArrayList<ItemsAllPost> postItemsList) {
if (postItemsList.size() > 0) {
adapter = new AllPostAdapter((BaseActivity) activity,
postItemsList, userDataFrag);
allpostsLV.setAdapter(adapter);
adapter.notifyDataSetChanged();
} else {
// do nothing
}
}
and add adapter.notifyDataSetChanged(); after
postItemsList.add(data);

Related

How to put ArrayObjectAdapter items in order

I am displaying multiple rows in one header and there is 5 more categories like drama and I am doing the same job for them. My question is when I set the adapter categories displaying randomly.(assuming of request speed).For example I want the display Drama on the first line always. I gave them id of adapter's constructor but didn't work out. Code :
if (response.body().getItems().size() > 0) {
Log.d("Drama",""+response.body().getItems().size());
List<MovieItem> newMovieItems = response.body().getItems();
HeaderItem liveHeader = new HeaderItem("Drama");
LiveChannelPresenter liveChannelPresenter = new LiveChannelPresenter();
ArrayObjectAdapter liveRowAdapter = new ArrayObjectAdapter(liveChannelPresenter);
for (int i = 0; i < newMovieItems.size(); i++) {
movieItem2 = response.body().getItems().get(i);
liveRowAdapter.add(movieItem2);
}
mRowsAdapter.add(new ListRow(0,liveHeader,liveRowAdapter));
}
}
if (response.body().getItems().size() > 0) {
Log.d("Drama",""+response.body().getItems().size());
List<MovieItem> newMovieItems = response.body().getItems();
//sorted:
Arrays.sort(newMoviewItems, new Comparator() { some condition to sort });
HeaderItem liveHeader = new HeaderItem("Drama");
LiveChannelPresenter liveChannelPresenter = new LiveChannelPresenter();
ArrayObjectAdapter liveRowAdapter = new ArrayObjectAdapter(liveChannelPresenter);
for (int i = 0; i < newMovieItems.size(); i++) {
//note the change here \|/
movieItem2 = newMoviewItems.get(i);
liveRowAdapter.add(movieItem2);
}
mRowsAdapter.add(new ListRow(0,liveHeader,liveRowAdapter));
}

Listview not updating based on value on Array Adapter

I call the method below to update my listview
ListView list = (ListView) listView.findViewById(R.id.plan_list);
itemsList = sortAndAddSections(getItems_search(name));
ListAdapter adapter = new ListAdapter(getActivity(), itemsList);
list.setAdapter(adapter);
but that code is associated with a value that changes and also this is the other code
private ArrayList<plan_model> getItems_search(String param_cusname) {
Cursor data = myDb.get_search_plan(pattern_email, param_name);
int i = 0;
while (data.moveToNext()) {
String date = data.getString(3);
String remarks = data.getString(4);
items.add(new plan_model(cusname, remarks);
}
return items;
}
and this is my sorter
private ArrayList sortAndAddSections(ArrayList<plan_model> itemList) {
Collections.sort(itemList);
plan_model sectionCell;
tempList.clear();
tmpHeaderPositions.clear();
String header = "";
int addedRow = 0;
int bgColor = R.color.alt_gray;
for (int i = 0; i < itemList.size(); i++) {
String remarks = itemList.get(i).getRemarks();
String date = itemList.get(i).getDate();
if (!(header.equals(itemList.get(i).getDate()))) {
sectionCell = new plan_model(remarks, date);
sectionCell.setToSectionHeader();
tmpHeaderPositions.add(i + addedRow);
addedRow++;
tempList.add(sectionCell);
header = itemList.get(i).getDate();
bgColor = R.color.alt_gray;
}
sectionCell = itemList.get(i);
sectionCell.setBgColor(bgColor);
tempList.add(sectionCell);
if (bgColor == R.color.alt_gray) bgColor = R.color.alt_white;
else bgColor = R.color.alt_gray;
}
tmpHeaderPositions.add(tempList.size());
for (int i = 0; i < tmpHeaderPositions.size() - 1; i++) {
sectionCell = tempList.get(tmpHeaderPositions.get(i));
sectionCell.setDate(sectionCell.getDate() + " (" +
(tmpHeaderPositions.get(i + 1) - tmpHeaderPositions.get(i) - 1) + ")");
}
return tempList;
}
my question is the value name changes but my listview is not how can I update my listview? because i need to update it based on search parameter
If your itemList is being updated properly, you don't need to create another instance of the adapter, just use notifyDataSetChanged():
private void createList() {
ListView list = (ListView) listView.findViewById(R.id.plan_list);
itemsList = sortAndAddSections(getItems_search(name));
adapter = new ListAdapter(getActivity(), itemsList);
list.setAdapter(adapter);
}
private void updateList() {
sortAndAddSections(getItems_search(name)); // Update itemList without re-assign its value, otherwise the adapter will loose reference
adapter.notifyDataSetChanged()
}
In getItems_search() add this line at the beginning:
items.clear();
Every time the value of name changes you have to do the following:
itemsList.clear();
itemsList = sortAndAddSections(getItems_search(name));
list.setAdapter(new ListAdapter(getActivity(), itemsList));

Why does variables changes depending on android version?

I got ListView with simpleAdapter. If I click on some item in my List view it show me 2 diferent variables.
Some code:
// Listview Data
ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>(Invoice_numberArr.length);
Map<String, Object> m;
for(int i = 0; i<Invoice_numberArr.length; i++){
int str = Integer.parseInt(Invoice_numberArr[i]);
int str2 = Integer.parseInt(InvoiceNumberForDetails);
if(str == str2){
m = new HashMap<String, Object>();
m.put(ATT_INU, Invoice_numberArr[i]);
m.put(ATT_ANU, Article_numberArr[i]);
m.put(ATT_AMO, AmountArr[i]);
m.put(ATT_PRE, PriceArr[i]);
m.put(ATT_TPR, Total_priceArr[i]);
m.put(ATT_SDE, Sale_designationArr[i]);
data.add(m);
}
}
String[] from = {ATT_INU, ATT_ANU, ATT_AMO, ATT_PRE, ATT_TPR, ATT_SDE};
int[] till = {R.id.txtInvoice_number, R.id.txtArticle_number, R.id.txtAmount, R.id.txtPrice, R.id.txtTotalPrice, R.id.txtSale_designation};
//activities elements
invoices_list_details_view = (ListView)findViewById(R.id.invoices_list_details_view);
invoicesDetailsSAdapter = new SimpleAdapter(InvoicesDetails.this, data, R.layout.invoices_list_item_details_view, from , till);
invoices_list_details_view.setAdapter(invoicesDetailsSAdapter);
Utility Utility = new Utility();
Utility.setListViewHeightBasedOnChildren(invoices_list_details_view);
//if item clicked
invoices_list_details_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String positions = parent.getAdapter().getItem(position).toString();
//int positions = parent.getAdapter().;
parent.getAdapter();
int indexPos = -1; // if doesnt exist
for (int i = 0; i < Invoice_numberArr.length; i++) {
if (positions.contains("article_numbers="+Article_numberArr[i]+", "+"sale_designations="+Sale_designationArr[i]+", "+"amounts="+AmountArr[i]+", "+"invoice_numbers=" + Invoice_numberArr[i]+", "+"prices="+PriceArr[i]+", "+"total_prices="+Total_priceArr[i])) {
indexPos = i;
break;
} else if (positions.contains("prices="+PriceArr[i]+", "+"article_numbers="+Article_numberArr[i]+", "+"amounts="+AmountArr[i]+", "+"sale_designations="+Sale_designationArr[i]+", "+"invoice_numbers=" + Invoice_numberArr[i]+", "+"total_prices="+Total_priceArr[i])){
indexPos = i;
break;
}
}
//some int to transfer it to position class
int integerr = indexPos;
Intent invoices_details_position = new Intent(InvoicesDetails.this, InvoicesDetailsPosition.class);
invoices_details_position.putExtra("saleDesignationForPosition", Sale_designationArr[indexPos]);
invoices_details_position.putExtra("articleNumberForPosition", Article_numberArr[indexPos]);
invoices_details_position.putExtra("sequenceNumberForPosition", Sequence_numberArr[indexPos]);
invoices_details_position.putExtra("amountForPosition", AmountArr[indexPos]);
invoices_details_position.putExtra("warehouseForPosition", WarehouseArr[indexPos]);
invoices_details_position.putExtra("containerDescriptionForPosition", Container_descriptionArr[indexPos]);
invoices_details_position.putExtra("priceForPosition", PriceArr[indexPos]);
invoices_details_position.putExtra("discountForPosition", DiscountArr[indexPos]);
invoices_details_position.putExtra("totalPriceForPosition", Total_priceArr[indexPos]);
startActivity(invoices_details_position);
}
});
So if clicked on my item from ListView under android 4.3 till 5.0 varible
String positions = parent.getAdapter().getItem(position).toString();
shows me
string " {prices=10.8, article_numbers=0736, amounts=1, sale_designations=Pfirsichlikör, invoice_numbers=1, total_prices=10.8} "
And if I clicked under Android version 5.1 its shows me
string " {article_numbers=0736, sale_designations=Pfirsichlikör, amounts=1, invoice_numbers=1, prices=10.8, total_prices=10.8} "
Because that I need to check it twice with that
for (int i = 0; i < Invoice_numberArr.length; i++) {
if (positions.contains("article_numbers="+Article_numberArr[i]+", "+"sale_designations="+Sale_designationArr[i]+", "+"amounts="+AmountArr[i]+", "+"invoice_numbers=" + Invoice_numberArr[i]+", "+"prices="+PriceArr[i]+", "+"total_prices="+Total_priceArr[i])) {
indexPos = i;
break;
} else if (positions.contains("prices="+PriceArr[i]+", "+"article_numbers="+Article_numberArr[i]+", "+"amounts="+AmountArr[i]+", "+"sale_designations="+Sale_designationArr[i]+", "+"invoice_numbers=" + Invoice_numberArr[i]+", "+"total_prices="+Total_priceArr[i])){
indexPos = i;
break;
}
}
So my question now why does it changes depending on Android version ?
Thx for help.
Thank #Mike M. LinkedHashMap s instead HashMap s works for all Android

How to read text dictionary from assests display on Candidate view in Softkeyboard

I'm developing softkeyboard in updateCandidates(). My question is how to retrieve each text when Composing have some words then load my dictionary in candidate view.
Image:
How to load words.
Image
like this
Thanks for share me any information about it.
Solution
You can make method like this :
public ArrayList<String> readFile() {
ArrayList<String> list = new ArrayList<String>();
try {
AssetManager am = getAssets();
InputStream data = am.open("data.txt");
InputStreamReader dataInputStream = new InputStreamReader(data);
BufferedReader reader = new BufferedReader(dataInputStream);
String each = null;
while ((each = reader.readLine()) != null) {
list.add(each);
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
Edit Softkeyboard
pickSuggestionManually()
public void pickSuggestionManually(int index) {
if (mCompletionOn && mCompletions != null && index >= 0 && index < mCompletions.length) {
CompletionInfo ci = mCompletions[index];
getCurrentInputConnection().commitCompletion(ci);
if (mCandidateView != null) {
mCandidateView.clear();
}
updateShiftKeyState(getCurrentInputEditorInfo());
} else if (mComposing.length() > 0) {
// If we were generating candidate suggestions for the current
// text, we would commit one of them here. But for this sample,
// we will just commit the current text.
mComposing.setLength(index);
mComposing = new StringBuilder(mCandidateList.get(index) + " ");
commitTyped(getCurrentInputConnection());
}
}
Important here updateCandidates()
ArrayList<String> listData = readFile();
System.out.println("Sonu Kumar: " + listData);
if (!mCompletionOn) {
if (mComposing.length() > 0) {
ArrayList<String> list = new ArrayList<String>();
// list.add(mComposing.toString());
for (int j = 0; j < listData.size(); j++) {
String str = mComposing.toString().toLowerCase();
if (listData.get(j).startsWith(str)) {
list.add(listData.get(j));
}
}
mCandidateList = list;
setSuggestions(list, true, true);
} else {
setSuggestions(null, false, false);
}
}
Thank
To show the suggestion words in candidate view, please modify the updateCandidates() method of SoftKeyboard.java file:
ArrayList<String> list = new ArrayList<String>();
updateCandidate(){
if (!mCompletionOn) {
list.clear();
if (mComposing.length() > 0) {
String mStr= mComposing.toString().toLowerCase();
for (int i = 0; i < Dictionary.data.length; i++) {
String str = Dictionary.data[i];
if (str.startsWith(mStr)) {
list.add(str);
}
}
setSuggestions(list, true, true);
} else {
setSuggestions(null, false, false);
}
}
}
To enter the picked word from candidate view to input text, please modify following method in SoftKeyboard example project.
public void pickSuggestionManually(int index) {
if (mCompletionOn && mCompletions != null && index >= 0
&& index < mCompletions.length) {
CompletionInfo ci = mCompletions[index];
getCurrentInputConnection().commitCompletion(ci);
if (mCandidateView != null) {
mCandidateView.clear();
}
updateShiftKeyState(getCurrentInputEditorInfo());
} else if (mComposing.length() > 0) {
mComposing.setLength(index);
mComposing = new StringBuilder(mCandidateList.get(index) + " ");
commitTyped(getCurrentInputConnection());
}
}

The method notifyDataSetChanged() not working in custom Listview

I custom listview with adapter extend BaseAdapter.
In method getView I have a button Add, and I set listener to it
item.btnAddBasket.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showChooseSize(products.get(pos), pos);
DialogFragmentCustom.setPosition(pos);
}
});
And I have two method, which are call when I press button Add.
public void showChooseSize(ProductInfo productInfo, int pos) {
ArrayList<Stock> stocks = new ArrayList<Stock>();
stocks.addAll(productInfo.getStock());
ArrayList<String> colors = new ArrayList<String>();
ArrayList<String> sizes = new ArrayList<String>();
if (stocks != null && stocks.size() > 0) {
for (int i = 0; i < stocks.size() - 1; i++) {
colors.add(stocks.get(i).getColorName());
sizes.add(stocks.get(i).getSize());
}
}
if (sizes != null && sizes.size() > 0) {
HashSet<String> hs_size = new HashSet<String>(); // remove elements
// duplicate
hs_size.addAll(sizes);
sizes.clear();
sizes.addAll(hs_size);
if (sizes.size() == 1) {
size = sizes.get(0);
} else {
for (int j = 0; j < sizes.size() - 1; j++) {
size = size + sizes.get(j) + ", ";
}
size = size + sizes.get(sizes.size() - 1);
}
a_sizes = null;
if (size.split(",") != null) {
a_sizes = size.split(",");
}
if (a_sizes == null) {
a_sizes[0] = "This product do not have size";
}
if (a_sizes != null && a_sizes.length > 0) {
Config.isWishList = true;
((Activity) context).setTheme(R.style.ActionSheetStyleIOS7);
ActionSheetChooseSize.setProductInfo(productInfo);
ActionSheetChooseSize.createBuilder(context, ((FragmentActivity) context).getSupportFragmentManager()).setOtherButtonTitles(a_sizes)
.setCancelableOnTouchOutside(true).setListener(this).show();
isShowChooseSize = true;
} else {
addToBag(productInfo, pos);
}
}
Method add product into Bag when press button Add, it inside my adapter
public void addToBag(ProductInfo productInfo, int pos) {
// Config.productSaleInfos.add(products.get(pos));
Config.productSaleInfos.add(productInfo);
Config.numProductSale = Config.productSaleInfos.size();
Config.numProductWishlist = Config.numProductWishlist - 1 < 0 ? Config.numProductWishlist - 1 : 0;
//SlideMenuFragment.setNumWish(Config.numProductWishlist + "");
new DeletionItemWishlist(context).execute(products.get(pos));
products.remove(pos);
notifyDataSetChanged();
float sumaryPrice = 0;
for (int i = 0; i < products.size(); i++) {
String price = products.get(i).getSalePrice();
int index = price.indexOf(",");
if (index > -1) {
price = price.replace(",", "");
}
float p = Functions.getFloatFromString(price);
sumaryPrice = sumaryPrice + p;
}
basket.setText(Config.numProductSale + "");
subtotal.setText(Html.fromHtml("<b>Subtotal: </b>" + "<font color=\"#FF7F00\">" + sumaryPrice + " ฿</font>"));
Functions.showLog(context, "add bag success!");
}
But notifyDataSetChanged(); is not working in my code. Can you help me please?

Categories

Resources