EditText show in a ListView - android

public class MainActivity extends Activity {
Button okButton;
EditText wishEditText;
ListView wishListView;
BaseAdapter adapter;
ArrayList<list_item>arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 0);
setContentView(R.layout.activity_main);
initializedAll();
}
public void initializedAll() {
okButton = (Button) findViewById(R.id.button1);
wishEditText = (EditText) findViewById(R.id.editText1);
wishListView = (ListView) findViewById(R.id.listView1);
arrayList = new ArrayList<list_item>();
adapter = new BaseAdapter() {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public View getView(int position, View view, ViewGroup viewGroupgroup) {
if (view==null) {
view = inflater.inflate(R.layout.wish_list_item, null);
}
TextView wishText = (TextView) findViewById(R.id.wishItemtextView);
TextView dateText = (TextView) findViewById(R.id.wishDatetextView);
wishText.setText(arrayList.get(position).getWishString());
Date date = arrayList.get(position).getDate();
dateText.setText(DateFormat.format("dd/MM/yyyy HH:mm:ss a", date));
return view;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayList.get(position);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
};
wishListView.setAdapter(adapter);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String string = wishEditText.getText().toString();
Date date = new Date();
list_item item = new list_item(date,string);
arrayList.add(item);
adapter.notifyDataSetChanged();
wishEditText.setText("");
InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(wishEditText.getWindowToken(), 0);
Toast.makeText(getBaseContext(), "New wish Added To List", Toast.LENGTH_SHORT);
}
});
};
}
Please help me.
When I pressed OK button then my apps has stop but there is no error even eclipse do't show any error.
How I can solve it?
Please help me.

This like inputMethodManager.hideSoftInputFromWindow(wishEditText.getWindowToken(), 0); might be giving you a NullPointerException

Try this way,hope this will help you to solve your problem.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="5dp">
<EditText
android:id="#+id/edtWishText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<Button
android:id="#+id/btnAddWishText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Add"/>
</LinearLayout>
<ListView
android:id="#+id/lstWish"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:divider="#android:color/white"
android:dividerHeight="1dp"/>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="#+id/txtWishText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/txtWishDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"/>
</LinearLayout>
public class MainActivity extends Activity{
private ListView lstWish;
private EditText edtWishText;
private Button btnAddWishText;
private WishListAdapter listAdapter;
private ArrayList<HashMap<String,Object>> wishList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 0);
setContentView(R.layout.activity_main);
lstWish = (ListView) findViewById(R.id.lstWish);
edtWishText = (EditText) findViewById(R.id.edtWishText);
btnAddWishText = (Button) findViewById(R.id.btnAddWishText);
wishList =new ArrayList<HashMap<String, Object>>();
listAdapter = new WishListAdapter(this,wishList);
lstWish.setAdapter(listAdapter);
btnAddWishText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(edtWishText.getText() == null && edtWishText.getText().toString().length()<=0){
edtWishText.setError("Value required");
}else{
HashMap<String,Object> data = new HashMap<String, Object>();
data.put("WishText",edtWishText.getText().toString());
data.put("WishText",new Date());
wishList.add(data);
listAdapter.notifyDataSetChanged();
edtWishText.setText("");
((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(edtWishText.getWindowToken(), 0);
Toast.makeText(getBaseContext(), "New wish Added To List", Toast.LENGTH_SHORT).show();
}
}
});
}
class WishListAdapter extends BaseAdapter{
private Context mContext;
public ArrayList<HashMap<String,Object>> wishList;
public WishListAdapter(Context mContext,ArrayList<HashMap<String,Object>> wishList)
{
this.mContext = mContext;
this.wishList = wishList;
}
#Override
public int getCount(){
return wishList.size();
}
#Override
public Object getItem(int position)
{
return wishList.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item,null,false);
holder.txtWishText = (TextView) convertView.findViewById(R.id.txtWishText);
holder.txtWishDate = (TextView) convertView.findViewById(R.id.txtWishDate);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.txtWishText.setText(wishList.get(position).get("wishText").toString());
holder.txtWishDate.setText(DateFormat.format("dd/MM/yyyy HH:mm:ss a",(Date)wishList.get(position).get("WishDate")));
return convertView;
}
}
public static class ViewHolder
{
public TextView txtWishText;
public TextView txtWishDate;
}
}

Related

Delete Button In CustomAdapter ListView

