Hello friends,
Today I am going to share very Important code for Multi-Clickable Listview in Android.
Suppose you want perform multiple task on click of Listview like- edit, delete, share and go to another activity etc in this case my blog will help you. For this I am using custom Array-adapter. Screen shot and code is given below step by step-
1-Print Screen:
a)Normal view-
b)Main List View Clicked-
c)Edit Button Clicked-
d)Delete Button Clicked-
2) Create MainActivity.java class
package com.example.multitouchlistview;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView userList;
UserCustomAdapter userAdapter;
ArrayList<User> userArray = new ArrayList<User>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* add item in arraylist
*/
userArray.add(new User("Mumer", "Spain", "Spain"));
userArray.add(new User("Jon", "EW", "USA"));
userArray.add(new User("Broom", "Span", "SWA"));
userArray.add(new User("Lee", "Aus", "AUS"));
userArray.add(new User("Jon", "EW", "USA"));
userArray.add(new User("Broom", "Span", "SWA"));
userArray.add(new User("Lee", "Aus", "AUS"));
/**
* set item into adapter
*/
userAdapter = new UserCustomAdapter(MainActivity.this, R.layout.row,
userArray);
userList = (ListView) findViewById(R.id.listView);
userList.setItemsCanFocus(false);
userList.setAdapter(userAdapter);
/**
* get on item click listener
*/
userList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v,
final int position, long id) {
Log.i("List View Clicked", "**********");
Toast.makeText(MainActivity.this,
"List View Clicked:" + position, Toast.LENGTH_LONG)
.show();
}
});
}
}
3)Create UserCustomAdapter.java for custom view
package com.example.multitouchlistview;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class UserCustomAdapter extends ArrayAdapter<User> {
Context context;
int layoutResourceId;
ArrayList<User> data = new ArrayList<User>();
public UserCustomAdapter(Context context, int layoutResourceId,
ArrayList<User> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
holder.textName = (TextView) row.findViewById(R.id.textView1);
holder.textAddress = (TextView) row.findViewById(R.id.textView2);
holder.textLocation = (TextView) row.findViewById(R.id.textView3);
holder.btnEdit = (Button) row.findViewById(R.id.button1);
holder.btnDelete = (Button) row.findViewById(R.id.button2);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
User user = data.get(position);
holder.textName.setText(user.getName());
holder.textAddress.setText(user.getAddress());
holder.textLocation.setText(user.getLocation());
holder.btnEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Edit Button Clicked", "**********");
Toast.makeText(context, "Edit button Clicked",
Toast.LENGTH_LONG).show();
}
});
holder.btnDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Delete Button Clicked", "**********");
Toast.makeText(context, "Delete button Clicked",
Toast.LENGTH_LONG).show();
}
});
return row;
}
static class UserHolder {
TextView textName;
TextView textAddress;
TextView textLocation;
Button btnEdit;
Button btnDelete;
}
}
4)Create User.java class
package com.example.multitouchlistview;
public class User {
String name;
String address;
String location;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public User(String name, String address, String location) {
super();
this.name = name;
this.address = address;
this.location = location;
}
}
Today I am going to share very Important code for Multi-Clickable Listview in Android.
Suppose you want perform multiple task on click of Listview like- edit, delete, share and go to another activity etc in this case my blog will help you. For this I am using custom Array-adapter. Screen shot and code is given below step by step-
1-Print Screen:
a)Normal view-
b)Main List View Clicked-
c)Edit Button Clicked-
d)Delete Button Clicked-
2) Create MainActivity.java class
package com.example.multitouchlistview;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView userList;
UserCustomAdapter userAdapter;
ArrayList<User> userArray = new ArrayList<User>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* add item in arraylist
*/
userArray.add(new User("Mumer", "Spain", "Spain"));
userArray.add(new User("Jon", "EW", "USA"));
userArray.add(new User("Broom", "Span", "SWA"));
userArray.add(new User("Lee", "Aus", "AUS"));
userArray.add(new User("Jon", "EW", "USA"));
userArray.add(new User("Broom", "Span", "SWA"));
userArray.add(new User("Lee", "Aus", "AUS"));
/**
* set item into adapter
*/
userAdapter = new UserCustomAdapter(MainActivity.this, R.layout.row,
userArray);
userList = (ListView) findViewById(R.id.listView);
userList.setItemsCanFocus(false);
userList.setAdapter(userAdapter);
/**
* get on item click listener
*/
userList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v,
final int position, long id) {
Log.i("List View Clicked", "**********");
Toast.makeText(MainActivity.this,
"List View Clicked:" + position, Toast.LENGTH_LONG)
.show();
}
});
}
}
3)Create UserCustomAdapter.java for custom view
package com.example.multitouchlistview;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class UserCustomAdapter extends ArrayAdapter<User> {
Context context;
int layoutResourceId;
ArrayList<User> data = new ArrayList<User>();
public UserCustomAdapter(Context context, int layoutResourceId,
ArrayList<User> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
holder.textName = (TextView) row.findViewById(R.id.textView1);
holder.textAddress = (TextView) row.findViewById(R.id.textView2);
holder.textLocation = (TextView) row.findViewById(R.id.textView3);
holder.btnEdit = (Button) row.findViewById(R.id.button1);
holder.btnDelete = (Button) row.findViewById(R.id.button2);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
User user = data.get(position);
holder.textName.setText(user.getName());
holder.textAddress.setText(user.getAddress());
holder.textLocation.setText(user.getLocation());
holder.btnEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Edit Button Clicked", "**********");
Toast.makeText(context, "Edit button Clicked",
Toast.LENGTH_LONG).show();
}
});
holder.btnDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Delete Button Clicked", "**********");
Toast.makeText(context, "Delete button Clicked",
Toast.LENGTH_LONG).show();
}
});
return row;
}
static class UserHolder {
TextView textName;
TextView textAddress;
TextView textLocation;
Button btnEdit;
Button btnDelete;
}
}
4)Create User.java class
package com.example.multitouchlistview;
public class User {
String name;
String address;
String location;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public User(String name, String address, String location) {
super();
this.name = name;
this.address = address;
this.location = location;
}
}
5)Create activity_main.xml
<RelativeLayout 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:background="#0099CC"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Multi Touch Listview"
android:textColor="#FFFFFF"
android:textSize="25sp" />
<ListView
android:id="@+id/listView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@+id/textView"
android:layout_marginTop="5dp"
android:cacheColorHint="#00000000" />
</RelativeLayout>
6)Create custom layout for view row.xml
<RelativeLayout 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:padding="5dp"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="User Name"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="5dp"
android:text="Address"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="16sp" />
<Button
android:id="@+id/button1"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#FFFFFF"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Edit Data"
android:textColor="#0099CC" />
<Button
android:id="@+id/button2"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_below="@+id/button1"
android:layout_marginTop="3dp"
android:background="#FFFFFF"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Delete"
android:textColor="#0099CC" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView2"
android:layout_marginTop="5dp"
android:text="Location" />
</RelativeLayout>
Note- Don't forget to add below line in Button View-
android:focusable="false"
android:focusableInTouchMode="false"
Hey, great end to end example! So far the best I found :) Thanks!
ReplyDeleteYour welcome Adam & thanks for nice comments...
Deleteis it possible to insert 2 different textview in different list item?
ReplyDeleteexample:
ListItem1 = TextView1
ListItem2 = TextView2
I did not got what you want here with 2 list view?
Deleteplease help me. how can we add multiple images for gallery in array list for different items
ReplyDeletefrom gallery or for gallery? Please clear your requirement..
DeleteHello. Thank you for spending your time on publishing this.
ReplyDeleteI am confused about the row.xml.
Is it a complete new activity og just a standalone XML file placed in layout folder?
row.xml is used for create custom adapter for list-view. Please don't be confused this is this is separate view for custom list view..
DeleteThank you Again. Confusion is solved :)
ReplyDeleteAnother thing I was wondering about is how to read what button is clicked. I mean which row does the button click belong to..
I know you get seperate information on if it is the edit button or the delete button, but I dont see how to actually see which row the edit or delete button belongs to.
Maybe I am blind and if that is the case then I am sorry :)
Please see here-
DeleteJust get the position of button...
holder.btnEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Edit Button Clicked", "**********");
Toast.makeText(context, "Edit button Clicked"+position,
Toast.LENGTH_LONG).show();
}
});
THank you. That worked.
ReplyDeleteI just had to change:
public View getView(int position, View convertView, ViewGroup parent) {
to:
public View getView(final int position, View convertView, ViewGroup parent) {
Else I wasnt able to Refer to position within the onclick method.
Thank you Again.
Your welcome!
DeleteI was wondering about another issue.
ReplyDeleteI think this might be more generally about customadapters than just this code you gave us.
Is it posible from the mainactivity class to actually iterate through the listview and also read the buttons state that are placed in the adapter?
Also is it possible to pass the onClick position from the adapter directly to the activity so I can use the position information IN the activity rather than in the adapter?
I know I am asking alot from you and that you probably have plenty of other Things to spend your time on, but I seem to get stuck on finding this information myself.
Ok just ignore my last post. I figured it out.
DeleteHi
ReplyDeleteI want to delete the particular row only when delete button is pressed. Please help me.
So from where you are getting data ? from sqlite, web-service? or in local array?
Deletejust delete that item from list or array and refill your adapter..
Thanks!
Thanks!
DeleteI am fetching data from sqlite, But I want to delete it using setTag & getTag method to reduce database query overhead.
additionally I want to display the data in next activity when user clicks edit data button.
DeleteHi,
Delete1)In this case you have to pass delete query. suppose you delete item from local object and when user come again on that page item will be there again because it is still in your database. Right?
No worry about overhead, now in these days our mobile device have good processor and ram.
2)Just use get single record activity and display that data on next page and after edit you record just pass update query..
Thanks!
This comment has been removed by the author.
ReplyDeletePlease don't remove comments, just write new comment if needed..
DeleteElse it will reduce my traffic.
Hey there!! thanks for this wonderful tutorial; i have implemented your code in Fragments. As in i call the (above)List view by Button Click from Swipey Tabs. All working cool . Just a Problem that i m getting is whenever i click the list View i dont get the Toast "List View is Clicked". Can u Figure out the problem Please
ReplyDeleteI can't guess anything without code. Any way I think problem with "this" keyword. try to use getParrant(), getApplicationContext() or something else.
ReplyDeleteAnd please try to print log first you are getting anything there or not?
Awesome post. I recommend it to my android classmates in HK.
ReplyDeleteThanks and your most welcome!
DeleteNote- Don't forget to add below line in Button View-
ReplyDeleteandroid:focusable="false"
android:focusableInTouchMode="false"
if we set this true, unable to click listview. Could you explain why? Thanks for your effort in posting the code. Thanks a lot.
Hi Sreelal, i am not sure why its happen exactly. i think this is android bug only any way i got some where this thing-
Deletein nested Views, the child view always gets all the touch events first. if you want the parent view (in your case, the listView row), to get a touch event, you must return false on the child events or set them to be android:clickable="false"
hope it will help you to understand that..
Thanks!
I have the forms whenever form submit button clicked that all form data will be stored into one json object and that json object stored in on column of database.again whenever submit the form i have to print the list msg in another activity like your new meter is installed.Just like I have seven forms whenever click those forms that msgs also will be append to previous msgs in listview. here there is no problem to me
ReplyDeleteproblem happends in this
in listview one imageview is there whenever click that image i want to retreive particular msg json object and that object data will be displayed in another activity list
so what problem you are facing? do some thing like that-
Deleteholder.btnEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(context,B.class)
//you can pass here that json object in putExtra
startActivity(intent);
}
});
or you can just pass next page that column id and on that page from database retrive detail of that image.
This comment has been removed by the author.
DeleteHi Manish,
ReplyDeleteA million thanks for ur wonderful tutorial!!!
I want to go to page "detail" when clicked the "detail" image. But the problem is when I write "startActivity(intent);" it tell me to create the startActivity method, that should not happen right?
And "android:focusable="false"" also make me a little bit confused. If it is set to be unfocusable, how can it respond to click event?
Thanks!
Lijin
hi just use this line-
ReplyDeleteIntent intent=new Intent(context,A.class);
context.startActivity(intent);
Cool, thx!
Deleteyour welcome!
Deletetnx for your reply..
ReplyDeletetelugu language is not supported in android mobiles.if any plugin is there...plz help me......
This comment has been removed by the author.
ReplyDeletei hv a image listview when i click a image then opened image
ReplyDeletecan u suggest me how to do this.
use onItemClickListner for your listview and on click that image open new activity and display that image on next page. see this post hope it will help you-
Deletehttp://www.androidhub4you.com/2013/04/sqlite-example-in-android-add-image.html
just copy, click and go to next page code..
Thanks!
thanks, its work like charm ..
ReplyDeletehi, your tutorial great and i manage to delete data from the database
ReplyDeletebut why don't it reflect in my list ?
It is deleted from database but your list-view is not refreshed. So re-create your list-view or use notify change or some other mechanism to do this task.
DeleteI want textview data of particular button clicked row.when user clicked on button it display textview data on toast of particular row.
ReplyDeleteso simple just put your value in any string type variable and then display it on toast-
DeleteString valueText=user.getName();
And now pass it in your Toast-
Toast.makeText(context, valueText,
Toast.LENGTH_LONG).show();
how to update the list view after delete. also how to update the set text after selecting particular row in the list view.
ReplyDeletehi it is very nice and thank you
ReplyDeletenice tutorial, One cuestion, I have gridview with listview but the listview only show 2 items on the list when the arrayList have 10 items.
ReplyDeleteSome solution?
thanks
Manish Srivastava,
ReplyDeleteI just want to say you are such as great man. Thank you very much for all what you do and share them with us. People like you in the world will be a peaceful place. Keep up with whatever you are doing my friend. Thanks a lot
Nice post, thank you. I was looking out for such post. It helped.
ReplyDeleteYour welcome man!
DeleteThis comment has been removed by the author.
ReplyDeleteThank you for your tutoial, how can I implement the delete function with database?
ReplyDeleteJust execute delete query on delete button click. Make a connection from your database and execute your query.
Deletewonderful tutorial Bro...thankyou :)...
ReplyDeletei tried implementing the same with edittexts instead of the buttons, i could do that but my problem araised when the edit text values started vanishing on scrolling the listview... how do i store the values entered in the edittext and display it at the same places even on scrolling, as i have to send all the data on edittexts to the database (server)... could you please help me on this... your reply means a lot to me
I am not sure but yes you can mannage it using handler post delay. Please google it on stackoverflow.
DeleteThanks its really help me a lot
ReplyDeletepublic View getView(int position, View view, ViewGroup parent) {
ReplyDelete// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.dialog_list_each_item, null);
cursor.moveToPosition(position);
String date = cursor.getString(cursor.getColumnIndex("T_date"));
id_delete = cursor.getInt(cursor.getColumnIndex("_id"));
Double payment = convert(cursor.getDouble(cursor
.getColumnIndex("T_amount")));
BigDecimal bd21 = new BigDecimal(payment);
BigDecimal rounded = bd21.setScale(2, BigDecimal.ROUND_HALF_DOWN);
TextView textViewdate = (TextView) view
.findViewById(R.id.tv_startDateAndTime);
TextView textViewcurrency = (TextView) view
.findViewById(R.id.tv_currency);
TextView textViewpayment = (TextView) view
.findViewById(R.id.tv_transactionAmmount);
Button btnEdit = (Button) view.findViewById(R.id.btn_edit);
Button btnDelete = (Button) view.findViewById(R.id.btn_delete);
textViewcurrency.setText(MyActivity.currency);
textViewdate.setText(date);
textViewpayment.setText(String.valueOf(rounded));
btnEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "Edit ", Toast.LENGTH_SHORT).show();
}
});
btnDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
mContext);
// Setting Dialog Title
alertDialog.setTitle("Confirm Delete...");
// Setting Dialog Message
alertDialog.setMessage("Are you sure you want delete this?");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.delete);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Log.d("Delete ID :", id_delete + "");
invoice.db
.execSQL("delete from Transactions where _id="
+ id_delete + "");
// Write your code here to invoke YES event
Toast.makeText(mContext, "Shift deleted",
Toast.LENGTH_SHORT).show();
int I_id = MyActivity.Iid;
int I_type = MyActivity.invoice_flag;
Intent myIntent = new Intent(mContext,
InvoiceDialogActivity.class);
myIntent.putExtra("ID", I_id);
myIntent.putExtra("Type", I_type);
mContext.startActivity(myIntent);
}
});
alertDialog.setNegativeButton("No",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
alertDialog.show();
Toast.makeText(mContext, "Delete ", Toast.LENGTH_SHORT).show();
}
});
return view;
}
trying to delete record from database but it not give me exact id on delete click it get always last id of the cursor!! please help.
i'm facing same problem?
DeleteHey, very useful tutorial. Great job! Thanks, Manish :)
ReplyDeleteHi Manish,
ReplyDelete1 Question .
I get the Toast Message and EveryThing OK.
But I want delete or add the item of the row, So I Have this information in my UserCustomAdapter but in this class I can't access to my BD. I don't want start another activity. Thanks
BD means? Database osomething else?
DeleteYes , Sorry BD = Databases.
DeleteSorry for may Bad English I sepak Spanish.
Thanks
Are you able to add remove item from activity class? If yes share the code i will change for adaptar.
DeleteIn this code , I add but when the USER Touch the listView. EXCEPT THE BUTTON
Deletelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
//ComprasDataSource.crearNota(position);
Toast.makeText(PantallaNueva.this, "You Clicked " + Elementos.get(position), Toast.LENGTH_SHORT).show();
db = oData.getWritableDatabase();
db.execSQL("insert into [carrito] ([_id_prod]) values ( " + Referencias.get(position) + ")");
int count = oData.CuentaRegistros(db);
TextView textview = (TextView)findViewById(R.id.textView20);
if(count == 1)
{
textview.setText("Hay " + count + " producto");
}else{
textview.setText("Hay " + count + " productos");
}
}
});
When I try to add this item in the CustomList , DOn't let me because I try to create the Databases and say me I can't
If you want I send the project.
ReplyDeleteOk send me the code @manishupacc@gmail.com
DeleteI send the email.
DeleteTHANKS
hi Manish,
ReplyDeleteNice blog ...
I am facing a problem with listview ... please have a look at my hangout chat ..
Thanks,
Can you share your problem here or drop an email me at manishupacc@gmail.com
DeleteThanks Manish,
DeleteHere is my question ..
http://stackoverflow.com/questions/25700156/listview-malfunctioning-with-v1-of-mobile-framework-odoo-for-android
I am new in android. this artical is very useful. but in this when delete button press,how to reload(refresh) listview.
ReplyDeleteGreat tutorial!
ReplyDeleteI have a question. Is it possible to declare the Button event fuctions in the MainActivity.java class, instead of the UserCustomAdapter.java. When I press the button, I want to process some data that is available in the MainActivity.java class.
Thanks
Hello Manish,
ReplyDeleteI have just followed as you have mentioned in your tutorial but I am facing problem while clicking on Button. Whenever I click on it ,My app got crashed. Can you please help me out in this and please do let me know how to delete the row of particular list item . Here is my code-
package com.abc_fragment;
import java.util.ArrayList;
import com.rajatKhanna.R;
import android.content.Context;
import android.util.Log;
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.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class Fragment_ListviewContactAdapter extends BaseAdapter
{
private static ArrayList listDetail;
private LayoutInflater mInflater;
Context context;
public Fragment_ListviewContactAdapter(Context Fragment, ArrayList results)
{
listDetail = results;
mInflater = LayoutInflater.from(Fragment);
}
@Override
public int getCount()
{
// TODO Auto-generated method stub
return listDetail.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return listDetail.get(arg0);
}
@Override
public long getItemId(int arg0)
{
// TODO Auto-generated method stub
return arg0;
}
@SuppressWarnings("unused")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(convertView == null)
{
convertView = mInflater.inflate(R.layout.fragment_listitem, null);
holder = new ViewHolder(); //Atomholderpayment
// holder.ListviewDashBoard = listDetail.get(position);
holder.orderno = (TextView) convertView.findViewById(R.id.OrderNo_text);
holder.dispatchTo = (TextView) convertView.findViewById(R.id.dispatchTo_text);
holder.dealerN = (TextView) convertView.findViewById(R.id.dealerName_text);
holder.orderT = (TextView) convertView.findViewById(R.id.order_text);
holder.amountT = (TextView) convertView.findViewById(R.id.Amount_text);
holder.removeButton = (Button)convertView.findViewById(R.id.button_delete);
//holder.removeButton.setTag(holder.ListviewDashBoard);
//holder.removeButton.setOnClickListener((OnClickListener) this);
//convertView.setOnClickListener(new OnItemClickListener(position));
convertView.setTag(holder);
/* holder.removeButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
int pos = (Integer) v.getTag();
listDetail.remove(pos);
Fragment_ListviewContactAdapter.this.notifyDataSetChanged();
}
// TODO Auto-generated method stub
});*/
} else
{
holder = (ViewHolder) convertView.getTag();
}
Fragment_listViewDashboard ListviewDashBoard =listDetail.get(position);
holder.orderno.setText(listDetail.get(position).getOrderno());
holder.dispatchTo.setText(listDetail.get(position).getDispatchTo());
holder.dealerN.setText(listDetail.get(position).getDealerN());
holder.orderT.setText(listDetail.get(position).getOrderT());
holder.amountT.setText(listDetail.get(position).getAmountT());
holder.removeButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Log.i("Delete Button Clicked", "*************************************************");
Toast.makeText(context, "Delete button Clicked",
Toast.LENGTH_LONG).show();
}
});
return convertView;
}
static class ViewHolder
{
TextView orderno, dispatchTo, dealerN,orderT, amountT ;
Button removeButton;
}
}
Can you share your crash report please?
Delete
Delete10-29 02:09:54.555: E/AndroidRuntime(2386): java.lang.NullPointerException
10-29 02:09:54.555: E/AndroidRuntime(2386): at android.widget.Toast.(Toast.java:92)
10-29 02:09:54.555: E/AndroidRuntime(2386): at android.widget.Toast.makeText(Toast.java:238)
10-29 02:09:54.555: E/AndroidRuntime(2386): at com.b2b_fragment.Fragment_ListviewContactAdapter$1.onClick(Fragment_ListviewContactAdapter.java:111)
10-29 02:09:54.555: E/AndroidRuntime(2386): at android.view.View.performClick(View.java:4222)
10-29 02:09:54.555: E/AndroidRuntime(2386): at android.view.View$PerformClick.run(View.java:17620)
10-29 02:09:54.555: E/AndroidRuntime(2386): at android.os.Handler.handleCallback(Handler.java:800)
10-29 02:09:54.555: E/AndroidRuntime(2386): at android.os.Handler.dispatchMessage(Handler.java:100)
10-29 02:09:54.555: E/AndroidRuntime(2386): at android.os.Looper.loop(Looper.java:194)
10-29 02:09:54.555: E/AndroidRuntime(2386): at android.app.ActivityThread.main(ActivityThread.java:5391)
10-29 02:09:54.555: E/AndroidRuntime(2386): at java.lang.reflect.Method.invokeNative(Native Method)
10-29 02:09:54.555: E/AndroidRuntime(2386): at java.lang.reflect.Method.invoke(Method.java:525)
10-29 02:09:54.555: E/AndroidRuntime(2386): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
10-29 02:09:54.555: E/AndroidRuntime(2386): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
10-29 02:09:54.555: E/AndroidRuntime(2386): at dalvik.system.NativeStart.main(Native Method)
hi how can i get updates from your new posts..from ur site..i can't see a subscribe button anywhere..or blog udpates rss
ReplyDeleteFor update follow my blog from right hand side.
DeleteGreat tutorial!
ReplyDeleteI have a problems!!!
public View getView(int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.dialog_list_each_item, null);
cursor.moveToPosition(position);
String date = cursor.getString(cursor.getColumnIndex("T_date"));
id_delete = cursor.getInt(cursor.getColumnIndex("_id"));
Double payment = convert(cursor.getDouble(cursor
.getColumnIndex("T_amount")));
BigDecimal bd21 = new BigDecimal(payment);
BigDecimal rounded = bd21.setScale(2, BigDecimal.ROUND_HALF_DOWN);
TextView textViewdate = (TextView) view
.findViewById(R.id.tv_startDateAndTime);
TextView textViewcurrency = (TextView) view
.findViewById(R.id.tv_currency);
TextView textViewpayment = (TextView) view
.findViewById(R.id.tv_transactionAmmount);
Button btnEdit = (Button) view.findViewById(R.id.btn_edit);
Button btnDelete = (Button) view.findViewById(R.id.btn_delete);
textViewcurrency.setText(MyActivity.currency);
textViewdate.setText(date);
textViewpayment.setText(String.valueOf(rounded));
btnEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "Edit ", Toast.LENGTH_SHORT).show();
}
});
btnDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
mContext);
// Setting Dialog Title
alertDialog.setTitle("Confirm Delete...");
// Setting Dialog Message
alertDialog.setMessage("Are you sure you want delete this?");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.delete);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Log.d("Delete ID :", id_delete + "");
invoice.db
.execSQL("delete from Transactions where _id="
+ id_delete + "");
// Write your code here to invoke YES event
Toast.makeText(mContext, "Shift deleted",
Toast.LENGTH_SHORT).show();
int I_id = MyActivity.Iid;
int I_type = MyActivity.invoice_flag;
Intent myIntent = new Intent(mContext,
InvoiceDialogActivity.class);
myIntent.putExtra("ID", I_id);
myIntent.putExtra("Type", I_type);
mContext.startActivity(myIntent);
}
});
alertDialog.setNegativeButton("No",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
alertDialog.show();
Toast.makeText(mContext, "Delete ", Toast.LENGTH_SHORT).show();
}
});
return view;
}
trying to delete record from database but it not give me exact id on delete click it get always last id of the cursor!! please help.
Hi Manish,
ReplyDeleteYour tutorials are really helpful. Is it feasible to call asynctask from onclick? I am not able to achieve this. Please help me. I would really appreciate your help.
e.g:
holder.btnEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
AsynctTaskAddfriend asynctTaskaddfrinend = new AsynctTaskAddfriend ();
asynctTaskaddfrin .execute(friendId);
}
});
where is the problem? here- asynctTaskaddfrin .execute(friendId);???
DeleteIf yes use Context to call web-services form Base Adapter-
ctx.asynctTaskaddfrin .execute(friendId);
thank you so much
Deletei had problem , it's when i added this line to onClickListner Delete Button
finalHolder.textName.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
it's work but apply the command on item i clicked and the 7th item bellow , how do i can fix it ?
Hello Manish,
ReplyDeleteIndeed a good post,
I want to display radio button in each list item in the above code.so that on the selection & click of edit & delete button will do the respective operation & on just click of radio button I can fetch the details of selected item from the list.
I am not using any radio group only using radio buttons.
TIA
hey manish
ReplyDeletei want to add a addButton to every list Item of my listview such that on clicking on add button that list item gets added to cart and those cart items gets displayed again in listview in another activity
(My list items contains imagesand text)
thank you so much
ReplyDeletei had problem , it's when i added this line to onClickListner Delete Button
finalHolder.textName.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
it's work but apply the command on item i clicked and the 7th item bellow , how do i can fix it ?
Read more: http://www.androidhub4you.com/2013/02/muftitouch-listview-multi-click.html#ixzz3g41Nkxlj
Hi Dark, I am not getting not getting your question. Can you please explain in detail?
Deletehow to get textview value from getview android
ReplyDeleteHow can i increment text view when click the button in same list items ?
ReplyDeleteUse notifiDataSetChange.
DeleteCan you show me some code or links because i am new in android that could be more helpful appreciate your work and thank you in advance
DeleteHi! I have the same problem as Luis Fernando Trujillo. When I click my delete buton I get Toast, but I want to also delete the image from my database.
ReplyDeleteFor now I can delete image from database by click only item in listview. This is my code:
//this part is in onCreate() method
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View view,
int position, long id) {
MyImage image = (MyImage) listView.getItemAtPosition(position);
Dialog(image);
}
});
//this is my Dialog() method
public void Dialog(final MyImage image) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
builder.setView(inflater.inflate(R.layout.custom_alert, null))
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
daOdb.deleteImage(image);
Intent i = new Intent(MainActivity.this,
MainActivity.class);
startActivity(i);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.show();
}
I have tried to do the same job using delete button but it didn't work. When I use daOdb.deleteImage(image); in delete button onClick() method I get this error:
FATAL EXCEPTION: main
Process: com.example.mateusz.pickimageandsave, PID: 31675
java.lang.NullPointerException
at com.example.mateusz.pickimageandsave.ImageAdapter$2.onClick(ImageAdapter.java:100)
at android.view.View.performClick(View.java:4569)
at android.view.View$PerformClick.run(View.java:18575)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5124)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:613)
at dalvik.system.NativeStart.main(Native Method).
I don't know where is wrong in my code. Do you know how to delete image from database using delete button?
It's seems main thread issue, try asynck task to delete an image and let me know if it work.
DeleteIf we click the button and pass selected item to new activity by using putExtra, I face the problem in new activity in getStringExtra method with Resource error. Could you find out solution for me please.
ReplyDeleteCan you share your error log please?
DeleteGreat and thanks....
ReplyDeletehow to solve this error"UserHolder cannot be resolved to a type"
ReplyDeleteYou don't have below static method-
Deletestatic class UserHolder {
TextView textName;
TextView textAddress;
TextView textLocation;
Button btnEdit;
Button btnDelete;
}
?
Hey! Great tutorial. However I have been asking for help in a lot of places and cannot figure out m problem. Hopefully you'll be able to help me. I am trying to have a 'like' button and I want the like button to increment a value on the list by 1, then change text to unlike. Then vice versa. However I have a few errors.
ReplyDelete1) When I click 'like' a "random" like button down the list is also clicked.
2) When I click like, it updates the like count, but when I scroll down out of view, then scroll back up, the like count is reset.
3) When I click like, the like count will change, now when I click like on a different post down the list, the like count changes to whatever the like count changed to on the first like button I clicked.
I have been stuck for a while and will greatly appreciate your help. Here is the method:
private void createLike(final int position, final Button like, final TextView hiddenid, final TextView likes){
final String hid = hiddenid.getText().toString().trim();
final String likess = likes.getText().toString().trim();
final Posts posts = new Posts(hid, likess);
if(like.getText().toString().equalsIgnoreCase("like")){
like.setText("UnLike");
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.SERVER_ADDRESS + "LikePost.php",
new Response.Listener() {
@Override
public void onResponse(String response) {
JSONObject jsonObject = null;
try {
//json string to jsonobject
jsonObject = new JSONObject(response);
//get json sstring created in php and store to JSON Array
result2 = jsonObject.getJSONArray(Config.json_array_likes);
//Update like count here
String postLikes = getLikeCount(result2);
likes.setText(postLikes);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
protected Map getParams() throws AuthFailureError {
Map hashMap = new HashMap<>();
//maps specified string key, to specified string value
hashMap.put(Config.hid, hid);
return hashMap;
}
};
//add string request to queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
else{
like.setText("Like");
}
}
Here is where method is called:
final Holder finalHolder = holder;
holder.like.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context, "Like Clicked", Toast.LENGTH_SHORT).show();
createLike(position, finalHolder.like, finalHolder.hiddenId, finalHolder.likes);
}
});
return view;
}
Thank you!
This comment has been removed by the author.
ReplyDeleteHello Bro,
ReplyDeletei need your help,
in my case,
i have two ListView in one Activity with Custom Adapter
ListView one = List Data
ListView two = Display data
the problem is:
how to Load data to ListView two
when button on row ListView one Clicked
Thank You