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;
}
Related
I have been using firebase for my app, all works fine, however, I recently updated my UI, by adding this library, the other data in my listview but this library's view does not update, can someone please help me with this, and there's one more issue with my code, when I update the status, i.e the library's view, only the selected items view should be updated, instead all the views in my list get updated, say if I select "Received" for one item in the list, all others get updated to "Received", this does not reflect in the firebase console, and when I re open the app, everything will fixed. Please assist me with this. Here' my git repository link if needed.
AddOrUpdateItem.java
package com.fayaz.uniabex;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class AddOrUpdateItem extends AppCompatActivity implements OnItemSelectedListener {
Button bOK,bCancel;
Item item;
int position;
EditText iName,iPono,iQty,iSupplier,iContact,iTranport,iLrno,iRemarks;
CoordinatorLayout cl;
public Spinner spinner;
String status, selectedStatus;
public ArrayAdapter<String> dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_or_update_item);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
position = getIntent().getIntExtra("Position", -1);
cl = (CoordinatorLayout) findViewById(R.id.cdlayout);
final Intent intent = new Intent(AddOrUpdateItem.this, MainActivity.class);
iName= (EditText) findViewById(R.id.iName);
iPono = (EditText) findViewById(R.id.iPoNo);
iQty = (EditText) findViewById(R.id.iQty);
iSupplier = (EditText) findViewById(R.id.iSupplier);
iContact = (EditText) findViewById(R.id.iContact);
iTranport = (EditText) findViewById(R.id.iTransport);
iLrno = (EditText) findViewById(R.id.iLrno);
iRemarks = (EditText) findViewById(R.id.iRemarks);
// Spinner element
spinner = (Spinner) findViewById(R.id.status);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories = new ArrayList<String>();
categories.add("Enquiry");
categories.add("Quotation");
categories.add("Po Rel");
categories.add("Dispatched");
categories.add("Received");
// Creating adapter for spinner
dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
bOK = (Button) findViewById(R.id.bOk);
bCancel = (Button) findViewById(R.id.bCancel);
if(position != -1) {
getSupportActionBar().setTitle("Edit Entry");
searchPerson(position);
item = new Item();
}
else {
getSupportActionBar().setTitle("Add Entry");
item = null;
}
bOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String test = iRemarks.getText().toString();
Item i = new Item();
i.setItem(iName.getText().toString());
i.setPonum(iPono.getText().toString());
i.setQty(iQty.getText().toString());
i.setSupplier(iSupplier.getText().toString());
i.setContact(iContact.getText().toString());
i.setTransporter(iTranport.getText().toString());
i.setLrnum(iQty.getText().toString());
i.setStatus(selectedStatus);
if(test.equals("\n")){
i.setRemarks(iRemarks.getText().toString());
}
else{
i.setRemarks(iRemarks.getText().toString() + "\n");
}
if (item == null)
MainActivity.getInstance().addItem(i);
else
MainActivity.getInstance().updateItemDetails(i, position);
finish();
}
});
bCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
public void searchPerson(int position) {
String clickedKey = MainActivity.getInstance().getKeysArray().get(position);
MainActivity.getInstance().getmDatabase().child(clickedKey).addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user value
String test = iRemarks.getText().toString();
Item person = dataSnapshot.getValue(Item.class);
iName.setText(person.getItem());
iPono.setText(person.getPonum());
iSupplier.setText(person.getSupplier());
iQty.setText(person.getQty());
iTranport.setText(person.getTransporter());
iContact.setText(person.getContact());
iLrno.setText(person.getLrnum());
spinner.setSelection(dataAdapter.getPosition(person.getStatus()));
if(test.equals("\n")){
iRemarks.setText(person.getRemarks());
}
else{
iRemarks.setText(person.getRemarks() + "\n");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
finish(); // close this activity and return to preview activity (if there is any)
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
status = parent.getItemAtPosition(position).toString();
selectedStatus = Integer.toString(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
ItemDetailsAdapter.java
package com.fayaz.uniabex;
/**
* Created by Fayaz on 21/12/2016.
*/
import android.widget.BaseAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.anton46.stepsview.StepsView;
import java.util.ArrayList;
public class ItemDetailsAdapter extends BaseAdapter {
private ArrayList<Item> arrayListItem;
private Context context;
private LayoutInflater inflater;
public String curStatus;
public ItemDetailsAdapter(Context context, ArrayList<Item> arrayListItem) {
this.context = context;
this.arrayListItem = arrayListItem;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return arrayListItem.size();
}
#Override
public Object getItem(int position) {
return arrayListItem.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final String[] labels = {"Enq", "Qtn", "PO", "Dspd", "Rcvd"};
View v = convertView;
Holder holder;
if (v == null) {
v = inflater.inflate(R.layout.list_item, null);
holder = new Holder();
holder.ItemName = (TextView) v.findViewById(R.id.ItemNametv);
holder.qty = (TextView) v.findViewById(R.id.qtytv);
holder.EditItem = (Button) v.findViewById(R.id.EditItem);
holder.DeleteItem = (Button) v.findViewById(R.id.DeleteItem);
holder.mStepsView = (StepsView) v.findViewById(R.id.stepsView);
curStatus = arrayListItem.get(position).getStatus();
int n = Integer.parseInt(curStatus);
holder.mStepsView.setLabels(labels)
.setBarColorIndicator(context.getResources().getColor(R.color.material_blue_grey_800))
.setProgressColorIndicator(context.getResources().getColor(R.color.colorPrimary))
.setLabelColorIndicator(context.getResources().getColor(R.color.colorPrimaryDark))
.setCompletedPosition(n)
.drawView();
v.setTag(holder);
} else {
holder = (Holder) v.getTag();
}
holder.ItemName.setText("Item: " + arrayListItem.get(position).getItem());
holder.qty.setText("Qty: " + arrayListItem.get(position).getQty());
holder.EditItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,AddOrUpdateItem.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("Position", position);
context.getApplicationContext().startActivity(intent);
}
});
holder.DeleteItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ShowConfirmDialog(context, position);
}
});
return v;
}
class Holder {
TextView ItemName,qty;
Button DeleteItem, EditItem;
StepsView mStepsView;
}
public static void ShowConfirmDialog(Context context, final int position) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder
.setMessage("Are you sure you want to delete this entry?")
.setCancelable(true)
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.getInstance().deleteItem(position);
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
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 am using custom listViewAdapter class and I want to check one box in a single row, but it is checking multiple checks in multiple rows which is not my requirement. Please tell me how can I resolve it.
CourseActivity.java
package com.technerdshub.vusocial.Activities;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.SaveCallback;
import com.technerdshub.vusocial.DBHelper;
import com.technerdshub.vusocial.Models.Course;
import com.technerdshub.vusocial.Models.StudyProgramModel;
import com.technerdshub.vusocial.Models.User;
import com.technerdshub.vusocial.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class CourseActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ListView list;
EditText editsearch;
ArrayList arrayList = new ArrayList();
CourseViewAdapter adapter;
Course courseObject;
boolean isChecked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.course_activity);
List<Course> courseList;
DBHelper db = new DBHelper(this);
courseList = db.getAllCourses();
list = (ListView) findViewById(R.id.listview1);
for (Course c : courseList) {
arrayList.add(c);
}
adapter = new CourseViewAdapter(this, arrayList);
adapter.courseActivity = this;
list.setAdapter(adapter);
editsearch = (EditText) findViewById(R.id.searchF);
editsearch.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 = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void afterTextChanged(Editable s) {
}
});
User user = User.getInstance();
saveUserOnParse(user);
}
private void saveUserOnParse(User user) {
ParseObject parseUser = new ParseObject("UserData");
parseUser.put("name", user.getName());
parseUser.put("vuId", user.getVuId());
parseUser.put("studyProgram", user.getStudyProgram());
parseUser.put("facebookId", user.getFacebookId());
parseUser.put("facebookEmail", user.getFacebookEmail());
parseUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
// Intent i = new Intent(getContext(), StudentDashboardActivity.class);
//// i.putExtra("E-mail", "abc");
// startActivity(i);
} else {
Toast temp = Toast.makeText(CourseActivity.this, "Data is not saved.", Toast.LENGTH_SHORT);
temp.show();
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 4
if (requestCode == 2) {
courseObject = (Course) data.getExtras().getSerializable("SelectedCourse");
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) view.findViewById(R.id.checkBox);
// TextView tv = (TextView) v.findViewById(R.id.textView1);
cb.performClick();
if (cb.isChecked()) {
// checkedValue.add(tv.getText().toString());
} else if (!cb.isChecked()) {
// checkedValue.remove(tv.getText().toString());
}
}
}
CourseViewAdapter.java
package com.technerdshub.vusocial.Activities;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import com.technerdshub.vusocial.Models.Course;
import com.technerdshub.vusocial.Models.StudyProgramModel;
import com.technerdshub.vusocial.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Created by Saroosh on 7/16/2016.
*/
public class CourseViewAdapter extends BaseAdapter {
protected CourseActivity courseActivity;
Context mContext;
LayoutInflater inflater;
private List<Course>worldpopulationlist=null;
private ArrayList<Course> arraylist;
public CourseViewAdapter(Context context, List<Course>worldpopulationlist){
mContext = context;
this.worldpopulationlist = worldpopulationlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<Course>();
this.arraylist.addAll(worldpopulationlist);
}
public class ViewHolder {
TextView courseCode;
TextView courseName;
CheckBox checkBox;
}
#Override
public int getCount() {
return worldpopulationlist.size();
}
#Override
public Course getItem(int position) {
return worldpopulationlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.c_list_item, null);
// Locate the TextViews in listview_item.xml
holder.courseName = (TextView) view.findViewById(R.id.course_name);
holder.courseCode = (TextView) view.findViewById(R.id.course_code);
holder.checkBox= (CheckBox) view.findViewById(R.id.checkBox);
// holder.duration = (TextView) view.findViewById(R.id.program_duration);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.courseName.setText(worldpopulationlist.get(position).getCourseName());
holder.courseCode.setText(worldpopulationlist.get(position).getCourseCode());
//holder.duration.setText(worldpopulationlist.get(position).getDuration());
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, CourseActivity.class);
// Pass all data ran
intent.putExtra("SelectedCourse", worldpopulationlist.get(position));
// Pass all data country
courseActivity.setResult(2,intent);
courseActivity.finish();
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
}
else
{
for (Course wp : arraylist)
{
if (wp.getCourseName().toLowerCase(Locale.getDefault()).contains(charText))
{
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Write all your checkbox logic inside you adapter getView method. That will work .
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.
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;
}
}