I'm trying to make a ToDo List App in Android. Here Is My code
MainActivity.java
import com.vrishankgupta.adapter.myPkg.listClass;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<listClass> arr = new ArrayList<listClass>(0);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arr.add(new listClass("Task 1",false));
arr.add(new listClass("Task 2",true));
arr.add(new listClass("Task 3",true));
arr.add(new listClass("Task 4",false));
final CustomAdapter adapter = new CustomAdapter(this,arr);
final ListView lv = findViewById(R.id.vishulv);
Log.e("Task 1", arr.get(0).isActive()+"" );
lv.setAdapter(adapter);
final EditText etnew = findViewById(R.id.etNew);
Button add = findViewById(R.id.addButn);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(etnew.getText()==null || etnew.getText().toString().equals(""))
{
Toast.makeText(getApplicationContext(),"Enter data",Toast.LENGTH_LONG).show();
}
else
{
arr.add(new listClass(etnew.getText().toString(),false));
CustomAdapter adapter = new CustomAdapter(MainActivity.this,arr);
final ListView lv = findViewById(R.id.vishulv);
lv.setAdapter(adapter);
etnew.setText("");
}
}
});
}
}
CustomAdapter
package com.vrishankgupta.adapter;
public class CustomAdapter extends ArrayAdapter<listClass> {
ArrayList<listClass> arr;
public CustomAdapter(#NonNull Context context, ArrayList<listClass> arr) {
super(context,R.layout.detail, arr);
this.arr = new ArrayList<listClass>(0);
this.arr.addAll(arr);
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull final ViewGroup parent) {
final ViewHolder holder;
if(convertView == null)
{
holder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.detail,parent,false);
holder.textview = (TextView)convertView.findViewById(R.id.todoTaskTV);
holder.checkBox = (CheckBox)convertView.findViewById(R.id.checkBut);
holder.button = (Button)convertView.findViewById(R.id.delBut);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
listClass task = arr.get(position);
Log.e("Checking", position + task.getTask().toString() );
holder.textview.setText(task.getTask());
holder.checkBox.setChecked(task.isActive());
holder.checkBox.setTag(task);
holder.button.setTag(task);
notifyDataSetChanged();
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox)v;
listClass task = (listClass) cb.getTag();
Toast.makeText(getContext(),"Checkbox",Toast.LENGTH_LONG).show();
task.setActive(cb.isChecked());
Log.e("isActive Task1", arr.get(1).isActive() +"" );
}
});
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button im = (Button) v;
listClass task = (listClass) im.getTag(R.id.delBut);
arr.remove(task);
Log.e("Del but",position + "");
Toast.makeText(getContext(),"Del",Toast.LENGTH_LONG).show();
}
});
Log.e("isActive Task1", arr.get(1).isActive() +"" );
return convertView;
}
}
ViewHolder Class
public class ViewHolder {
TextView textview;
Button button;
CheckBox checkBox;
}
listClass
public class listClass {
String task;
boolean active;
public listClass(String task, boolean active) {
this.task = task;
this.active = active;
}
public String getTask() {
return task;
}
public void setTask(String task) {
this.task = task;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.vrishankgupta.adapter.MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Enter New Task"
android:id="#+id/etNew"
android:textSize="24sp"
android:layout_gravity="left"
android:gravity="left"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="ADD"
android:id="#+id/addButn"
android:textSize="24sp"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/vishulv"
android:layout_marginTop="94dp"
/>
</FrameLayout>
detail.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="left"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="#+id/todoTaskTV"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:paddingLeft="8dp"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/delBut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Delete"
android:layout_marginRight="5dp"
/>
<CheckBox
android:id="#+id/checkBut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/delBut"
android:layout_centerVertical="true"
android:layout_marginRight="10dp" />
</RelativeLayout>
I want to remove List element on Click of Delete Button or toggle the status of task with checkBox,I'm not even seeing the Toast that is present in clickListener of Checkbox and Delete Button,there's just nothing happening, unable to figure out how to do that..
Make a Callback interface to solve your problem. I think this the best way what you want to achieve.
OnItemClickListener
public class OnItemClickListener implements View.OnClickListener {
private int position;
private OnItemClickCallback onItemClickCallback;
public OnItemClickListener(int position, OnItemClickCallback
onItemClickCallback) {
this.position = position;
this.onItemClickCallback = onItemClickCallback;
}
#Override
public void onClick(View view) {
onItemClickCallback.onItemClicked(view, position);
}
public interface OnItemClickCallback {
void onItemClicked(View view, int position);
}
}
In your adapter class
private OnItemClickListener.OnItemClickCallback onItemClickCallback;
public CustomAdapter(#NonNull Context context, ArrayList<listClass> arr,
OnItemClickListener.OnItemClickCallback onItemClickCallback)
{
super(context,R.layout.detail, arr);
this.arr = new ArrayList<listClass>(0);
this.onItemClickCallback = onItemClickCallback;
this.arr.addAll(arr);
}
and
holder.imageButton.setOnClickListener(new OnItemClickListener(position,
onItemClickCallback));
In your activity
private OnItemClickListener.OnItemClickCallback
onItemDeleteClickCallback = new
OnItemClickListener.OnItemClickCallback() {
#Override
public void onItemClicked(View view, int position) {
//here you will get delete item pos
}
};
and
CustomAdapter adapter = new CustomAdapter(MainActivity.this, arr,
onItemDeleteClickCallback );
final ListView lv = findViewById(R.id.vishulv);
lv.setAdapter(adapter);
Hope this will help you.
Try this in your adapter
holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.isChecked()) {
//checked
Toast.makeText(getContext(),"active checkbox",Toast.LENGTH_LONG).show();
}
else
{
//not checked
Toast.makeText(getContext(),"inactive checkbox",Toast.LENGTH_LONG).show();
}
});

