Hello I am newbie to android and working on a list-view demo,I recently found a weird behavior of list-view when i scroll it down it forcefully comes upside,Can anybody tell me what should be the reason behind this behavior.I am posting my code here.
activity
package one.tusk.stush.fragments;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.company.stush.R;
import java.util.List;
import one.tusk.stush.SearchPostActivity;
import one.tusk.stush.adapters.TimelineAdapter;
import one.tusk.stush.connect.Post;
import one.tusk.stush.loaders.SearchPostsLoader;
import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;
public class SearchPostsFragment extends BaseFragment implements LoaderManager.LoaderCallbacks<List<Post>>, OnRefreshListener, OnScrollListener {
public static android.widget.PopupMenu popupMenu;
private int index = -1;
private int top = 0;
TimelineAdapter mTimelineAdapter;
SearchPostsLoader mTimelineLoader;
PullToRefreshLayout mPullToRefreshLayout;
ListView mListViewTimeline;
ProgressBar mProgressBarLoading;
TextView mTextViewNoItems;
ImageView im;
Menu mm;
int total;
int lastPosition;
int lastTop;
String search;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
search = getArguments().getString("search");
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_timeline_other, container, false);
setHasOptionsMenu(false);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
public void onResume () {
super.onResume();
getActivity().invalidateOptionsMenu();
mListViewTimeline.setSelectionFromTop(
lastPosition,
lastTop
);
// if(index!=-1){
// mListViewTimeline.setSelectionFromTop(index, top);
// }
setHasOptionsMenu(false);
}
#Override
public void onStop() {
super.onStop();
lastPosition = mListViewTimeline.getFirstVisiblePosition();
View v = mListViewTimeline.getChildAt(0);
lastTop = (v == null) ? 0 : v.getTop();
// lastPosition = mListViewTimeline.getSelectedItemPosition();
// int lastPositionInGroup = lastPosition - mListViewTimeline.getFirstVisiblePosition();
// lastTop = mListViewTimeline.getChildAt( lastPositionInGroup ).getTop();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
getActivity().getMenuInflater().inflate(R.menu.search_post, menu);
//MenuItem refreshItem = menu.findItem(R.id.action_edit);
//refreshItem.setVisible(true);
//inflater.inflate(R.menu.fragment_profile_menu, menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.search22) {
// Log.d("MyApp", "action bar clicked");
Intent intent = new Intent(getActivity(), SearchPostActivity.class);
intent.putExtra("View_mode", true);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
total = 0;
mPullToRefreshLayout = (PullToRefreshLayout) getActivity().findViewById(R.id.ptr_layout);
ActionBarPullToRefresh.from(getActivity()).allChildrenArePullable().listener(this).setup(mPullToRefreshLayout);
mProgressBarLoading = (ProgressBar) getActivity().findViewById(R.id.progressBarLoading);
mTextViewNoItems = (TextView) getActivity().findViewById(R.id.textViewNoItems);
mTimelineAdapter = new TimelineAdapter(getActivity());
mListViewTimeline = (ListView) getActivity().findViewById(R.id.listViewTimeline);
mListViewTimeline.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
mListViewTimeline.setEmptyView(mProgressBarLoading);
mListViewTimeline.setAdapter(mTimelineAdapter);
mListViewTimeline.setOnScrollListener(this);
// mListViewTimeline.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
mListViewTimeline.setVerticalScrollBarEnabled(false);
getLoaderManager().initLoader(0, null, this);
}
#Override
public Loader<List<Post>> onCreateLoader(int id, Bundle args) {
mTimelineLoader = new SearchPostsLoader(getActivity(), mListViewTimeline, search);
setHasOptionsMenu(false);
return mTimelineLoader;
}
#Override
public void onLoadFinished(Loader<List<Post>> arg0, List<Post> data) {
mTimelineAdapter.setData(data);
mTimelineAdapter.notifyDataSetChanged();
mPullToRefreshLayout.setRefreshComplete();
mTextViewNoItems.setVisibility(View.VISIBLE);
mProgressBarLoading.setVisibility(View.INVISIBLE);
mListViewTimeline.setEmptyView(mTextViewNoItems);
}
#Override
public void onLoaderReset(Loader<List<Post>> arg0) {
mTimelineAdapter.setData(null);
setHasOptionsMenu(false);
}
#Override
public void onRefreshStarted(View view) {
getLoaderManager().destroyLoader(0);
getLoaderManager().initLoader(0, null, this);
mTextViewNoItems.setVisibility(View.INVISIBLE);
mProgressBarLoading.setVisibility(View.VISIBLE);
mListViewTimeline.setEmptyView(mProgressBarLoading);
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount >= totalItemCount && visibleItemCount != 0) {
if (mTimelineLoader.loadMore() && !mTimelineLoader.loading()) {
total = totalItemCount - 1;
lastPosition = view.getFirstVisiblePosition();
View v = view.getChildAt(0);
lastTop = (v == null) ? 0 : v.getTop();
mTimelineLoader.onContentChanged();
}
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
public void searchPost(String query)
{
search = query;
lastPosition = 0;
lastTop = 0;
mTimelineAdapter.clear();
// mTimelineLoader.loadInBackground();
Log.d("12","UPDATE");
getLoaderManager().restartLoader(0, null, this);
}
}
Adapter
package one.tusk.stush.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import com.company.stush.R;
import java.util.List;
import one.tusk.stush.connect.Post;
import one.tusk.stush.views.PostListItem;
public class TimelineAdapter extends ArrayAdapter<Post> {
private final LayoutInflater mInflater;
public TimelineAdapter(Context context) {
super(context, R.layout.list_item_post);
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setData(List<Post> data) {
setNotifyOnChange(true);
clear();
if (data != null) {
addAll(data);
notifyDataSetChanged();
}
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Post post = getItem(position);
PostListItem view;
if (convertView == null) {
view = (PostListItem) mInflater.inflate(R.layout.list_item_post, parent, false);
} else {
view = (PostListItem) convertView;
}
view.setPost(post);
notifyDataSetChanged();
return view;
}
}
You can try this,
Change your code
if(results.size() > 0){
SearchAdapter searchAdapter = new SearchAdapter(SearchActivity.this);
searchAdapter.setData(results);
mListViewSearchUsers.setAdapter(searchAdapter);
textNotFound.setVisibility(View.GONE);
}else {
textNotFound.setVisibility(View.VISIBLE);
textNotFound.setText("No users found");
}
to
if(results.size() > 0){
SearchAdapter searchAdapter = new SearchAdapter(SearchActivity.this);
if (searchAdapter== null) {
searchAdapter.setData(results);
mListViewSearchUsers.setAdapter(searchAdapter);
} else {
searchAdapter.setData(results);
mListViewSearchUsers.notifyDatasetChange();
}
textNotFound.setVisibility(View.GONE);
}else {
textNotFound.setVisibility(View.VISIBLE);
textNotFound.setText("No users found");
}
Change some code in adapter (comment some code)
public void setData(List<User> data) {
// clear();
if (data != null) {
addAll(data);
// notifyDataSetChanged();
}
}
Update:(problem resolved by comments this line)
mListViewTimeline.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
I hope this will help you.
Related
I referred [this][1] and [this][2] site and tried to modify it according to my own needs. Problem is I can't remove an item from the cart. I have tried everything including searching for solutions in stackoverflow and google but no luck.
Here is my CatalogActivity.java
package com.comlu.sush.shoppingcart;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import java.util.List;
public class CatalogActivity extends AppCompatActivity {
private List<Product> mProductList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalog);
// Obtain a reference to the product catalog
mProductList = ShoppingCartHelper.getCatalog(getResources());
// Create the list
ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
listViewCatalog.setAdapter(new ProductAdapter(mProductList, getLayoutInflater(), false,false));
listViewCatalog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent productDetailsIntent = new Intent(getBaseContext(),ProductDetailsActivity.class);
productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX, position);
startActivity(productDetailsIntent);
}
});
Button viewShoppingCart = (Button) findViewById(R.id.ButtonViewCart);
viewShoppingCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent viewShoppingCartIntent = new Intent(getBaseContext(), ShoppingCartActivity.class);
startActivity(viewShoppingCartIntent);
}
});
}
}
ShoppingCartHelper.java
package com.comlu.sush.shoppingcart;
import android.content.res.Resources;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
public class ShoppingCartHelper {
public static final String PRODUCT_INDEX = "PRODUCT_INDEX";
private static List<Product> catalog;
private static Map<Product, ShoppingCartEntry> cartMap = new HashMap<Product, ShoppingCartEntry>();
public static List<Product> getCatalog(Resources res){
if(catalog == null) {
catalog = new Vector<Product>();
catalog.add(new Product("Dead or Alive", res
.getDrawable(R.drawable.first),
"Dead or Alive by Tom Clancy with Grant Blackwood", 29.99));
catalog.add(new Product("Switch", res
.getDrawable(R.drawable.second),
"Switch by Chip Heath and Dan Heath", 24.99));
catalog.add(new Product("Watchmen", res
.getDrawable(R.drawable.third),
"Watchmen by Alan Moore and Dave Gibbons", 14.99));
}
return catalog;
}
public static void setQuantity(Product product, int quantity) {
// Get the current cart entry
ShoppingCartEntry curEntry = cartMap.get(product);
// If the quantity is zero or less, remove the products
if(quantity <= 0) {
if(curEntry != null)
removeProduct(product);
return;
}
// If a current cart entry doesn't exist, create one
if(curEntry == null) {
curEntry = new ShoppingCartEntry(product, quantity);
cartMap.put(product, curEntry);
return;
}
// Update the quantity
curEntry.setQuantity(quantity);
}
public static int getProductQuantity(Product product) {
// Get the current cart entry
ShoppingCartEntry curEntry = cartMap.get(product);
if(curEntry != null)
return curEntry.getQuantity();
return 0;
}
public static void removeProduct(Product product) {
cartMap.remove(product);
}
public static List<Product> getCartList() {
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
}
return cartList;
}
}
ShoppingCartActiity.java
package com.comlu.sush.shoppingcart;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import java.util.List;
public class ShoppingCartActivity extends AppCompatActivity {
private List<Product> mCartList;
private ProductAdapter mProductAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_cart);
mCartList = ShoppingCartHelper.getCartList();
// Make sure to clear the selections
for(int i=0; i<mCartList.size(); i++) {
mCartList.get(i).selected = false;
}
// Create the list
final ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
mProductAdapter = new ProductAdapter(mCartList, getLayoutInflater(), true,true);
listViewCatalog.setAdapter(mProductAdapter);
listViewCatalog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
mProductAdapter.toggleSelection(position);
}
});
removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProductAdapter.removeSelected();
}
});
}
#Override
protected void onResume() {
super.onResume();
// Refresh the data
if(mProductAdapter != null) {
mProductAdapter.notifyDataSetChanged();
}
}
}
ProductDetailsActivity.java
package com.comlu.sush.shoppingcart;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class ProductDetailsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
final int result=0;
List<Product> catalog = ShoppingCartHelper.getCatalog(getResources());
int productIndex = getIntent().getExtras().getInt(
ShoppingCartHelper.PRODUCT_INDEX);
final Product selectedProduct = catalog.get(productIndex);
// Set the proper image and text
ImageView productImageView = (ImageView) findViewById(R.id.ImageViewProduct);
productImageView.setImageDrawable(selectedProduct.productImage);
TextView productTitleTextView = (TextView) findViewById(R.id.TextViewProductTitle);
productTitleTextView.setText(selectedProduct.title);
TextView productDetailsTextView = (TextView) findViewById(R.id.TextViewProductDetails);
productDetailsTextView.setText(selectedProduct.description);
// Update the current quantity in the cart
TextView textViewCurrentQuantity = (TextView) findViewById(R.id.textViewCurrentlyInCart);
textViewCurrentQuantity.setText("Currently in Cart: "
+ ShoppingCartHelper.getProductQuantity(selectedProduct));
// Save a reference to the quantity edit text
final EditText editTextQuantity = (EditText) findViewById(R.id.editTextQuantity);
Button addToCartButton = (Button) findViewById(R.id.ButtonAddToCart);
addToCartButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Check to see that a valid quantity was entered
int quantity = 0;
try {
quantity = Integer.parseInt(editTextQuantity.getText()
.toString());
if (quantity < 0) {
Toast.makeText(getBaseContext(),
"Please enter a quantity of 0 or higher",
Toast.LENGTH_SHORT).show();
return;
}
} catch (Exception e) {
Toast.makeText(getBaseContext(),
"Please enter a numeric quantity",
Toast.LENGTH_SHORT).show();
return;
}
// If we make it here, a valid quantity was entered
ShoppingCartHelper.setQuantity(selectedProduct, quantity);
// Close the activity
finish();
}
});
}
}
ProductAdapter.java
package com.comlu.sush.shoppingcart;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class ProductAdapter extends BaseAdapter {
private List<Product> mProductList;
private LayoutInflater mInflater;
private boolean mShowQuantity;
private boolean mShowCheckbox;
public ProductAdapter(List<Product> list, LayoutInflater inflater, boolean showQuantity, boolean showCheckbox) {
mProductList = list;
mInflater = inflater;
mShowQuantity = showQuantity;
mShowCheckbox = showCheckbox;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public Object getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewItem item;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item, null);
item = new ViewItem();
item.productImageView = (ImageView) convertView
.findViewById(R.id.ImageViewItem);
item.productTitle = (TextView) convertView
.findViewById(R.id.TextViewItem);
item.productQuantity = (TextView) convertView
.findViewById(R.id.textViewQuantity);
item.productCheckbox = (CheckBox) convertView.findViewById(R.id.CheckBoxSelected);
convertView.setTag(item);
} else {
item = (ViewItem) convertView.getTag();
}
Product curProduct = mProductList.get(position);
item.productImageView.setImageDrawable(curProduct.productImage);
item.productTitle.setText(curProduct.title);
if(!mShowCheckbox) {
item.productCheckbox.setVisibility(View.GONE);
} else {
if(curProduct.selected == true)
item.productCheckbox.setChecked(true);
else
item.productCheckbox.setChecked(false);
}
// Show the quantity in the cart or not
if (mShowQuantity) {
item.productQuantity.setText("Quantity: "
+ ShoppingCartHelper.getProductQuantity(curProduct));
} else {
// Hid the view
item.productQuantity.setVisibility(View.GONE);
}
return convertView;
}
public void toggleSelection(int position) {
Product selectedProduct = (Product) getItem(position);
if(selectedProduct.selected) { // no need to check " == true"
selectedProduct.selected = false;
}
else {
selectedProduct.selected = true;
}
notifyDataSetInvalidated();
}
public void removeSelected() {
for(int i=mProductList.size()-1; i>=0; i--) {
if(mProductList.get(i).selected) {
mProductList.remove(i);
}
}
notifyDataSetChanged();
}
private class ViewItem {
ImageView productImageView;
TextView productTitle;
TextView productQuantity;
CheckBox productCheckbox;
}
}
You should move data manipulation to the adapter, and design-wise it would make sense and might also fix the problem you're telling us.
Write this method in your ProductAdapter:
public void removeSelected() {
for(int i = mProductList.size()-1; i >= 0; i--) {
if(mProductList.get(i).selected) {
mProductList.remove(i);
}
}
notifyDataSetChanged();
}
Update your OnClickListener (in your ShoppingCartActiity of course):
removeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mProductAdapter.removeSelected();
}
});
Edit
I noticed that you aren't applying OOP's concept of encapsulation here. That is, ShoppingCartActiity shouldn't be making changes to the data which belongs to your adapter.
So, just create public methods inside the ProductAdapter for item for selection, etc and call them from ShoppingCartActiity as needed.
Copy this method in your ProductAdapter:
public void toggleSelection(int position) {
Product selectedProduct = (Product) getItem(position);
if(selectedProduct.selected) { // no need to check " == true"
selectedProduct.selected = false;
}
else {
selectedProduct.selected = true;
}
notifyDataSetInvalidated();
}
mProductAdapter.toggleSelection(position); will replace following code ShoppingCartActiity:
Product selectedProduct = mCartList.get(position);
if(selectedProduct.selected == true)
selectedProduct.selected = false;
else
selectedProduct.selected = true;
mProductAdapter.notifyDataSetInvalidated();
Edit2
The problem is that the ShoppingCartActiity takes items from ShoppingCartEntry on starting up, but it never writes back the changes to it when you remove items.
update your removeButton's onClick() to:
mProductAdapter.removeSelected();
if (product.selected) {
// set products which are remaining in the adapter
ShoppingCartHelper.setProducts(mProductAdapter.getProducts());
}
ShoppingCartHelper.setProducts() would replace the old data with the passed one:
public static void setProducts(ArrayList<Product> products) {
catalog = new Vector<Product>();
for (Product product : products) {
catalog.add(product);
}
}
mProductAdapter.getProducts() will just return the list of Products, like:
public List<Product> getProducts() {
return mProductList;
}
you just have to remove selected item from list, and after adapter.notifiyDataSetChanged() it will refresh the adapter.
removeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Loop through and remove all the products that are selected
// Loop backwards so that the remove works correctly
for(int i=mCartList.size()-1; i>=0; i--) {
if(mCartList.get(i).selected) {
mCartList.remove(i);
//mProductAdapter.removeSelected();
}
}
if(mProductAdapter!=null)
mProductAdapter.notifyDataSetChanged();
}
});
I want to display 3 textviews in autocomplete textview drop down so I'm using arryalist but when I pass arraylist to AutoCompleteTextview,nothing display in dropdown.
I print the arryalist.tostring() in logcat.and the output is
[com.novityrecharge.Beans.AutocompletetextviewGeSe#41097f28]
How to solve this
Autcocompleteadapter2.java
package com.novityrecharge.adapter;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;
import com.novityrecharge.Beans.AutocompletetextviewGeSe;
import com.novityrecharge.R;
import java.util.ArrayList;
import java.util.List;
/**
* Created by varshils on 3/26/2016.
*/
public class AutoCompleteAdapter2 extends ArrayAdapter<AutocompletetextviewGeSe> {
private Activity context;
ArrayList<AutocompletetextviewGeSe> data;
int layoutResourceId;
public AutoCompleteAdapter2(Activity context, int resource,ArrayList<AutocompletetextviewGeSe> data)
{
super(context, resource, data);
this.context = context;
this.data = data;
this.layoutResourceId = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
return getDropDownView(position, convertView, parent);
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{ // This view starts when we click the spinner.
View row = convertView;
listHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new listHolder();
holder.firm = (TextView)row.findViewById(R.id.a_firm);
holder.mob = (TextView)row.findViewById(R.id.a_mobno);
holder.mcode = (TextView)row.findViewById(R.id.a_mcode);
row.setTag(holder);
}
else
{
holder = (listHolder)row.getTag();
}
AutocompletetextviewGeSe item = data.get(position);
holder.firm.setText(item.getAfirm());
holder.mob.setText(item.getAmob());
holder.mcode.setText(item.getAmcode());
return row;
}
static class listHolder
{
TextView firm,mob,mcode;
}
}
Topuptransfer.java
package com.novityrecharge;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v4.view.GravityCompat;
import android.support.v7.app.ActionBar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import com.novityrecharge.Beans.AutocompletetextviewGeSe;
import com.novityrecharge.Beans.ResponseString;
import com.novityrecharge.CrashingReport.ExceptionHandler;
import com.novityrecharge.Interfaces.callback;
import com.novityrecharge.adapter.AutoCompleteAdapter;
import com.novityrecharge.adapter.AutoCompleteAdapter2;
import com.novityrecharge.async.AsyncTaskCommon;
import com.novityrecharge.async.AsynctaskgetBalance;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by varshils on 1/13/2016.
*/
public class TopupTransfer extends BaseActivity{
AutoCompleteTextView memberView;
ArrayList <AutocompletetextviewGeSe> name1= null;
Button btnSubmit;
String membercode2,amount;
TextInputLayout smspin_textInputLayout;
EditText amnt,smspin;;
HashMap<String,String> memberDetail;
AutoCompleteAdapter2 adapter;
DatabaseHelper db;
int amont;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.topuptransfer);
if(!(Thread.getDefaultUncaughtExceptionHandler() instanceof ExceptionHandler))
{
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
}
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#4CB5F5")));
db = new DatabaseHelper(TopupTransfer.this);
memberView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
name1 = new ArrayList<AutocompletetextviewGeSe>();
memberDetail = new HashMap<String,String>();
amnt = (EditText) findViewById(R.id.topup_amnt);
btnSubmit = (Button) findViewById(R.id.button);
smspin = (EditText) findViewById(R.id.smspin);
smspin_textInputLayout = (TextInputLayout) findViewById(R.id.topuptransfer_smspin);
if(ResponseString.getRequiredSmsPin().equals("TRUE"))
{
smspin_textInputLayout.setVisibility(View.VISIBLE);
smspin.setVisibility(View.VISIBLE);
}
else
{
smspin_textInputLayout.setVisibility(View.GONE);
smspin.setVisibility(View.GONE);
}
memberView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String text = s.toString();
Log.d("text", "" + text);
int len = text.length();
if (memberView != null)
{
if( len >= 3) {
Log.d("text", "" + text);
try {
name1 = GetList2(text);
Log.d("ADPTER LIST", name1.toString());
adapter = new AutoCompleteAdapter2(TopupTransfer.this,R.layout.autocompletetextview_layout,name1);
memberView.setAdapter(adapter);
}catch(Exception e){
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(TopupTransfer.this));
}
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(amnt.getText().toString().length() != 0)
{
amont = Integer.parseInt(amnt.getText().toString());
}
if(ResponseString.getRequiredSmsPin().equals("TRUE"))
{
String sms = smspin.getText().toString();
String rs = ResponseString.getSmspwd();
if (sms.length() == 0) {
toastValidationMessage(TopupTransfer.this, getResources().getString(R.string.plsentersmspin));
return;
}
else if (!sms.equals(rs)) {
toastValidationMessage(TopupTransfer.this, getResources().getString(R.string.pinentercorrect));
return;
}
}else if (memberView.getText().toString().length() == 0) {
toastValidationMessage(TopupTransfer.this, getResources().getString(R.string.plsenterfirm));
memberView.requestFocus();
return;
}else if (amnt.getText().toString().length() == 0) {
toastValidationMessage(TopupTransfer.this, getResources().getString(R.string.plsenteramnt));
amnt.requestFocus();
return;
}else if(amont <= 0)
{
toastValidationMessage(TopupTransfer.this, getResources().getString(R.string.plsentercrectamnt));
return;
}
String Dpattern = memberView.getText().toString();
membercode2 = BaseActivity.detailMember.get(Dpattern);
amount = amnt.getText().toString();
Log.d("topup membercode",membercode2);
try {
if (membercode2 == null) {
//Toast.makeText(TopupTransfer.this, "Firm name is not Valid", Toast.LENGTH_SHORT).show();
toastValidationMessage(TopupTransfer.this, "Firm name is not Valid");
memberView.requestFocus();
} else {
boolean con = isInternetConnected();
if (con) {
AsynctaskgetBalance asy = new AsynctaskgetBalance(TopupTransfer.this,new callback(){
public void run(String result){
if (ResponseString.getStcode().equals("0")) {
AlertDialog.Builder builder = new AlertDialog.Builder(TopupTransfer.this);
builder.setTitle(R.string.app_name);
builder.setMessage(BaseActivity.sMsg);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
BaseActivity.sMsg = "";
finish();
Intent m = new Intent(TopupTransfer.this,TopupTransfer.class);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
startActivity(m);
}
});
setOnlyBalance();
builder.show();
} else {
toastValidationMessage(TopupTransfer.this,sMsg);
}
}
} , membercode2,amount,"","BALANCE","DISCOUNT");
asy.execute("TopupTransfer");
} else {
toastValidationMessage(TopupTransfer.this,getResources().getString(R.string.checkinternet));
}
}
}catch (Exception e)
{
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(TopupTransfer.this));
}
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
case R.id.action_signout:
logout(TopupTransfer.this);
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
if (fullLayout != null && fullLayout.isDrawerOpen(GravityCompat.START)) {
fullLayout.closeDrawer(GravityCompat.START);
} else {
Intent intent = new Intent(TopupTransfer.this, HomePage.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
}
#Override
protected void onPause() {
super.onPause();
if ((BaseActivity.pleaseWaitDialog != null) && BaseActivity.pleaseWaitDialog.isShowing()) {
BaseActivity.pleaseWaitDialog.dismiss();
BaseActivity.pleaseWaitDialog = null;
}
}
}
GetList2()
ArrayList<AutocompletetextviewGeSe> GetList2(String text) {
AutocompletetextviewGeSe autogese;
ArrayList<AutocompletetextviewGeSe> arrayListtemp = new ArrayList<AutocompletetextviewGeSe>();;
Cursor cursor = db.getTimeRecordList(text, "ChildUserInfo");
if (cursor != null){
if (cursor.moveToFirst()) {
do {
autogese = new AutocompletetextviewGeSe();
autogese.setAfirm(cursor.getString(cursor.getColumnIndex("FirmName")));
autogese.setAmob(cursor.getString(cursor.getColumnIndex("MobileNumber")));
autogese.setAmcode(cursor.getString(cursor.getColumnIndex("MemberCode")));
arrayListtemp = new ArrayList<AutocompletetextviewGeSe>();
arrayListtemp.add(autogese);
} while (cursor.moveToNext());
}
}
Log.d("arraylist",arrayListtemp.toString());
return arrayListtemp;
}
iam currently doing a project in which i populate a Listview from JSON.
The JSON iam passing works perfectly and my listview shows all list values properly But problem occurs when i click on any list after 10/12th list the values which i get is repeated from the first.
The respective values are not retrieved.
I also refereed other post regarding this issue but now solved my problem.
Below is my code. I hope someone will find the solution for it.
package com.desitv.geojoy;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.widget.SearchView;
import com.desitv.geojoy.R;
import com.desitv.geojoy.adapter.LatestGridAdapter;
import com.desitv.geojoy.item.ItemLatest;
import com.desitv.geojoy.util.AlertDialogManager;
import com.desitv.geojoy.util.Constant;
import com.desitv.geojoy.util.JsonUtils;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class LatestFragment extends SherlockFragment {
ListView lsv_latest;
List<ItemLatest> arrayOfLatestMusic;
LatestGridAdapter objAdapter;
AlertDialogManager alert = new AlertDialogManager();
ArrayList<String> allListImageUrl,allListChannelCatName;
ArrayList<String> allListChannelId,allListChannelCatId,allListChannelUrl,allListChannelName,allListChannelDesc;
String[] allArrayImage,allArrayChannelCatName;
String[] allArrayChannelId,allArrayChannelCatId,allArrayChannelurl,allArrayChannelName,allArrayChannelDesc;
private ItemLatest objAllBean;
private int columnWidth;
JsonUtils util;
int textlength = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.fragment_latest, container, false);
setHasOptionsMenu(true);
lsv_latest=(ListView)rootView.findViewById(R.id.lsv_latest);
arrayOfLatestMusic=new ArrayList<ItemLatest>();
allListImageUrl=new ArrayList<String>();
allListChannelCatName=new ArrayList<String>();
allListChannelCatId=new ArrayList<String>();
allListChannelId=new ArrayList<String>();
allListChannelName=new ArrayList<String>();
allListChannelUrl=new ArrayList<String>();
allListChannelDesc=new ArrayList<String>();
allArrayImage=new String[allListImageUrl.size()];
allArrayChannelCatName=new String[allListChannelCatName.size()];
allArrayChannelId=new String[allListChannelId.size()];
allArrayChannelCatId=new String[allListChannelCatId.size()];
allArrayChannelurl=new String[allListChannelUrl.size()];
allArrayChannelName=new String[allListChannelName.size()];
allArrayChannelDesc=new String[allListChannelDesc.size()];
util=new JsonUtils(getActivity());
if (JsonUtils.isNetworkAvailable(getActivity())) {
new MyTask().execute(Constant.LATEST_URL);
} else {
showToast("No Network Connection!!!");
alert.showAlertDialog(getActivity(), "Internet Connection Error",
"Please connect to working Internet connection", false);
}
lsv_latest.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
objAllBean=arrayOfLatestMusic.get(position);
int pos=objAllBean.getId();
Intent intplay=new Intent(getActivity(),TvDetails.class);
intplay.putExtra("POSITION", pos);
intplay.putExtra("CHANNEL_IMAGE", allArrayImage);
intplay.putExtra("CHANNEL_CATNAME", allArrayChannelCatName);
intplay.putExtra("CHANNEL_CATID", allArrayChannelCatId);
intplay.putExtra("CHANNEL_URL", allArrayChannelurl);
intplay.putExtra("CHANNEL_NAME", allArrayChannelName);
intplay.putExtra("CHANNEL_CID", allArrayChannelId);
intplay.putExtra("CHANNEL_DISCRIPTION", allArrayChannelDesc);
startActivity(intplay);
}
});
return rootView;
}
private class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
if (null == result || result.length() == 0) {
showToast("Server Connection Error");
alert.showAlertDialog(getActivity(), "Server Connection Error",
"May Server Under Maintaines Or Low Network", false);
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.LATEST_ARRAY_NAME);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
ItemLatest objItem = new ItemLatest();
objItem.setId(objJson.getInt(Constant.CHANNEL_ID));
objItem.setCategoryId(objJson.getInt(Constant.CHANNEL_CATID));
objItem.setCategoryName(objJson.getString(Constant.CHANNEL_CAT_NAME));
objItem.setChannelName(objJson.getString(Constant.LATEST_CHANNEL_NAME));
objItem.setChannelUrl(objJson.getString(Constant.lATETST_CHANNEL_URL));
objItem.setDescription(objJson.getString(Constant.LATEST_CHANNEL_DESCRIPTION));
objItem.setImage(objJson.getString(Constant.LATEST_CHANNEL_IMAGE));
arrayOfLatestMusic.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
for(int j=0;j<arrayOfLatestMusic.size();j++)
{
objAllBean=arrayOfLatestMusic.get(j);
allListImageUrl.add(objAllBean.getImage());
allArrayImage=allListImageUrl.toArray(allArrayImage);
allListChannelCatName.add(objAllBean.getCategoryName());
allArrayChannelCatName=allListChannelCatName.toArray(allArrayChannelCatName);
allListChannelId.add(String.valueOf(objAllBean.getId()));
allArrayChannelId=allListChannelId.toArray(allArrayChannelId);
allListChannelCatId.add(String.valueOf(objAllBean.getCategoryId()));
allArrayChannelCatId=allListChannelCatId.toArray(allArrayChannelCatId);
allListChannelUrl.add(String.valueOf(objAllBean.getChannelUrl()));
allArrayChannelurl=allListChannelUrl.toArray(allArrayChannelurl);
allListChannelName.add(String.valueOf(objAllBean.getChannelName()));
allArrayChannelName=allListChannelName.toArray(allArrayChannelName);
allListChannelDesc.add(objAllBean.getDescription());
allArrayChannelDesc=allListChannelDesc.toArray(allArrayChannelDesc);
}
setAdapterToListview();
}
}
}
public void setAdapterToListview() {
objAdapter = new LatestGridAdapter(getActivity(), R.layout.latest_lsv_item,
arrayOfLatestMusic,columnWidth);
lsv_latest.setAdapter(objAdapter);
}
public void showToast(String msg) {
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_search, menu);
final SearchView searchView = (SearchView) menu.findItem(R.id.search)
.getActionView();
final MenuItem searchMenuItem = menu.findItem(R.id.search);
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(!hasFocus) {
searchMenuItem.collapseActionView();
searchView.setQuery("", false);
}
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
textlength=newText.length();
arrayOfLatestMusic.clear();
for(int i=0;i< allArrayChannelName.length;i++)
{
if(textlength <= allArrayChannelName[i].length())
{
if(newText.toString().equalsIgnoreCase((String) allArrayChannelName[i].subSequence(0, textlength)))
{
ItemLatest objItem = new ItemLatest();
objItem.setId(Integer.parseInt(allArrayChannelId[i]));
objItem.setCategoryId(Integer.parseInt(allArrayChannelCatId[i]));
objItem.setCategoryName(allArrayChannelCatName[i]);
objItem.setDescription(allArrayChannelDesc[i]);
objItem.setImage(allArrayImage[i]);
objItem.setChannelName(allArrayChannelName[i]);
objItem.setChannelUrl(allArrayChannelurl[i]);
arrayOfLatestMusic.add(objItem);
}
}
}
setAdapterToListview();
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
// Do something
return true;
}
});
}
}
LatestGridAdapter code
package com.desitv.geojoy.adapter;
import java.util.List;
import com.desitv.geojoy.R;
import com.desitv.geojoy.imageloader.ImageLoader;
import com.desitv.geojoy.item.ItemLatest;
import com.desitv.geojoy.util.Constant;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class LatestGridAdapter extends ArrayAdapter<ItemLatest>{
private Activity activity;
private List<ItemLatest> itemsLatest;
private ItemLatest objLatestBean;
private int row;
public ImageLoader imageLoader;
public LatestGridAdapter(Activity act, int resource, List<ItemLatest> arrayList, int columnWidth) {
super(act, resource, arrayList);
this.activity = act;
this.row = resource;
this.itemsLatest = arrayList;
imageLoader=new ImageLoader(activity);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(row, null);
holder = new ViewHolder();
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
if ((itemsLatest == null) || ((position + 1) > itemsLatest.size()))
return view;
objLatestBean = itemsLatest.get(position);
holder.imgv_latetst=(ImageView)view.findViewById(R.id.picture);
holder.name=(TextView)view.findViewById(R.id.text);
holder.txt_category=(TextView)view.findViewById(R.id.text_category);
imageLoader.DisplayImage(Constant.SERVER_IMAGE_UPFOLDER_THUMB+objLatestBean.getImage().toString(), holder.imgv_latetst);
holder.name.setText(objLatestBean.getChannelName().toString());
holder.txt_category.setText(objLatestBean.getCategoryName().toString());
return view;
}
public class ViewHolder {
public ImageView imgv_latetst;
public TextView name,txt_category;
}
}
I have developed a Contacts application. It does everything that a normal contacts application should does. There is always a chance of improvement. I had noticed in Android Emulator that loading for contact images starts when user has settled, he has scrolled the contact list to the area where there are chances are good that he would get contact he is searching for. So, I tried to implement the same thing on my app copy. I have implemented it. Its running very very slow. As I presume, I believe that application is running the thread multiple time even if it has retrieved the image which leads to big lagging. I am aware of the ASync task but just out of curiosity and to check whether it can be done, I don't wish to implement it here. Here is the source code for MainActivity.
package com.example.contact;
import java.io.InputStream;
import java.util.ArrayList;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
public class MainActivity extends ListActivity {
ListView listview;
private boolean mPaused;
private MyAdapter mAdapter;
private View view;
private boolean running = false;
final private ArrayList<String> con_ids = new ArrayList<String>();
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listview = getListView();
context = this;
Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
null,
null,
null,
ContactsContract.Contacts.DISPLAY_NAME+" ASC");
if(c!=null)
{
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
con_ids.add(c.getString(c.getColumnIndex(ContactsContract.Contacts._ID)));
}
}
mAdapter = new MyAdapter(this, android.R.layout.simple_list_item_1, con_ids);
listview.setAdapter(mAdapter);
listview.setOnScrollListener(makeScrollListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void setEnabled(boolean enabled) {
mPaused = !enabled;
}
private AbsListView.OnScrollListener makeScrollListener() {
return new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
setEnabled(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
running = false;
}
#Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
String log = "";
Log.d(log, "Scroll First Item" + i);
Log.d(log, ""+ listview.getChildCount());
final int want = i;
running = true;
runOnUiThread(new Thread(new Runnable() {
int totalChild = listview.getChildCount();
int first = listview.getFirstVisiblePosition() - listview.getHeaderViewsCount();
int toRetrieve = want-first;
int id;
long con_id;
Bitmap thumbnail;
final ListView list = listview;
#Override
public void run() {
// TODO Auto-generated method stub
while(running)
{
if(!(toRetrieve<0||toRetrieve>=totalChild))
{
id = want+toRetrieve;
con_id = Long.valueOf(con_ids.get(id));
Uri ContactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, con_id);
InputStream stream = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(), ContactUri);
thumbnail = BitmapFactory.decodeStream(stream);
if(thumbnail == null)
{
toRetrieve++;
continue;
}
else
{
View view = list.getChildAt(toRetrieve);
if(view == null)
{
toRetrieve++;
continue;
}
else
{
ImageView iamge = (ImageView) view.findViewById(R.id.contact_iamge);
iamge.setImageBitmap(thumbnail);
}
toRetrieve++;
}
}
else
{
running = false;
}
}
}
}));
}
};
}
}
Code for MyAdapter,
package com.example.contact;
import java.util.ArrayList;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MyAdapter extends ArrayAdapter<String> {
private Context context;
private ListView listview;
private ArrayList<String> ids;
private LayoutInflater infl;
private String displayname;
private String maindetail;
private SimplifiedContact contact;
private Drawable drawable;
public MyAdapter(Context context, int ResourceId, ArrayList<String> list)
{
super(context, ResourceId, list);
this.context = context;
ids = list;
infl = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
drawable = context.getResources().getDrawable(R.drawable.person);
}
static class ViewHolder
{
public ImageView image;
public TextView display_name;
public TextView main_detail;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
contact = new SimplifiedContact(context, Long.valueOf(ids.get(position)));
if(row == null)
{
row = infl.inflate(R.layout.single_cell, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.display_name =(TextView) row.findViewById(R.id.disp_name);
viewHolder.main_detail = (TextView) row.findViewById(R.id.main_detail);
viewHolder.image = (ImageView)row.findViewById(R.id.contact_iamge);
row.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) row.getTag();
holder.display_name.setText(contact.getDisplayName());
holder.main_detail.setText(contact.getMainDetail());
holder.image.setBackgroundDrawable(drawable);
return row;
}
}
I wish to know, how this lag can be reduced. Thanks in advance.
Why don't you try to take that Thread instance that you are making in runOnUiThread and put It in a field, initializing It in the onCreate. I think that you are creating several thread instaces with no use.
public class MainActivity extends ListActivity {
ListView listview;
private boolean mPaused;
private MyAdapter mAdapter;
private View view;
private boolean running = false;
final private ArrayList<String> con_ids = new ArrayList<String>();
private Context context;
Thread uiThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listview = getListView();
context = this;
Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
null,
null,
null,
ContactsContract.Contacts.DISPLAY_NAME+" ASC");
if(c!=null)
{
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
con_ids.add(c.getString(c.getColumnIndex(ContactsContract.Contacts._ID)));
}
}
uiThread = new Thread(new Runnable() {
int totalChild = listview.getChildCount();
int first = listview.getFirstVisiblePosition() - listview.getHeaderViewsCount();
int toRetrieve = want-first;
int id;
long con_id;
Bitmap thumbnail;
final ListView list = listview;
#Override
public void run() {
// TODO Auto-generated method stub
while(running)
{
if(!(toRetrieve<0||toRetrieve>=totalChild))
{
id = want+toRetrieve;
con_id = Long.valueOf(con_ids.get(id));
Uri ContactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, con_id);
InputStream stream = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(), ContactUri);
thumbnail = BitmapFactory.decodeStream(stream);
if(thumbnail == null)
{
toRetrieve++;
continue;
}
else
{
View view = list.getChildAt(toRetrieve);
if(view == null)
{
toRetrieve++;
continue;
}
else
{
ImageView iamge = (ImageView) view.findViewById(R.id.contact_iamge);
iamge.setImageBitmap(thumbnail);
}
toRetrieve++;
}
}
else
{
running = false;
}
}
}
});
mAdapter = new MyAdapter(this, android.R.layout.simple_list_item_1, con_ids);
listview.setAdapter(mAdapter);
listview.setOnScrollListener(makeScrollListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void setEnabled(boolean enabled) {
mPaused = !enabled;
}
private AbsListView.OnScrollListener makeScrollListener() {
return new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
setEnabled(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
running = false;
}
#Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
String log = "";
Log.d(log, "Scroll First Item" + i);
Log.d(log, ""+ listview.getChildCount());
final int want = i;
running = true;
runOnUiThread(uiThread);
}
};
}
}
I came across a nice filterable listview tutorial and I was wondering how to determine what listview item is selected and display a toast. Here is the code:
package com.example.listview;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
public class TestFilterListView extends Activity {
FrameLayout historyContainer;
ViewStub viewStub;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.history_container);
historyContainer = (FrameLayout) findViewById(R.id.historyContainerLayout);
EditText filterEditText = (EditText) findViewById(R.id.filter_text);
filterEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
historyContainer.removeAllViews();
final List<String> tempHistoryList = new ArrayList<String>();
tempHistoryList.addAll(historyList);
for(String data : historyList) {
if(data.indexOf((s.toString())) == -1) {
tempHistoryList.remove(data);
}
}
viewStub = new ViewStub(TestFilterListView.this, R.layout.history_schedule);
viewStub.setOnInflateListener(new ViewStub.OnInflateListener()
{
public void onInflate(ViewStub stub, View inflated)
{
setUIElements(inflated, tempHistoryList);
}
});
historyContainer.addView(viewStub);
viewStub.inflate();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
setViewStub();
}
/********************************************************************************************************/
private void setViewStub()
{
historyList.add("first");
historyList.add("second");
historyList.add("third");
historyList.add("fourth");
historyList.add("fifth");
historyList.add("sixth");
historyList.add("seventh");
viewStub = new ViewStub(TestFilterListView.this, R.layout.history_schedule);
viewStub.setOnInflateListener(new ViewStub.OnInflateListener()
{
public void onInflate(ViewStub stub, View inflated)
{
setUIElements(inflated, historyList);
}
});
historyContainer.addView(viewStub);
viewStub.inflate();
}
/********************************************************************************************************/
final List<String> historyList = new ArrayList<String>();
String displayName = "";
ListView historyListView;
private void setUIElements(View v, List<String> historyLists)
{
if (v != null)
{
historyScheduleData.clear();
//historyList.clear();
historyScheduleData.addAll(historyLists);
historyListView = (ListView) findViewById(R.id.historylist);
historyListView.setAdapter(new BeatListAdapter(this));
registerForContextMenu(historyListView);
}
}
private static class BeatListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public BeatListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return historyScheduleData.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.history_list_view, null);
holder = new ViewHolder();
holder.historyData = (TextView) convertView
.findViewById(R.id.historytext);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.historyData.setText(historyScheduleData.get(position));
return convertView;
}
static class ViewHolder {
TextView historyData;
}
}
private static final List<String> historyScheduleData = new ArrayList<String>();
}
I thought about using
protected void onListItemClick(ListView l, View v, int position, long id) {
if(position == 0) {
Intent intent = new Intent(getApplicationContext(), GODoc1Activity.class);
startActivity(intent);
But when I try to implement it, it does not work. Am I missing something here? How do I go about doing this?
you tried this?: (in the onCreate)
historyListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
//your code
}
});
If you are trying to find the selected item in your ListView:
listView.getAdapter().getItem(listView.getCheckedItemPosition());
Take a look at the documentation here for more information http://developer.android.com/reference/android/widget/AbsListView.html#getCheckedItemPosition%28%29