I created an imageviewer app. Its working fine but when I select a gridview item to delete it, it stops working. On selecting the item, delete button appears . On clicking the delete button ,an alert dialog appears asking for confirmation.I want the file to get deleted after cliking the YES button. But it does not happen. Instead it throws an indexoutofbounds exception. How can I delete selected file succesfully ?
PhotosActivity.java
import static com.example.dell_1.myapp3.ImageViewer.ImageGallery.al_images;
public class PhotosActivity extends AppCompatActivity {
int int_position;
private GridView gridView;
GridViewAdapter adapter;
ArrayList<Model_images> al_menu = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
final ImageButton button1 = (ImageButton) findViewById(R.id.button1);
final ImageButton button2 = (ImageButton) findViewById(R.id.button2);
final ImageButton button3 = (ImageButton) findViewById(R.id.button3);
final ImageButton button4 = (ImageButton) findViewById(R.id.button4);
final ImageButton button5 = (ImageButton) findViewById(R.id.button5);
button1.setVisibility(View.GONE);
button2.setVisibility(View.GONE);
button3.setVisibility(View.GONE);
button4.setVisibility(View.GONE);
button5.setVisibility(View.GONE);
gridView = (GridView) findViewById(android.R.id.list);
int_position = getIntent().getIntExtra("value", 0);
adapter = new GridViewAdapter(this, al_images, int_position);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String abc = "file://" + al_images.get(int_position).getAl_imagepath().get(position);
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("id", position);
i.putExtra("folderPosition", int_position);
i.putExtra("abc", abc);
startActivity(i);
}
});
gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
for (int j = 0; j < parent.getChildCount(); j++)
parent.getChildAt(j).setBackgroundColor(Color.TRANSPARENT);
// change the background color of the selected element
view.setBackgroundColor(Color.LTGRAY);
button1.setVisibility(View.VISIBLE);
button2.setVisibility(View.VISIBLE);
button3.setVisibility(View.VISIBLE);
button4.setVisibility(View.VISIBLE);
button5.setVisibility(View.VISIBLE);
button3.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(PhotosActivity.this);
builder1.setMessage("Are you sure you want to delete it ?");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
File file = new File( al_menu.get(int_position).getAl_imagepath().get(position));
file.delete();
al_menu.remove(position);
adapter.notifyDataSetChanged();
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
});
return true;
}
});
}
}
ImageGallery.java:
public class ImageGallery extends AppCompatActivity {
public static ArrayList<Model_images> al_images = new ArrayList<>();
boolean boolean_folder;
Adapter_PhotosFolder obj_adapter;
GridView gv_folder;
private static final int REQUEST_PERMISSIONS = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
gv_folder = (GridView) findViewById(android.R.id.list);
final ImageButton button1 = (ImageButton) findViewById(R.id.button1);
final ImageButton button2 = (ImageButton) findViewById(R.id.button2);
final ImageButton button3 = (ImageButton) findViewById(R.id.button3);
final ImageButton button4 = (ImageButton) findViewById(R.id.button4);
final ImageButton button5 = (ImageButton) findViewById(R.id.button5);
button1.setVisibility(View.GONE);
button2.setVisibility(View.GONE);
button3.setVisibility(View.GONE);
button4.setVisibility(View.GONE);
button5.setVisibility(View.GONE);
gv_folder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PhotosActivity.class);
intent.putExtra("value",i);
startActivity(intent);
}
});
GridViewAdapter.java:
public class GridViewAdapter extends ArrayAdapter<Model_images> {
Context context;
ViewHolder viewHolder;
ArrayList<Model_images> al_menu = new ArrayList<>();
int int_position;
public GridViewAdapter(Context context, ArrayList<Model_images> al_menu,int int_position) {
super(context, R.layout.activity_adapter__photos_folder, al_menu);
this.al_menu = al_menu;
this.context = context;
this.int_position = int_position;
}
#Override
public int getCount() {
Log.e("ADAPTER LIST SIZE", al_menu.get(int_position).getAl_imagepath().size() + "");
return al_menu.get(int_position).getAl_imagepath().size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
if (al_menu.get(int_position).getAl_imagepath().size() > 0) {
return al_menu.get(int_position).getAl_imagepath().size();
} else {
return 1;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_adapter__photos_folder, parent, false);
viewHolder.tv_foldern = (TextView) convertView.findViewById(R.id.tv_folder);
viewHolder.tv_foldersize = (TextView) convertView.findViewById(R.id.tv_folder2);
viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv_foldern.setVisibility(View.GONE);
viewHolder.tv_foldersize.setVisibility(View.GONE);
Glide.with(context).load("file://" + al_menu.get(int_position).getAl_imagepath().get(position))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(viewHolder.iv_image);
return convertView;
}
private static class ViewHolder {
TextView tv_foldern, tv_foldersize;
ImageView iv_image;
}
}
LOGCAT:
10-20 17:27:02.769 24402-24402/com.example.dell_1.Myapp3 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.dell_1.Myapp3, PID: 24402
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:411)
at com.example.dell_1.myapp3.ImageViewer.PhotosActivity$2$1$1.onClick(PhotosActivity.java:85)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:161)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Based on your code, I don't see where the ArrayList al_menu is ever loaded with data. So when your onClick executes and attempts to get item at index 0, you get an IndexOutOfBoundsException exception. Looks like you for got to provide it with default values. Also inside of GridViewAdapter you the declare and instantiate al_menu at the top of the file and then overwrite it inside of the constructor. That is unnecessary and causing an extra object to be used and thrown away and doesn't protect against a NullPointerException later in the adapter because null could be passed into the GridViewAdapter' constructor and you don't check to make sure of that. I recommend adding a condition that checks if the passed in ArrayList is not null and add the values to your ArrayList using a for loop or even removed the instantiation line from the top of the file and do it in the GridViewAdapter's constructor and use in the ArrayList argument as a parameter if it isn't null as parameter when you instantiate your al_menu.
Example:
public class GridViewAdapter extends ArrayAdapter<Model_images> {
Context context;
ViewHolder viewHolder;
ArrayList<Model_images> al_menu;
int int_position;
public GridViewAdapter(Context context, ArrayList<Model_images> al_menu,int int_position) {
super(context, R.layout.activity_adapter__photos_folder, al_menu);
if(al_menu != null) {
this.al_menu = new ArrayList(al_menu);
}
this.context = context;
this.int_position = int_position;
}
#Override
public int getCount() {
Log.e("ADAPTER LIST SIZE", al_menu.get(int_position).getAl_imagepath().size() + "");
return al_menu.get(int_position).getAl_imagepath().size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
if (al_menu.get(int_position).getAl_imagepath().size() > 0) {
return al_menu.get(int_position).getAl_imagepath().size();
} else {
return 1;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_adapter__photos_folder, parent, false);
viewHolder.tv_foldern = (TextView) convertView.findViewById(R.id.tv_folder);
viewHolder.tv_foldersize = (TextView) convertView.findViewById(R.id.tv_folder2);
viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv_foldern.setVisibility(View.GONE);
viewHolder.tv_foldersize.setVisibility(View.GONE);
Glide.with(context).load("file://" + al_menu.get(int_position).getAl_imagepath().get(position))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(viewHolder.iv_image);
return convertView;
}
private static class ViewHolder {
TextView tv_foldern, tv_foldersize;
ImageView iv_image;
}
}
Related
This question already has an answer here:
Button inside SimpleCursorAdapter
(1 answer)
Closed 5 years ago.
I'm fresh n funky in android dev. I start learning and got stoped by clickable button in listview!
`public class Test2 extends AppCompatActivity {
private static final String TAG = "Test2";
Button btnEdytuj;
DatabaseHelper myDb;
SimpleCursorAdapter dataAdapter;`
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test2);
myDb = new DatabaseHelper(this);
displayList();
}
private void displayList() {
Cursor cursor = myDb.getAllData();
String from[] = new String[]{myDb.COL_ID, myDb.COL_NAZWA, myDb.COL_LAT, myDb.COL_LON};
int to[] = new int[]{R.id.textView10, R.id.textView1, R.id.textView2, R.id.textView3};
dataAdapter = new SimpleCursorAdapter(this, R.layout.row_item_edit, cursor, from, to, 0);
ListView lv = (ListView) findViewById(R.id.listViewId);
lv.setAdapter(dataAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
btnEdytuj = (Button) view.findViewById(R.id.buttonEE);
btnEdytuj.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
// Do something
Intent intent = new Intent(Test2.this,Edytuj.class);
startActivity(intent);`
And my wish is to open new activity from list by intent trigger by pressing a row or a button and passing an id to handle editing.
I have found an error maybe it will helps to figure it out:
android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
in your list adapter do this :
this for get view function :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_note, null);
btnEdytuj = (Button) convertView.findViewById(R.id.buttonEE);
btnEdytuj.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
// Do something
}
});
}
return convertView;
}
this other for bind view:
#Override
public void bindView(View view, Context context, Cursor cursor){
int row_id = cursor.get('_id'); //Your row id (might need to replace)
Button button = (Button) view.findViewById(R.id.buttonEE);
button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
//ADD STUFF HERE you know which row is clicked. and which button
}
});
}
Here you go :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Write your code here
}
});
Hope this helps.
You have to put the button onClick method inside Adapter class.
As you have used SimpleCursorAdapter, use button-inside-simplecursoradapter for reference.
Kindly write following code in your activity class.
MainActivity.java
ArrayList<MobileData> searchResults = getMobileData();
final ListView lv1 = (ListView) findViewById(R.id.ListView01);
lv1.setAdapter(new MobileAdapter(this, searchResults));
Add all list item by using adapter class and also add button event in adaptaer class.
MobileAdapter.java
public class MobileAdapter extends BaseAdapter {
private static ArrayList<MobileData> searchArrayList;
private LayoutInflater mInflater;
private Context context;
MobilezonDAO dao;
public MobileAdapter(Context context, ArrayList<MobileData> results) {
this.context = context;
searchArrayList = results;
mInflater = LayoutInflater.from(context);
dao = new MobilezonDAO(this.context);
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.mobile_row_view, null);
holder = new ViewHolder();
holder.mobileImage = (ImageView) convertView.findViewById(R.id.mobileImage);
holder.mobileName = (TextView) convertView.findViewById(R.id.mobileName);
holder.mobilePrice = (TextView) convertView.findViewById(R.id.mobilePrice);
holder.mobileBrand = (TextView) convertView.findViewById(R.id.mobileBrand);
holder.viewDetails = (Button) convertView.findViewById(R.id.viewDetails);
holder.addToCart = (Button) convertView.findViewById(R.id.addToCart);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.mobileImage.setImageBitmap(searchArrayList.get(position).getMobileImage());
holder.mobileName.setText(searchArrayList.get(position).getMobileName());
holder.mobilePrice.setText("Price: $"+searchArrayList.get(position).getMobilePrice());
holder.mobileBrand.setText("Brand: "+searchArrayList.get(position).getMobileBrand());
holder.viewDetails.setBackgroundResource(R.drawable.view_details);
holder.viewDetails.setId(position);
holder.addToCart.setBackgroundResource(R.drawable.addtocart);
holder.viewDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MobileData mobileData = searchArrayList.get(holder.viewDetails.getId());
Intent intent= new Intent(context, MobileViewDetailsActivity.class);
intent.putExtra("ModelNumber", mobileData.getModelNumber());
context.startActivity(intent);
}
});
holder.addToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MobileData mobileData = searchArrayList.get(holder.viewDetails.getId());
CartData cartData = new CartData();
cartData.setUsername(emailid);
cartData.setModelNumber(mobileData.getModelNumber());
cartData.setPrice(mobileData.getMobilePrice());
cartData.setQuantity("1");
CartData tempCartData = dao.searchParticularCartData(cartData.getUsername(), cartData.getModelNumber());
if(tempCartData!=null && tempCartData.getQuantity()!=null && Integer.valueOf(tempCartData.getQuantity())>0){
Snackbar.make(view, "Selected Mobile already added in your cart.", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}else{
dao.insertCartData(cartData);
Snackbar.make(view, "Mobile has been successfully added in your cart.", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
}
});
return convertView;
}
static class ViewHolder {
ImageView mobileImage;
TextView mobileName;
TextView mobilePrice;
TextView mobileBrand;
Button viewDetails;
Button addToCart;
}
}
I have a custom listview with checkbox. It's working fine. When I click on any item its value store to arraylist and when I again click value is removed from array list. It's working but when I click on checkbox its value not store to the arraylist. I want to use checkbox setOnCheckedChangeListener to handle checkbox but issue is this I have only one adapter and I want to use this adapter for more than on activity. Please tell me can I use setOnCheckedChangeListener in activity. If I can than how to can I get position and textview and checkbox in activity please tell me with some code or edit my code thanks in adavnce.
Here is my adapter
public class Listadapter extends BaseAdapter {
CheckBox checkBox;
boolean index[];
boolean[] itemChecked;
ResolveInfo entry;
String[] itempkg;
private Context mContext;
private List<ResolveInfo> mListAppInfo;
private PackageManager mPackManager;
private ArrayList<Boolean> checkList = new ArrayList<Boolean>();
public Listadapter(Context applicationContext, List<ResolveInfo> installedApplication, PackageManager packageManager)
{
//super(applicationContext,textViewResourceId,installedApplication);
super();
this.mContext = applicationContext;
this.mListAppInfo = installedApplication;
index = new boolean[installedApplication.size()];
this.mPackManager = packageManager;
for (int i = 0; i < installedApplication.size(); i++) {
checkList.add(false);
itemChecked = new boolean[installedApplication.size()];
itempkg = new String[installedApplication.size()];
}
}
#Override
public int getCount()
{
return mListAppInfo.size();
//return ((null != mListAppInfo) ? mListAppInfo.size() : 0);
}
#Override
public Object getItem(int position)
{
// index = new boolean[mListAppInfo.size()];
return mListAppInfo.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
// get the selected entry
final ViewHolder holder;
// LayoutInflater inflater = (LayoutInflater) mContext.getLayoutInflater();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
// reference to convertView
holder.tvAppName = (TextView) convertView
.findViewById(R.id.textView1);
holder.tvPkgName = (TextView) convertView
.findViewById(R.id.textView);
holder.checkBox = (CheckBox) convertView
.findViewById(R.id.checkBox1);
holder.ivAppIcon = (ImageView) convertView
.findViewById(R.id.imageView);
convertView.setTag(holder);
// holder.ck1.setTag(packageList.get(position));
} else {
holder = (ViewHolder) convertView.getTag();
}
entry = mListAppInfo.get(position);
holder.ivAppIcon.setImageDrawable(entry.loadIcon(mPackManager));
holder.tvAppName.setText(entry.loadLabel(mPackManager));
holder.tvPkgName.setText(entry.activityInfo.packageName);
holder.checkBox.setChecked(false);
if (itemChecked[position])
holder.checkBox.setChecked(true);
else
holder.checkBox.setChecked(false);
holder.checkBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (holder.checkBox.isChecked()) {
itemChecked[position] = true;
} else {
itemChecked[position] = false;
}
}
});
return convertView;
}
private class ViewHolder
{
ImageView ivAppIcon;
TextView tvAppName;
TextView tvPkgName;
CheckBox checkBox;
}
}
this is activity code.
public class Profile5Activity extends Activity implements AdapterView.OnItemClickListener {
ListView apps5;
PackageManager packageManager5;
static ArrayList<String> checkedValue5;
Button bt5;
ResolveInfo pi5 = new ResolveInfo();
Context context = this;
CheckBox cb5;
Listadapter Adapter5 = null;
boolean[] itemChecked5;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile5);
itemChecked5 = new boolean[AllApps.getInstalledApplication(this).size()];
checkedValue5 = new ArrayList<String>();
}
apps5 = (ListView) findViewById(R.id.list5);
apps5.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
packageManager5 = getPackageManager();
List<String> list = new ArrayList<String>();
Adapter5 = new Listadapter(this, AllApps.getInstalledApplication(this), packageManager5);
apps5.setAdapter(Adapter5);
apps5.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, final int position, long arg3)
{
// TODO Auto-generated method stub
cb5 = (CheckBox) v.findViewById(R.id.checkBox1);
final TextView tv5 = (TextView) v.findViewById(R.id.textView);
final TextView tvv5 = (TextView) v.findViewById(R.id.textView1);
pi5 = (ResolveInfo) arg0.getItemAtPosition(position);
cb5.performClick();
if (cb5.isChecked()) {
checkedValue5.add(tv5.getText().toString());
itemChecked5[position] = true;
Toast.makeText(context, "all :" +checkedValue5, Toast.LENGTH_SHORT).show();
} else if (!cb5.isChecked()) {
checkedValue5.remove(tv5.getText().toString());
Toast.makeText(context, "all :" +checkedValue5, Toast.LENGTH_SHORT).show();
}
}
hi friends i had tried to implement list view in the custom dialog and passing data dynamically by using JSON and searched everywhere but don't got any solution i had tried everything from past 3 days and also i don't see any wrong in my code too i had set adapter correctly i am getting this error
Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
public class Cat_comment_adap extends BaseAdapter {
String cid;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
int idddget;
private LayoutInflater inflater;
private List<CurrentList> catlist;
private PopupWindow commentWindow;
ArrayList<CurrentList> commentlist = new ArrayList<CurrentList>();
Activity activity;
public Cat_comment_adap(Activity activity, List<CurrentList> catlist) {
this.activity = activity;
this.catlist = catlist;
}
#Override
public int getCount() {
return catlist.size();
}
#Override
public Object getItem(int i) {
return catlist.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.cat_row, viewGroup, false);
NetworkImageView singleimg = (NetworkImageView) view.findViewById(R.id.singleimg);
final ImageView agree = (ImageView) view.findViewById(R.id.agree);
ImageView commentbox = (ImageView) view.findViewById(R.id.commentbox);
commentbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onShowpopup(view);
Toast.makeText(activity, "Comments Button clicked", Toast.LENGTH_SHORT).show();
}
});
final CurrentList catertlist = catlist.get(i);
singleimg.setImageUrl(catertlist.getCatimg(), imageLoader);
idddget = catertlist.getCcids();
SharedPreferences eveid = activity.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
cid = eveid.getString("userid", "");
agree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String url = "http://sampletemplates.net/majority/api.php?action=addVote&question_id=" + idddget + "&user_id=" + cid + "&vote=1&source=android";
Log.d("Vote", "http://sampletemplates.net/majority/api.php?action=addVote&question_id=" + idddget + "&user_id=" + cid + "&vote=1&source=android");
JsonObjectRequest voting = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String votings = response.getString("status");
if (votings.equals("success")) {
agree.setImageResource(R.drawable.agreed);
Toast.makeText(activity, "Voted Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(activity, "Already Voted", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(voting);
}
});
return view;
}
public void onShowpopup(View v) {
LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View popupview = layoutInflater.inflate(R.layout.current_comment_dialog, null);
ListView commentsListView = (ListView) v.findViewById(R.id.commentsListView);
// commentAdapter = new comment_adapter(activity, commentlist);
WindowManager wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
commentWindow = new PopupWindow(popupview, width - 50, height - 400, true);
commentWindow.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.comment_bg));
commentWindow.setFocusable(true);
commentWindow.setOutsideTouchable(true);
commentWindow.showAtLocation(v, Gravity.BOTTOM, 0, 100);
commentsListView.setAdapter(new comment_adapter(activity,commentlist));
commentAdapter.notifyDataSetChanged();
}
Adapter class
public class comment_adapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<CurrentList> commentlist;
public comment_adapter(Activity activity, List<CurrentList> commentlist){
this.activity = activity;
this.commentlist = commentlist;
}
#Override
public int getCount() {
return commentlist.size();
}
#Override
public Object getItem(int i) {
return commentlist.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view = inflater.inflate(R.layout.comment_row, viewGroup, false);
TextView user_name = (TextView) view.findViewById(R.id.user_name);
TextView posttime = (TextView) view.findViewById(R.id.posttime);
TextView comtsdetails = (TextView) view.findViewById(R.id.comtsdetails);
CurrentList listofcomments = commentlist.get(i);
user_name.setText(listofcomments.getEvtusername());
posttime.setText(listofcomments.getTimetaken());
comtsdetails.setText(listofcomments.getEvcomment());
return view;
}
}
here in this class Cat_comment_adap in the method onShowpopup change
View popupview = layoutInflater.inflate(R.layout.current_comment_dialog, null);
ListView commentsListView = (ListView) v.findViewById(R.id.commentsListView);
to
View popupview = layoutInflater.inflate(R.layout.current_comment_dialog, null);
ListView commentsListView = (ListView) popupview.findViewById(R.id.commentsListView);
because your inflating listview from this layout so u have to give the name of inflated layout object there not the parameter of the method
public void onClick(View view) {
onShowpopup(view);
Toast.makeText(activity, "Comments Button clicked", Toast.LENGTH_SHORT).show();
}
Here passed view is not R.layout.cat_row as you think but it's a button that was clicked.
So just use onShowpopup(self.view) and it will work :)
or change to onClick(View clickedButton)
I have one problem, I have one activity and one dialogfragment. When I click on button in my dialogfragment I send model to Activity and write this model to the list. But when I add to the list more than one element, my listview duplicate first element, I init my adapter in onCreate() and add new information in onExcerciseAdd:
Activity:
public class AddTrainingActivity extends ActionBarActivity implements ExcercisesFragment.onButtonAdd {
private ActionBarDrawerToggle toggle;
int DIALOG_TIME = 1;
int myHour = 00;
int myMinute = 00;
TextView tvTime;
Button btn_add_ex;
ListView list;
ExcerciseAdapter adapter;
ArrayList<ExcerciseModel> excercise_list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addtraining);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tvTime = (TextView) findViewById(R.id.tv_time_add);
tvTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DIALOG_TIME);
}
});
btn_add_ex = (Button) findViewById(R.id.btn_add_exercise);
list = (ListView) findViewById(R.id.list_excercise);
excercise_list = new ArrayList<ExcerciseModel>();
Log.d("onCreate", "Work!");
adapter = new ExcerciseAdapter(excercise_list, this);
btn_add_ex.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ExcercisesFragment dlg = new ExcercisesFragment();
dlg.show(getSupportFragmentManager(),"dlg");
}
});
}
protected Dialog onCreateDialog(int id) {
if (id == DIALOG_TIME) {
Calendar c = Calendar.getInstance();
myHour = c.getTime().getHours();
myMinute = c.getTime().getMinutes();
TimePickerDialog tpd = new TimePickerDialog(this, myCallBack, myHour, myMinute, true);
return tpd;
}
return super.onCreateDialog(id);
}
TimePickerDialog.OnTimeSetListener myCallBack = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
myHour = hourOfDay;
myMinute = minute;
if (myMinute < 10) {
tvTime.setText(myHour + " : 0" + myMinute );
} else {
tvTime.setText(myHour + " : " + myMinute );
}
Log.d("TIME", "minutes " + myMinute);
}
};
#Override
public void onExcerciseAdd(ExcerciseModel model) {
Log.d("Adapter", "null? " + (adapter.isEmpty()));
excercise_list.add(model);
if (adapter.isEmpty()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetInvalidated();
adapter.notifyDataSetChanged();
list.invalidate();
list.invalidateViews();
}
});
}
list.setAdapter(adapter);
for (int i = 0; i < excercise_list.size(); i++){
Log.d("List_ex", "list(" + i +"): " + excercise_list.get(i).getTitle().toString());
}
}
}
Dialogfragment:
public class ExcercisesFragment extends DialogFragment {
private Button btn_add_dialog;
private EditText edit_time;
private EditText edit_count1;
private EditText edit_count2;
private EditText edit_weight;
private AutoCompleteTextView edit_ex;
public interface onButtonAdd {
void onExcerciseAdd (ExcerciseModel model);
}
onButtonAdd button_add;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getDialog().setTitle("Title!");
View v = inflater.inflate(R.layout.fragment_add_excersise, null);
btn_add_dialog = (Button) v.findViewById(R.id.btn_add_exercise_fr);
edit_time = (EditText) v.findViewById(R.id.edit_ex_go);
edit_count1 = (EditText) v.findViewById(R.id.edit_podh);
edit_count2 = (EditText) v.findViewById(R.id.edit_repeat);
edit_weight = (EditText) v.findViewById(R.id.edit_weight_add);
edit_ex = (AutoCompleteTextView) v.findViewById(R.id.excercise_title);
button_add = (onButtonAdd) getActivity();
Resources res = getResources();
String[] excersices = res.getStringArray(R.array.excersices);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
R.layout.profile_item, R.id.item_autotext, excersices);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
edit_ex.setAdapter(adapter);
edit_ex.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
// Just ignore the [Enter] key
return true;
}
// Handle all other keys in the default way
return false;
}
});
edit_ex.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edit_ex.showDropDown();
}
});
btn_add_dialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String time = edit_time.getText().toString();
String title = edit_ex.getText().toString();
String weight = edit_weight.getText().toString();
String count1 = edit_count1.getText().toString();
String count2 = edit_count2.getText().toString();
if (title.equals("") || count1.equals("") || count2.equals("") || weight.equals("") || time.equals("")) {
Toast.makeText(getActivity(),"Необходимо заполнить все поля", Toast.LENGTH_SHORT).show();
} else {
ExcerciseModel model = new ExcerciseModel();
model.setTitle(edit_ex.getText().toString());
model.setTime(Integer.parseInt(edit_time.getText().toString()));
model.setPodh(Integer.parseInt(edit_count1.getText().toString()));
model.setCount(Integer.parseInt(edit_count2.getText().toString()));
model.setWeight(Integer.parseInt(edit_weight.getText().toString()));
button_add.onExcerciseAdd(model);
dismiss();
}
}
});
return v;
}
}
and Adapter:
public class ExcerciseAdapter extends BaseAdapter {
ArrayList<ExcerciseModel> list;
Activity context;
public ExcerciseAdapter (ArrayList<ExcerciseModel> list, Activity context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
TextView txtViewTitle;
TextView txtViewTime;
TextView txtViewPodh;
TextView txtViewCount;
TextView txtViewWeight;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
Log.d("ConvertView", "convertview is null " + (convertView == null));
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_ex, null);
holder = new ViewHolder();
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.tv_adapter_title);
holder.txtViewTime = (TextView) convertView.findViewById(R.id.tv_adapter_time_get);
holder.txtViewPodh = (TextView) convertView.findViewById(R.id.tv_adapter_podh_get);
holder.txtViewCount = (TextView) convertView.findViewById(R.id.tv_adapter_count_get);
holder.txtViewWeight = (TextView) convertView.findViewById(R.id.tv_adapter_weight_get);
holder.txtViewTitle.setText(list.get(position).getTitle().toString());
holder.txtViewTime.setText(String.valueOf(list.get(position).getTime()));
holder.txtViewPodh.setText(String.valueOf(list.get(position).getPodh()));
holder.txtViewCount.setText(String.valueOf(list.get(position).getCount()));
holder.txtViewWeight.setText(String.valueOf(list.get(position).getWeight()));
} else {
holder = (ViewHolder) convertView.getTag();
}
Log.d("Adapter", "List_size = " +list.size());
Log.d("Adapter", "Title(" + position + "): " + list.get(position).getTitle().toString());
return convertView;
}
}
I don't know, but Adatper calls too many times, when I add one element it's calls 3 times. Please help me with this problem.
You only update your list items when you are creating them. You should do something like this:
LayoutInflater inflater = context.getLayoutInflater();
View view = (convertView == null)? inflater.inflate(R.layout.list_item_ex, parent, false) : convertView;
holder = new ViewHolder();
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.tv_adapter_title);
holder.txtViewTime = (TextView) convertView.findViewById(R.id.tv_adapter_time_get);
holder.txtViewPodh = (TextView) convertView.findViewById(R.id.tv_adapter_podh_get);
holder.txtViewCount = (TextView) convertView.findViewById(R.id.tv_adapter_count_get);
holder.txtViewWeight = (TextView) convertView.findViewById(R.id.tv_adapter_weight_get);
holder.txtViewTitle.setText(list.get(position).getTitle().toString());
holder.txtViewTime.setText(String.valueOf(list.get(position).getTime()));
holder.txtViewPodh.setText(String.valueOf(list.get(position).getPodh()));
holder.txtViewCount.setText(String.valueOf(list.get(position).getCount()));
holder.txtViewWeight.setText(String.valueOf(list.get(position).getWeight()));
return view;
Also you don't need to call all of these methods when changing the data set
adapter.notifyDataSetInvalidated();
adapter.notifyDataSetChanged();
list.invalidate();
list.invalidateViews();
Calling adapter.notifyDataSetChanged(); should be enough
You also don't need to reset the adapter every time you change the data, so this line can also be removed
list.setAdapter(adapter);
I want to dynamically add new listitems by pressing a button.but i don't no the right way to do this.
BaseAdapter
public class CompetitionResultListAdapter extends BaseAdapter{
private Activity activity;
private ArrayList<Result> result;
DataManager datamanager;
#Override
public int getCount() {
return result!=null ? result.size() : 0;
}
#Override
public Object getItem(int position) {
return result.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
// inflate the layout
LayoutInflater inflater = activity.getLayoutInflater();
convertView = inflater.inflate(R.layout.list_item_competition_result, parent, false);
}
EditText listItemDate = (EditText) convertView.findViewById(R.id.date);
EditText listItemPlace = (EditText) convertView.findViewById(R.id.place);
EditText listItemComment = (EditText) convertView.findViewById(R.id.comment);
result.get(position).setDate(listItemDate.getText().toString());
result.get(position).setPlace(listItemPlace.getText().toString());
result.get(position).setComment(listItemComment.getText().toString());
return convertView;
}
public void refreshResultList(ArrayList<Result> result){
this.result = result;
notifyDataSetChanged();
}
}
java class
public class AddCompetitionResult extends Fragment {
private CompetitionResultListAdapter competitionResultListAdapter;
private DataManager datamanager;
ArrayList<Result> result;
ListView listView;
private Horse horse;
private Button addResults;
int clickCounter=0;
public AddHorseCompetitionResult(Horse horse) {
this.horse = horse;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.add_horse_competition_result,
null);
addResults = (Button) view.findViewById(R.id.btn_add_competition_result);
listView = (ListView) view.findViewById(R.id.data_list);
// result = datamanager.create(getActivity());
competitionResultListAdapter = new CompetitionResultListAdapter();
View footerView = ((LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.competition_result_listview_footer, null, false);
listView.addFooterView(footerView);
listView.setAdapter(competitionResultListAdapter);
addResults.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String resultId = null;
// result.add();
competitionResultListAdapter.notifyDataSetChanged();
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (competitionResultListAdapter.getCount() == position) {
MainActivity mainActivity = MainActivity.getInstance();
mainActivity.setFragment(new AddHorseDetailedInfo(horse),
"Add horse more info");
// datamanager.createResult(result);
} else {
// ContactGroup cg = (ContactGroup)
// competitionResultListAdapter.getItem(position);
// MainActivity mainActivity = MainActivity.getInstance();
// mainActivity.setFragment(new
// ContactListView(cg.getGroupId()), "contacts");
}
}
});
return view;
}
}
// on button CLick
{
// toast a meesaage here : onClick()
result.add(urObject)// simply put create a object of ur result type and put "" values
// finallly call notifyDataSetChanged on adapter
adapter.notifyDataSetChanged();
}
Tryt to replace your adapter code with this.
public class CompetitionResultListAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<Result> result;
DataManager datamanager;
#Override
public int getCount() {
return result!=null ? result.size() : 0;
}
#Override
public Object getItem(int position) {
return result.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
holder = new ViewHolder();
convertView = LayoutInflater.from(activity).inflate(R.layout.list_item_competition_result, null, false);
holder.listItemDate = (EditText) convertView.findViewById(R.id.date);
holder.listItemPlace = (EditText) convertView.findViewById(R.id.place);
holder.listItemComment = (EditText) convertView.findViewById(R.id.comment);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.listItemDate = (EditText) convertView.findViewById(R.id.date);
holder.listItemPlace = (EditText) convertView.findViewById(R.id.place);
holder.listItemComment = (EditText) convertView.findViewById(R.id.comment);
result.get(position).setDate(listItemDate.getText().toString());
result.get(position).setPlace(listItemPlace.getText().toString());
result.get(position).setComment(listItemComment.getText().toString());
return convertView;
}
class ViewHolder {
EditText listItemDate;
EditText listItemPlace;
EditText listItemComment;
}
public void refreshResultList(ArrayList<Result> result){
this.result = result;
notifyDataSetChanged();
}
}