Android OnClickListener not working with custom adapter

I've made a custom adapter for a ListView in order to display a String and an ImageButton within the same row. A row is generated every time the add button is clicked. The string is taken from the EditText field, while the ImageButton bin_button is allocated dinamically. Everything works fine except I can't make the bin_buttons fire an OnClick event.
I've tried several solutions. Here bin_button_listener is generated outside the add_button OnClickListener and then set. I've also tried to set listeners with a new OnClickListener every time a new bin_button was created.
Here some code:
Row layout list_string_button_layout.xml:
<TextView
android:id="#+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingStart="8dp"
android:paddingEnd="0dp"
android:paddingTop="8dp"
android:textSize="18sp"
android:textStyle="bold"/>
<ImageButton
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingEnd="5dp"
android:background="#00ffffff"
android:src="#drawable/ic_delete_black_18dp"
android:layout_alignBottom="#+id/list_item_string"
android:layout_alignParentEnd="true"
android:focusableInTouchMode="true"
/>
</RelativeLayout>
Activity layout activity_search.xml:
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ingredient_text_input"
android:hint="#string/start_typing_ingredient"
android:layout_marginTop="52dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
/>
<Button
style="#style/Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/add_button"
android:backgroundTint="#color/colorPrimaryLight"
android:id="#+id/add_button"
android:layout_alignTop="#+id/ingredient_text_input"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ingredients_view"
android:layout_above="#+id/search_button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/add_button" />
</RelativeLayout>
Custom Adapter IngredientBinAdapter:
public class IngredientBinAdapter extends BaseAdapter {
private Context context = null;
private List<HashMap<String,ImageButton>> items = new ArrayList<>();
public IngredientBinAdapter(Context context, ArrayList<HashMap<String,ImageButton>> items){
this.context=context;
this.items=items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return getItem(position).hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null)
convertView = LayoutInflater.from(context).inflate(R.layout.list_string_button_layout,null);
HashMap<String,ImageButton> item = (HashMap<String,ImageButton>) getItem(position);
TextView string = (TextView) convertView.findViewById(R.id.list_item_string);
String key=(String) item.keySet().toArray()[0];
string.setText(key);
item.get(key).setImageResource(R.drawable.ic_delete_black_18dp);
return convertView;
}
}
Activity:
public class SearchActivity extends AppCompatActivity{
//getting resources and allocating variables
Button add_button = null;
Button search_button = null;
EditText insert_ingredient = null;
ListView ingredient_list_view = null;
ArrayList<HashMap<String,ImageButton>> ingredient_list = new ArrayList<>();
IngredientBinAdapter list_adapter = new IngredientBinAdapter(this,ingredient_list);
ArrayList<String> ingredients_utils = new ArrayList<>();
View.OnClickListener bin_button_listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("BIN_BUTTON CLICKED");
ImageButton clicked_button = (ImageButton) v;
for(Iterator<HashMap<String,ImageButton>> i = ingredient_list.iterator(); i.hasNext(); ){
HashMap<String,ImageButton> temp= i.next();
if(temp.values().toArray()[0].equals(clicked_button))
ingredient_list.remove(temp);
}
list_adapter.notifyDataSetChanged();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
}
#Override
protected void onStart(){
super.onStart();
add_button = (Button) findViewById(R.id.add_button);
search_button = (Button) findViewById(R.id.search_button2);
insert_ingredient = (EditText) findViewById(R.id.ingredient_text_input);
ingredient_list_view = (ListView) findViewById(R.id.ingredients_view);
ingredient_list_view.setAdapter(list_adapter);
//add_button listener
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String current_ingredient_string = insert_ingredient.getText().toString().trim();
if (!current_ingredient_string.isEmpty() && !ingredients_utils.contains(current_ingredient_string)) {
HashMap<String, ImageButton> temp = new HashMap<String, ImageButton>();
ImageButton temp_bin_button = new ImageButton(SearchActivity.this);
temp_bin_button.setOnClickListener(bin_button_listener);
temp.put(current_ingredient_string, temp_bin_button);
ingredient_list.add(temp);
list_adapter.notifyDataSetChanged();
}
ingredients_utils.add(insert_ingredient.getText().toString().trim());
insert_ingredient.getText().clear();
}
});
}
}
first of all
u should move your logic to onCreate() see: Difference between onCreate() and onStart()?
second
u should in your method in adapter :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// 1. inflate view
// 2. find button
// 3. assign here listener to bin button
// i advice to use convert view pattern
}
some hints :
create data object describing row item
public class BinRow {
private String _someString;
private Drawable _imageDrawable; // (or resource id name)
public String getString() {
return _someString;
}
public Drawable getImage() {
return _imageDrawable;
}
public BinRow(String someText, Drawable imageDrawable) {
_someText = someText;
_imageDrawable = imageDrawable;
}
}
here u have adapter example ( u need adjust Album - to your BinRow & layout for row & convert view items in view holder ) - this should show you idea how adapter works :
public class AlbumAdapter extends BaseAdapter implements IListAdapter<Album> {
private List<Album> _albums;
private Context _context;
private LayoutInflater _layoutInflater;
static class ViewHolder {
ImageView imageView;
TextView albumName;
public ViewHolder(View v) {
imageView = (ImageView) v.findViewById(R.id.image);
albumName = (TextView) v.findViewById(R.id.tvAlbumName);
}
}
public AlbumAdapter(List<Album> albums) {
if(albums == null) {
_albums = new ArrasyList<>();
} else {
_albums = albums;
}
}
#Override
public int getCount() {
return _albums.size();
}
#Override
public Album getItem(int position) {
return _albums.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
final Album album = getItem(position);
if (_context == null) {
_context = parent.getContext();
}
if (_layoutInflater == null) {
_layoutInflater = LayoutInflater.from(_context);
}
View _view = convertView;
ViewHolder viewHolder;
if (_view == null) {
_view = _layoutInflater.inflate(R.layout.album_item_layout, parent, false);
viewHolder = new ViewHolder(_view);
_view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) _view.getTag();
}
viewHolder.albumName.setText(album.getAlbumDescription());
// here u can set: image to image view & listener to image
// image view could be a button
viewHolder.imageView.setOnClickListener(View.OnClickListener);
return _view;
}
#Override
public void add(Album listElement) {
_albums.add(listElement);
}
#Override
public void addAll(List<Album> listOfElements) {
_albums.addAll(listOfElements);
}
#Override
public void clear() {
_albums.clear();
}
#Override
public void remove(Album listElement) {
_albums.remove(listElement);
}
}
public interface IListAdapter<T> {
void add(T listElement);
void addAll(List<T> listOfElements);
void clear();
void remove(T listElement);
}
above interface serves as helper for adapter list methods

Null Pointer Exception at Imageview in Custom List View

I have a custom list view with a TextView and three ImageViews. On click of image view I want to start a new activity and pass the data of specific position to next activity. But I am getting null pointer exception.
I have use this for refernce http://jmsliu.com/2444/click-button-in-listview-and-get-item-position.html
Here is my code. This is main Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_employees);
toolbar = (Toolbar) findViewById(R.id.app_bar);
toolbar.setTitle("Manage Employees");
nPregress = (ProgressBar) findViewById(R.id.toolbar_progress_bar);
nPregress.setVisibility(View.GONE);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mainList = (ListView) findViewById(R.id.manageemployeeList);
employee1 = new ArrayList<Pojo>();
tii = new ArrayList<String>();
SharedPreferences prefs = getSharedPreferences("MyPref4", MODE_PRIVATE);
Set<String> set1 = prefs.getStringSet("employeename", null);
if (set1 != null ) {
List<String> nameList = new ArrayList<String>(0);
nameList.addAll(set1);
for (int i = 0; i < set1.size(); i++) {
pojo = new Pojo();
pojo.setMgEmpName(nameList.get(i));
employee1.add(pojo);
Log.e("namemmee0", "" + nameList.get(i));
}
mainAdapter = new EmployeesAdapter(EmployeesActivity.this, employee1);
mainList.setAdapter(mainAdapter);
} else {
new NetCheck().execute();
}
new NetCheck().execute();
emp_edit = (ImageView) findViewById(R.id.imgedit);
emp_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentRow = (View) v.getParent();
mainList = (ListView) parentRow.getParent();
final int position = mainList.getPositionForView(parentRow);
String emp_name = employee1.get(position).getMgEmpName().toString();
Intent i = new Intent(EmployeesActivity.this, EditEmployee.class);
i.putExtra("empname", emp_name);
startActivity(i);
}
});
}
I am getting exception at this line
emp_edit.setOnClickListener(new View.OnClickListener()
How can i do this? Please help me.
This is my Adapter. I have tried onClickListener in adpter also But i am not gtting proper data in next activity.. I get same value even if i select different list view items
public class EmployeesAdapter extends BaseAdapter {
TextView categoryName;
Pojo pojo;
private Context activity1;
ArrayList<Pojo> data1;
private ArrayList<Pojo> arraylist1 = null;
public static LayoutInflater inflater;
ImageView edit, delete, historyy;
String del_empid;
public EmployeesAdapter(Context ctx, ArrayList<Pojo> employee1) {
// TODO Auto-generated constructor stub
activity1 = ctx;
data1 = employee1;
inflater = (LayoutInflater) activity1
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arraylist1 = new ArrayList<Pojo>();
this.arraylist1.addAll(data1);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data1.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
v = inflater.inflate(R.layout.manage_emp_list, parent, false);
pojo = data1.get(position);
categoryName = (TextView) v.findViewById(R.id.employeeName);
categoryName.setText(pojo.getMgEmpName());
edit = (ImageView) v.findViewById(R.id.imgedit);
delete = (ImageView) v.findViewById(R.id.imgdelete);
historyy = (ImageView) v.findViewById(R.id.imgHistory);
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity1, EditEmployee.class);
intent.putExtra("empname", "" + pojo.getMgEmpName());
intent.putExtra("empmobile", "" + pojo.getMgEmpContact());
intent.putExtra("empemail", "" + pojo.getMgEmpEmail());
intent.putExtra("empappcost", "" + pojo.getMgEmpAppCost());
activity1.startActivity(intent);
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
del_empid = pojo.getMgEmp_id();
new NetCheck().execute();
}
});
historyy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity1, MainActivity.class);
activity1.startActivity(intent);
}
});
return v;
}
manage_emp_list of the custom list view
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/employeeName"
android:textColor="#000000"
android:textSize="18dp"
android:padding="5dp"
android:layout_marginLeft="5dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgdelete"
android:src="#drawable/delete32"
android:layout_marginRight="12dp"
android:layout_marginEnd="12dp"
android:layout_alignBottom="#+id/employeeName"
android:layout_toLeftOf="#+id/imgedit"
android:layout_toStartOf="#+id/imgedit"
android:clickable="true"
android:onClick="delete_empoyee"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgedit"
android:layout_marginRight="15dp"
android:layout_marginEnd="15dp"
android:src="#drawable/edit32"
android:layout_alignTop="#+id/imgdelete"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:clickable="true"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgHistory"
android:src="#drawable/history32"
android:clickable="true"
android:onClick="employee_history"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/imgdelete"
android:layout_toStartOf="#+id/imgdelete"
/>
Try this, There may be position mismatch when store it locally
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity1, EditEmployee.class);
intent.putExtra("empname", "" + data1.get(position).getMgEmpName());
intent.putExtra("empmobile", "" + data1.get(position).getMgEmpContact());
intent.putExtra("empemail", "" + data1.get(position).getMgEmpEmail());
intent.putExtra("empappcost", "" + data1.get(position).getMgEmpAppCost());
activity1.startActivity(intent);
}
});
Your getView() method should look like this in your adapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
pojo = data1.get(position);
ViewHolder holder;
if (pojo != null) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.manage_emp_list, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.categoryName.setText(pojo.getMgEmpName());
//holder.edit.setOnClickListener()...
//holder.delete.setOnclickListener()...
}
return convertView;
}
And add a static class in to your Adapter:
static class ViewHolder {
TextView categoryName;
ImageView edit;
ImageView delete;
ImageView historyy;
public ViewHolder(View view) {
categoryName = (TextView) v.findViewById(R.id.employeeName);
edit = (ImageView) v.findViewById(R.id.imgedit);
delete = (ImageView) v.findViewById(R.id.imgdelete);
historyy = (ImageView) v.findViewById(R.id.imgHistory);
}
}

set button onclick in listview android

i have a listView with list item like this.
i want to set an action at button "Edit" and "Delete".
this is my code.
listitem.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
android:orientation="vertical" >
<TextView
android:id="#+id/varId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone"
/>
<TextView
android:id="#+id/varNoNota"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:textStyle="bold"
android:padding="2dp"
/>
<TextView
android:id="#+id/varSenderName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/varNoNota"
android:padding="2dp"
/>
<TextView
android:id="#+id/varTotalAmount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/varSenderName"
android:padding="2dp"
/>
<Button
android:id="#+id/btnEdit"
android:layout_width="100dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#color/YellowGreen"
android:text="#string/Edit"
/>
<Button
android:id="#+id/btnDelete"
android:layout_width="100dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_alignBottom="#+id/varTotalAmount"
android:layout_alignRight="#+id/varTotalAmount"
android:background="#color/Red"
android:text="#string/Delete" />
</RelativeLayout >
this is resigteritem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/LimeGreen">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/registerItem"
android:textSize="20sp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip"
android:text="#string/from" />
<EditText
android:id="#+id/dateFrom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip"
android:text="#string/to" />
<EditText
android:id="#+id/dateTo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp" />
<Button
android:id="#+id/btnSearchRegisterItem"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:background="#color/YellowGreen"
android:text="#string/search" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="10dp"
android:background="#color/DarkGray">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="5dp"
android:layout_below="#+id/btnSearchRegisterItem"
/>
</LinearLayout>
</LinearLayout>
this is my code at file java.
public class registerItem extends Activity {
private Context context = this;
private EditText dateFrom;
private EditText dateTo;
private Calendar c = Calendar.getInstance();
private int day = c.get(Calendar.DAY_OF_MONTH);
private int month = c.get(Calendar.MONTH);
private int year = c.get(Calendar.YEAR);
private static String url = "http:localhost:8080/exdar/api/registerItem/list";
private static final String RegisterItemList = "registerItemList";
private static final String NoNota = "noNota";
private static final String SenderName = "senderName";
private static final String TotalAmount = "totalAmount";
private static final String ID = "id";
private boolean isFrom = false;
private Button btnSubmit;
private Button btnDelete;
private Button btnEdit;
ListView list;
private static String content ;
private static String from;
private static String to;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
private DatePickerDialog.OnDateSetListener dateSetListener = new OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
String finalDate = pad(dayOfMonth) + "/" + pad(monthOfYear + 1)
+ "/" + year;
if (isFrom) {
dateFrom.setText(finalDate);
} else {
dateTo.setText(finalDate);
}
}
public String pad(int data) {
if (data < 10) {
return "0" + data;
} else {
return String.valueOf(data);
}
}
};
#Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 1) {
return new DatePickerDialog(context, dateSetListener, year, month,
day);
}
return null;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.registeritem);
setUpView();
list = (ListView) findViewById(R.id.list);
}
private void setUpView() {
// TODO Auto-generated method stub
dateFrom = (EditText) findViewById(R.id.dateFrom);
dateTo = (EditText) findViewById(R.id.dateTo);
btnSubmit = (Button) findViewById(R.id.btnSearchRegisterItem);
btnEdit = (Button) findViewById(R.id.btnEdit);
btnDelete = (Button) findViewById(R.id.btnDelete);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
oslist.clear();
System.out.println("before JSON parse .........!!!!");
new JSONParse().execute();
System.out.println("after JSON parse .........!!!!");
}
});
dateFrom.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(1);
isFrom = true;
}
});
dateTo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(1);
isFrom = false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class JSONParse extends AsyncTask<Void, Void, Void>{
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(registerItem.this);
pDialog.setMessage("Getting List Item ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
System.out.println("masuk on preexecute");
}
#Override
protected Void doInBackground(Void... params) {
System.out.println("masuk doin background");
SimpleDateFormat dateparse = new SimpleDateFormat("dd/MM/yyyy");
HttpUtils networkGet = HttpUtils.getInstance();
System.out.println("networkGet = "+networkGet);
from = dateFrom.getText().toString();
System.out.println("from = "+from);
to = dateTo.getText().toString();
System.out.println("to = "+to);
try {
try{
ArrayList<NameValuePair> parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("from", from));
parameter.add(new BasicNameValuePair("to", to));
content = MyHttpURLConnection.postToHTTPJSON(url,parameter);
}
catch(Exception e){
System.out.print(e);
}
// Getting JSON Object from URL Content
JSONObject json = new JSONObject(content);
JSONArray jsonArray = json.getJSONArray(RegisterItemList);
for (int i = 0; i < jsonArray.length(); i++)
{
System.out.println("looping ke = "+i);
JSONObject c = jsonArray.getJSONObject(i);
System.out.println("c = "+c);
// Storing JSON item in a Variable
String id = c.getString(ID);
System.out.println("id "+id);
String noNota = c.getString(NoNota);
System.out.println("noNota = "+noNota);
String senderName = c.getString(SenderName);
System.out.println("senderName = "+senderName);
String totalAmount = c.getString(TotalAmount);
System.out.println("totalAmount = "+totalAmount);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(ID,id);
map.put(NoNota, noNota);
map.put(SenderName, senderName);
map.put(TotalAmount, totalAmount);
oslist.add(map);
System.out.println("oslist = "+oslist);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
list.setAdapter(new customadapter(oslist,getApplicationContext()));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(
registerItem.this,
"You Clicked at "
+ oslist.get(+position).get(NoNota),
Toast.LENGTH_SHORT).show();
}
});
}
}
}
i tried add this code to see if my code run with correctly then the toast will be show but i got error;
i got this error
i am trying to create a baseadapter..
package com.example.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class customadapter extends BaseAdapter{
ArrayList<HashMap<String, String>> oslist;
Context context;
private Button btnDelete;
private Button btnEdit;
public customadapter(ArrayList<HashMap<String, String>> oslist, Context context) {
context = context;
oslist = oslist;
this.oslist = oslist;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
System.out.println("oslist.size() = "+oslist.size());
return oslist.size();
}
#Override
public Map.Entry<String, String> getItem(int position) {
// TODO Auto-generated method stub
return (Map.Entry) oslist.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater lif = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = lif.inflate(R.layout.listitem, null);
TextView txt_Name = (TextView) convertView.findViewById(R.id.varId);
Button btnEdit = (Button) convertView.findViewById(R.id.btnEdit);
btnEdit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("mybutton in listview already works!!");
//Here perform the action you want
}
});
return convertView;
}
}
Try to use BaseAdapter Instead of ListAdapter it will be easier
Here i'm giving sample code you can implement like this in your code,
public class BaseAdapContact extends BaseAdapter {
List<String> liName;
Context con;
public BaseAdapContact(List<String> liName, Context con) {
this.liName = liName;
this.con = con;
}
#Override
public int getCount() { // TODO Auto-generated method stub
return liName.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater lif = (LayoutInflater) con
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = lif.inflate(R.layout.list_view, null);
TextView txt_Name = (TextView) convertView.findViewById(R.id.txtName);
Button btn_Call = (Button) convertView.findViewById(R.id.btnCall);
txt_Name.setText(liName.get(position));
btn_Call.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Here perform the action you want
}
});
return convertView;
}
}
As per my aspect you should initialized your list in setUpView();
list = (ListView) findViewById(R.id.list);
Your app is crash at
list.invalidateViews();
list.setAdapter(adapter);
in onPostExecute(Void result) at this line list==null
Where is your list adapter???
You should set onClickListner on a button inside your list adapter
you should use interface to listen Click Event.
Here is example,
First, you need to create a interface in adapter.
public interface onListItemClickListener{
void onEditClick();
void onDeleteClick();
}
And then implement onListItemClickListener in your registerItem activity. It will need to implement two methods in your activity.
in click event from your adapter, for ex
btn_edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//you will contain Context from your parent activity
//cast your context to listener coz it implement that listener
onListItemClickListener listener = (onListItemClickListener) mContext;
// you can add parameter in method
listener.onEditClick();
//Done this will call your method in your activity.
}
});
Hope this will help you.

edittext value not save in listview dynamically

in my listview already 20 items and above listview there is one "ADD" button .when i am click on button then open one popup dialog.. in popup dialog there is on edittext and save and close button .. when i am write something edittext and click on save button then its not working.... i'll use custom listview with one image left side and text in center..... help me
Button add = (Button)findViewById(R.id.btn_Add);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.popup);
dialog.setTitle("Add Category");
Button close = (Button)dialog.findViewById(R.id.btn_cls);
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
Button save = (Button)dialog.findViewById(R.id.btn_sv);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText edit = (EditText)dialog.findViewById(R.id.editText1);
list.add(edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
});
dialog.show();
}
});
Try this way,hope this will help you to solve your problem.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="#drawable/black"
android:orientation="vertical">
<EditText
android:id="#+id/search"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#drawable/bbbb"
android:ems="10"
android:textColor="#color/White"
android:hint="Search"
android:padding="5dp"
android:textSize="20sp">
<requestFocus />
</EditText>
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_marginTop="10dp"
android:dividerHeight="5dp"
android:cacheColorHint="#null"
android:listSelector="#null"
android:clipToPadding="false"
android:drawSelectorOnTop="true" />
<Button
android:id="#+id/btn_Add"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/list_selector"
android:text="ADD Category"
android:textSize="25sp"
android:textStyle="bold" />
</LinearLayout>
listview_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/button_border"
android:gravity="center"
android:padding="5dp">
<ImageView
android:id="#+id/flag"
android:background="#drawable/sd"
android:layout_width="60dp"
android:layout_height="60dp"
android:adjustViewBounds="true"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="5dp">
<TextView
android:id="#+id/country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="21sp"
android:textStyle="bold" />
</LinearLayout>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/round"
android:layout_marginLeft="5dp"/>
</LinearLayout>
popup.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp">
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<Button
android:id="#+id/btn_cls"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:background="#drawable/list_selector"
android:text="Close" />
<Button
android:id="#+id/btn_sv"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:background="#drawable/list_selector"
android:text="Save" />
</LinearLayout>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
private ListView list;
private ListViewAdapter adapter;
private EditText editsearch;
private Button add;
private String[] animal = new String[] {"COW","LION","TIGER","ELEPHANT","MONKEY","DONKEY"};
private ArrayList<String> listData;
private Dialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listview);
add = (Button)findViewById(R.id.btn_Add);
listData = new ArrayList<String>();
for (int i=0;i<animal.length;i++){
listData.add(animal[i]);
}
Collections.sort(listData);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
addAnimal();
}
});
adapter = new ListViewAdapter(this,listData);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this,listData.get(position),Toast.LENGTH_SHORT).show();
// if(listData.get(position).equals("COW"));
// intent = new Intent(getBaseContext(),COW.class);
//
// else if(listData.get(position).equals("LION"))
// intent = new Intent(getBaseContext(),LION.class);
//
// else if(listData.get(position).equals("TIGER"))
// intent = new Intent(getBaseContext(),TIGER.class);
//
// else if(listData.get(position).equals("MONKEY"))
// intent = new Intent(getBaseContext(),MOKEY.class);
//
// else if(listData.get(position).equals("DONKEY"))
// intent = new Intent(getBaseContext(),DONKEY.class);
}
});
editsearch = (EditText) findViewById(R.id.search);
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
String text = editsearch.getText().toString();
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {
}
});
}
public void addAnimal(){
dialog = new Dialog(this);
dialog.setContentView(R.layout.popup);
dialog.setTitle("Add Animal");
final EditText edit = (EditText)dialog.findViewById(R.id.editText1);
Button close = (Button)dialog.findViewById(R.id.btn_cls);
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button save = (Button)dialog.findViewById(R.id.btn_sv);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(edit.getText().toString().trim().length()>0){
listData.add(edit.getText().toString());
Collections.sort(listData);
adapter = new ListViewAdapter(MainActivity.this,listData);
list.setAdapter(adapter);
dialog.dismiss();
}else{
edit.setError("Value Required");
}
}
});
dialog.show();
}
class ListViewAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> data;
private ArrayList<String> filterData;
public ListViewAdapter(Context context,ArrayList<String> data) {
this.context = context;
this.data = data;
filterData =new ArrayList<String>();
filterData.addAll(this.data);
}
public class ViewHolder {
TextView country;
}
#Override
public int getCount() {
return filterData.size();
}
#Override
public Object getItem(int position) {
return filterData.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 = LayoutInflater.from(context).inflate(R.layout.listview_item, null);
holder.country = (TextView) view.findViewById(R.id.country);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.country.setText(filterData.get(position));
return view;
}
public void filter(String charText) {
filterData.clear();
if (charText.length() == 0) {
filterData.addAll(data);
}else{
for (String animal : data){
if (animal.toLowerCase().contains(charText.toLowerCase())){
filterData.add(animal);
}
}
}
notifyDataSetChanged();
}
}
}
i will use like that..
public class list extends Activity {
private ListView list;
private Button add ;
private Dialog dialog;
private ListViewAdapter adapter;
private ArrayList<String> listData;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
list = (ListView)findViewById(R.id.listview1);
add = (Button)findViewById(R.id.btn_Addd);
listData = new ArrayList<String>();
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AddSMS();
}
});
list.setAdapter(adapter);
}
public void AddSMS(){
dialog = new Dialog(this);
dialog.setContentView(R.layout.popup1);
dialog.setTitle("Add Your SMS");
final EditText et = (EditText)dialog.findViewById(R.id.editText11);
Button close = (Button)dialog.findViewById(R.id.btn_clss);
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button save = (Button)dialog.findViewById(R.id.btn_svv);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (et.getText().toString().trim().length()>0){
listData.add(et.getText().toString());
adapter = new ListViewAdapter(list.this, listData);
list.setAdapter(adapter);
dialog.dismiss();
}else {
et.setError("Value Required");
}
}
});
dialog.show();
}
class ListViewAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> data;
private ArrayList<String> filterData;
public ListViewAdapter(Context context,ArrayList<String> data) {
this.context = context;
this.data = data;
filterData =new ArrayList<String>();
filterData.addAll(this.data);
}
public class ViewHolder {
TextView txttt;
}
#Override
public int getCount() {
return filterData.size();
}
#Override
public Object getItem(int position) {
return filterData.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 = LayoutInflater.from(context).inflate(R.layout.list_double, null);
holder.txttt = (TextView) view.findViewById(R.id.txttt);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.txttt.setText(filterData.get(position));
return view;
}
public void filter(String charText) {
filterData.clear();
if (charText.length() == 0) {
filterData.addAll(data);
}else{
for (String Detail : data){
if (Detail.toLowerCase().contains(charText.toLowerCase())){
filterData.add(Detail);
}
}
}
notifyDataSetChanged();
}
}
}
instead of add to list add the item in adapter and then call notifyDataSetChanged

Categories

Resources