I want to edit my RecyclerView content using with Adapter class. I can edit all the values in RecyclerView using adapter position. i did everything except image upload. I can browse images, but onActivityResult is never used. This is a working code. Copy paste from activity class.
public class AlbumsAdapter extends RecyclerView.Adapter<AlbumsAdapter.MyViewHolder> {
private Context mContext;
List<Anime> mData;
List<Anime> contactListFiltered;
RequestOptions option;
private List<ChatUser> mUsersList;
CustomFiterAds fiterAds;
private RequestQueue requestQueue ;
String JSON_URL;
String RemoveCategory;
String editCategory;
Spinner spin_category,spin_sub_category,spin_product_for,spin_product_typ,condition,negotiable,city,ad_age;
ArrayList<String> arrayList_categry;
private ArrayList<Model> modelList;
String JsonURL;
private static String sub_category;
LinearLayout lin_product,lin_category;
private ImageView imageView1;
private static final int SELECT_PICTURE = 100;
private Bitmap bitmap1;
private int CAMERA = 1;
Uri selectedImageUri;
public AlbumsAdapter(Context mContext, List<Anime> mData,List<ChatUser> mUsersList) {
this.mContext = mContext;
this.mData = mData;
this.contactListFiltered = mData;
this.mUsersList=mUsersList;
// Request option for Glide
option = new RequestOptions().centerCrop().placeholder(R.drawable.loading_shape).error(R.drawable.loading_shape);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, count,desc;
public ImageView thumbnail, overflow,delete,edit;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
count = (TextView) view.findViewById(R.id.count);
desc = (TextView) view.findViewById(R.id.desc);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
overflow = (ImageView) view.findViewById(R.id.overflow);
delete=view.findViewById(R.id.deletepost);
edit=view.findViewById(R.id.editpost);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.myadlist, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.title.setText(mData.get(position).getAd_title());
holder.count.setText("AED "+mData.get(position).getAd_price());
holder.desc.setText(mData.get(position).getAd_description());
Glide.with(mContext).load(mData.get(position).getImage1()).apply(option).into(holder.thumbnail);
holder.overflow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showPopupMenu(holder.overflow,position);
}
});
holder.edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editCategory=mData.get(position).getId();
editHeadline(position);
notifyDataSetChanged();
}
});
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RemoveCategory=mData.get(position).getId();
deletevolley();
notifyItemRemoved(position);
notifyDataSetChanged();
}
});
}
/**
* Showing popup menu when tapping on 3 dots
*/
private void showPopupMenu(View view,int position) {
// inflate menu
PopupMenu popup = new PopupMenu(mContext, view);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_album, popup.getMenu());
popup.setOnMenuItemClickListener(new MyMenuItemClickListener(position));
popup.show();
}
/**
* Click listener for popup menu items
*/
class MyMenuItemClickListener implements PopupMenu.OnMenuItemClickListener {
private int position;
public MyMenuItemClickListener(int thisPosition) {
this.position=thisPosition;
}
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_delete:
RemoveCategory=mData.get(position).getId();
deletevolley();
notifyItemRemoved(position);
notifyDataSetChanged();
return true;
case R.id.action_edit:
editCategory=mData.get(position).getId();
editHeadline(position);
return true;
default:
}
return false;
}
}
#Override
public int getItemCount() {
return mData.size();
}
public void deletevolley() {
JSON_URL="https://alot.ae/api/disable_ads.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getInt("success") == 0) {
Toast.makeText(mContext, jsonObject.getString("message"), Toast.LENGTH_LONG).show();
} else if (jsonObject.getInt("success") == 1) {
Toast.makeText(mContext, jsonObject.getString("message"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mContext,"Check Internet connection", Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() {
// Creating Map String Params.
Map<String, String> params = new HashMap<String, String>();
// Adding All values to Params.
SharedPreferences prefs = mContext.getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
String userid = prefs.getString("userId", "");
params.put("user_id",userid);
params.put("id",RemoveCategory);
return params;
}
};
requestQueue = Volley.newRequestQueue(mContext);
requestQueue.add(stringRequest) ;
}
private void editHeadline(final int position) {
//Creating a LayoutInflater object for the dialog box
LayoutInflater li = LayoutInflater.from(mContext);
//Creating a view to get the dialog box
View confirmDialog = li.inflate(R.layout.edit_my_ads, null);
arrayList_categry=new ArrayList<>();
modelList = new ArrayList<Model>();
spin_category=confirmDialog.findViewById(R.id.editAdCatogoery);
spin_sub_category=confirmDialog.findViewById(R.id.editAdSubCatogoery);
spin_product_for=confirmDialog.findViewById(R.id.editAdproperty_for);
spin_product_typ=confirmDialog.findViewById(R.id.editAdproperty_typ);
condition=confirmDialog.findViewById(R.id.editAdCondition);
negotiable=confirmDialog.findViewById(R.id.editAdNegotiable);
city=confirmDialog.findViewById(R.id.editadLocation);
ad_age=confirmDialog.findViewById(R.id.editAdage);
imageView1=confirmDialog.findViewById(R.id.editadimageView);
lin_product=confirmDialog.findViewById(R.id.editlin_layout_prdct);
lin_category=confirmDialog.findViewById(R.id.editlay_sub);
lin_product.setVisibility(View.GONE);
lin_category.setVisibility(View.VISIBLE);
spin_category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
sub_category=spin_category.getItemAtPosition(spin_category.getSelectedItemPosition()).toString().trim();
modelList.clear();
if(sub_category.contentEquals("Properties"))
{
saveinformation1();
lin_product.setVisibility(View.VISIBLE);
lin_category.setVisibility(View.GONE);
}
else
{ saveinformation1();
lin_category.setVisibility(View.VISIBLE);
lin_product.setVisibility(View.GONE);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
// DO Nothing here
}
});
imageView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPictureDialog();
}
});
//
Button buttonEdit = (Button) confirmDialog.findViewById(R.id.updateAdpostButton);
final EditText editTextHeadline = (EditText) confirmDialog.findViewById(R.id.editAdTitle);
editTextHeadline.setText(mData.get(position).getAd_title());
final EditText editTextDes = (EditText) confirmDialog.findViewById(R.id.editAdDescription);
editTextDes.setText(mData.get(position).getAd_description());
final EditText editTextprice = (EditText) confirmDialog.findViewById(R.id.editAdPrice);
editTextprice.setText(mData.get(position).getAd_price());
final EditText editTextnumber = (EditText) confirmDialog.findViewById(R.id.editAdcontactpersonnumber);
editTextnumber.setText(mData.get(position).getAd_usermobile());
final EditText editTextname = (EditText) confirmDialog.findViewById(R.id.editAdcontactperson);
editTextname.setText(mData.get(position).getAd_username());
AlertDialog.Builder alert = new AlertDialog.Builder(mContext);
//Adding our dialog box to the view of alert dialog
alert.setView(confirmDialog);
//Creating an alert dialog
final AlertDialog alertDialog = alert.create();
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.BLUE ));
//Displaying the alert dialog
alertDialog.show();
buttonEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String headline = editTextHeadline.getText().toString().trim();
final String des = editTextDes.getText().toString().trim();
final String price = editTextprice.getText().toString().trim();
final String number = editTextnumber.getText().toString().trim();
final String name = editTextname.getText().toString().trim();
final String category = spin_category.getSelectedItem().toString().trim();
final String age = ad_age.getSelectedItem().toString().trim();
final String cityname = city.getSelectedItem().toString().trim();
final String negotiables = negotiable.getSelectedItem().toString().trim();
final String conditions = condition.getSelectedItem().toString().trim();
final String productfor = spin_product_for.getSelectedItem().toString().trim();
final String producttype = spin_product_typ.getSelectedItem().toString().trim();
Toast.makeText(mContext, "Updating...", Toast.LENGTH_SHORT).show();
SharedPreferences prefs = mContext.getApplicationContext().getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
String userID = prefs.getString("userId","");
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("user_id", userID);
hashMap.put("id", editCategory);
hashMap.put("ad_category", category);
hashMap.put("ad_sub_category", sub_category);
hashMap.put("property_type", producttype);
hashMap.put("property_to",productfor);
hashMap.put("ad_title", headline);
hashMap.put("ad_description", des);
hashMap.put("ad_condition", conditions);
hashMap.put("age", age);
hashMap.put("ad_price", price);
hashMap.put("negotiable", negotiables);
hashMap.put("ad_username", name);
hashMap.put("ad_usermobile", number);
hashMap.put("ad_city", cityname);
AndroidNetworking.post("https://alot.ae/api/edit_my_ads.php")
.addBodyParameter(hashMap)
.setTag("agredwe")
.setPriority(Priority.HIGH)
.build()
.getAsString(new StringRequestListener() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getInt("success") == 0)
{
Toast.makeText(mContext, jsonObject.getString("message"), Toast.LENGTH_LONG).show();
}
else if (jsonObject.getInt("success") == 1)
{
Toast.makeText(mContext, jsonObject.getString("message"), Toast.LENGTH_LONG).show();
notifyDataSetChanged();
}
else
Toast.makeText(mContext, jsonObject.getString("message"), Toast.LENGTH_LONG).show();
}
catch (JSONException e)
{
e.printStackTrace();
}
}
#Override
public void onError(ANError anError) {
Toast.makeText(mContext, "Couldnt update", Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
}
});
}
});
}
private void showPictureDialog(){
android.support.v7.app.AlertDialog.Builder pictureDialog = new android.support.v7.app.AlertDialog.Builder(mContext);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera" };
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
openImageChooser();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
private void takePhotoFromCamera() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
((Activity) mContext).startActivityForResult(Intent.createChooser(intent, "Take Picture"),CAMERA);
}
private void openImageChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
((Activity) mContext).startActivityForResult(Intent.createChooser(intent, "Select Picture"),SELECT_PICTURE);
Log.d("Edit",);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
selectedImageUri = data.getData();
if (null != selectedImageUri) {
}
if (requestCode == SELECT_PICTURE) {
try {
bitmap1 = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), selectedImageUri);
imageView1.setImageBitmap(bitmap1);
} catch (IOException e) {
e.printStackTrace();
}
} else if (requestCode == CAMERA) {
try {
bitmap1 = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), selectedImageUri);
imageView1.setImageBitmap(bitmap1);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void saveinformation1() {
JsonURL="https://alot.ae/api/loadspinner.php?ad_category="+sub_category;
JsonURL=JsonURL.replaceAll(" ","%20");
StringRequest stringRequest = new StringRequest(Request.Method.GET,JsonURL,
new Response.Listener<String>() {
#Override
public void onResponse(String ServerResponse) {
// Hiding the progress dialog after all task complete.
// pDialog.dismiss();
if (ServerResponse != null) {
try {
JSONObject jsonObj = new JSONObject(ServerResponse);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("modal");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Model cat = new Model(catObj.getString("sub_category"));
modelList.add(cat);
}
populateSpinner();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
// Hiding the progress dialog after all task complete.
// pDialog.dismiss();
// Showing error message if something goes wrong.
Toast.makeText(mContext, "Check Internet connection", Toast.LENGTH_LONG).show();
}
}) {
};
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
requestQueue.add(stringRequest);
}
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < modelList.size(); i++) {
lables.add(modelList.get(i).getSub_category());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(mContext,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spin_sub_category.setAdapter(spinnerAdapter);
}
}
Example as you asked, I have just used camera. You can use in your code.
Don't forget to provide camera permission, as I don't check for it.
MainActivity.java
final RecyclerView recyclerView = findViewById(R.id.list);
List<String> name = new LinkedList<>();
for(int i=0;i<200;i++){
name.add("Index = "+i);
}
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(new RecyclerAdapter(name, new RecyclerAdapter.ImageHelper() {
#Override
public void onImageSelect(ImageView imagView) {
recyclerImage = imagView;
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);//zero can be replaced with any action code
}
}));
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
Bitmap bm = (Bitmap) data.getExtras().get("data");
recyclerImage.setImageBitmap(bm);
}
break;
}
}
RecyclerAdapter.java
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder>{
private List<String> listId;
private ImageHelper imageHelper;
public RecyclerAdapter(List<String> listId,ImageHelper imageHelper) {
this.listId = listId;
this.imageHelper = imageHelper;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext())
.inflate(R.layout._layoutItem,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, int position) {
// holder.img_brand.setImageResource(""+listId.get(position));
holder.textView.setText(listId.get(position));
holder.img_brand.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(imageHelper!=null)
imageHelper.onImageSelect(holder.img_brand);
}
});
}
#Override
public int getItemCount() {
return listId.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
public ImageView img_brand;
public TextView textView;
public MyViewHolder(View itemView) {
super(itemView);
img_brand=itemView.findViewById(R.id.imageView);
textView=itemView.findViewById(R.id.text);
}
}
public interface ImageHelper{
void onImageSelect(ImageView imagView);
}
}
_layoutItem.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="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:id="#+id/text"
android:gravity="center"
android:textSize="20sp"
android:textColor="#000000"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="#+id/imageView"
android:background="#color/colorAccent"
android:scaleType="centerCrop"/>
</LinearLayout>
Related
I am creating a RecyclerView with Card view
my json data contains movie name,year,rating
my card view contains three text fields moviename,rating,year
when i click on rating field it should get the data from the json and display rating beside the rating text field, but the problem here is when i click on text field the data of my card view is displayed on other positions of the card view also.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mList = findViewById(R.id.recylcerview);
movieList = new ArrayList<>();
builder = new AlertDialog.Builder(this);
adapter = new MovieAdapter(this, movieList);
linearLayoutManager = new LinearLayoutManager(this);
dividerItemDecoration = new DividerItemDecoration(mList.getContext(), linearLayoutManager.getOrientation());
mList.setHasFixedSize(true);
mList.setLayoutManager(linearLayoutManager);
mList.addItemDecoration(dividerItemDecoration);
mList.setAdapter(adapter);
if ((isNetworkConnected() == true)) {
getData();
} else {
builder.setTitle("turn on internet");
builder.setCancelable(false);
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.create();
builder.show();
}
}
#Override
protected void onResume() {
super.onResume();
if ((isNetworkConnected() == true)) {
getData();
adapter.notifyDataSetChanged();
} else {
builder.setTitle("turn on internet");
builder.setCancelable(false);
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.create();
builder.show();
}
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = this.getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
private void getData() {
builder = new AlertDialog.Builder(this);
try {
JSONObject reader = new JSONObject(loadJSONFromAsset());
JSONArray jArray = reader.getJSONArray("rootnode");
for (int i = 0; i < jArray.length(); i++) {
try {
JSONObject jsonObject = jArray.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(jsonObject.getString("title"));
movie.setRating(jsonObject.getDouble("rating"));
movie.setYear(jsonObject.getInt("releaseYear"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
There should not be any duplicate data in my recycler view
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.ViewHolder> {
private Context context;
Movie movie;
public MovieAdapter(Context context, ArrayList<Movie> list) {
this.context = context;
this.list = list;
}
private ArrayList<Movie> list;
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.single_item, parent, false);
final ViewHolder viewHolder = new ViewHolder(v);
viewHolder.view_container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Intent i=new Intent(context,Main2Activity.class);
// String a=list.get(viewHolder.getAdapterPosition()).getTitle();
// Double b=list.get(viewHolder.getAdapterPosition()).getRating();
// int c=list.get(viewHolder.getAdapterPosition()).getYear();
// String g =String.valueOf(c);
// viewHolder.textYear.setText(g);
// i.putExtra("movie",a);
// i.putExtra("rating",b);
// i.putExtra("year",c);
// context.startActivity(i);
}
});
viewHolder.something.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Double w = list.get(viewHolder.getAdapterPosition()).getRating();
String k = Double.toString(w);
viewHolder.textRating.setText(k);
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
movie = list.get(position);
holder.textTitle.setText(movie.getTitle());
holder.view_container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int c = list.get(holder.getAdapterPosition()).getYear();
String g = String.valueOf(c);
holder.textYear.setText(g);
}
});
// holder.textRating.setText(String.valueOf(movie.getRating()));
// holder.textYear.setText(String.valueOf(movie.getYear()));
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView view_container;
TextView something;
public TextView textTitle, textRating, textYear;
public ViewHolder(#NonNull View itemView) {
super(itemView);
view_container = itemView.findViewById(R.id.textView5);
something = itemView.findViewById(R.id.Rating);
textTitle = itemView.findViewById(R.id.title);
textRating = itemView.findViewById(R.id.textView2);
textYear = itemView.findViewById(R.id.main_year);
}
}
}
Never bind data with view inside onCreateViewHolder method as you have done this on click of something' ,holder.textYear.setText(g);`
So instead of managing it like this, I suggest you to manage your rating textview with visibility.
Just move your click action inside onBindViewHolder(), and do below changes with it.
Double w = list.get(viewHolder.getAdapterPosition()).getRating();
String k = Double.toString(w);
viewHolder.textRating.setText(k);
viewHolder.textRating.setVisibility(View.INVISIBLE);
viewHolder.something.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewHolder.textRating.setVisibility(View.VISIBLE);
}
});
To maintain the review state:
First create one booelan variable inside your model class and generate getter-setter for that.
i.e.
private boolean isReviewedVisible = false;
public boolean isReviewedVisible() {
return isReviewedVisible;
}
public void setIsReviewedVisible(boolean isVisible) {
this.isReviewedVisible = isVisible;
}
Than add below checks in onBindViewHolder() method.
if(movie.isReviewedVisible()){
viewHolder.textRating.setVisibility(View.VISIBLE);
} else {
viewHolder.textRating.setVisibility(View.INVISIBLE);
}
viewHolder.something.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
movie.setReviewedVisible(true);
viewHolder.textRating.setVisibility(View.VISIBLE);
}
});
I am trying to remove a list item from the list view using a delete Menu in the list. The delete is must for my application.
I need to delete item from fragment.
The problem in item list, I don't know how to define this List<Item> listtache.
I use this, I can launch the app and everything loads correctly. Help me please.
public class Tachefragment extends Fragment implements AdapterView.OnItemClickListener {
String supprimertache = "http://192.168.1.15/projet/supprimertache.php";
private static final int CODE_GET_REQUEST = 1024;
Httppars ht = new Httppars();
TextView txtmen;
ProgressBar progressBar;
ListView listview;
Typeface type;
ImageView img;
HashMap<String,String> hashMap = new HashMap<>();
ItemAdapter adapter ;
String listviewid;
List<Item> listtache;
List<String> idlist = new ArrayList<>();
public Tachefragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tachefragment, container, false);
txtmen = (TextView) rootView.findViewById(R.id.textmenu);
img = (ImageView) rootView.findViewById(R.id.imgmenu);
progressBar = (ProgressBar) rootView.findViewById(R.id.ProgressBar1);
listview = (ListView) rootView.findViewById(R.id.listtask);
type = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Montserrat-Light.otf");
txtmen.setTypeface(type);
listview.setOnItemClickListener(this);
listtache = new ArrayList<Item>();
new ParseJSonDataClass(container.getContext()).execute();
return rootView;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
listviewid = idlist.get(i).toString();
Toast.makeText(getContext() , listviewid.toString() , Toast.LENGTH_SHORT).show();
}
private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
List<Item> item;
public ParseJSonDataClass(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
httpwebservice htp = new httpwebservice(Link.affichertache);
try {
htp.ExecutePostRequest();
if (htp.getResponseCode() == 200) {
FinalJSonResult = htp.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
Item itm;
item = new ArrayList<Item>();
for (int i = 0; i < jsonArray.length(); i++) {
itm = new Item();
jsonObject = jsonArray.getJSONObject(i);
idlist.add(jsonObject.getString("idt").toString());
itm.setNomt(jsonObject.getString("nomt"));
itm.setDatet(jsonObject.getString("datet"));
itm.setHeuredebut(jsonObject.getString("heuredebut"));
itm.setTempstotal(jsonObject.getString("tempstotal"));
itm.setDescription(jsonObject.getString("description"));
item.add(itm);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, htp.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (item != null) {
progressBar.setVisibility(View.GONE);
listview.setVisibility(View.VISIBLE);
adapter = new ItemAdapter(item, context);
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
registerForContextMenu(listview);
} else {
progressBar.setVisibility(View.GONE);
txtmen.setVisibility(View.VISIBLE);
img.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater minfalter = getActivity().getMenuInflater();
minfalter.inflate(R.menu.menucontext , menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
final Item selectitem = (Item) adapter.getItem(info.position);
switch (item.getItemId()){
case R.id.supprimer:
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage("Voulez vous supprimer cette tache" + " " + selectitem.getNomt()+" !")
.setCancelable(false)
.setPositiveButton("Oui", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
listtache.remove(selectitem);
adapter.notifyDataSetChanged();
}
})
.setNegativeButton("Non", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
return true;
default:
return super.onContextItemSelected(item);
}
}
}
In your code listtache in initialization but it is empty list .you cannot remove item if it is empty.if you want remove item from listview than you should be use item which are use in adapter.
In below example listtache replace to mListItem.
For example:
String listviewid;
List<Item> mListItem;
HashMap<String,String> hashMap = new HashMap<>();
List<String> idlist = new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tachefragment, container, false);
txtmen = (TextView) rootView.findViewById(R.id.textmenu);
img = (ImageView) rootView.findViewById(R.id.imgmenu);
progressBar = (ProgressBar) rootView.findViewById(R.id.ProgressBar1);
listview = (ListView) rootView.findViewById(R.id.listtask);
type = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Montserrat-Light.otf");
txtmen.setTypeface(type);
listview.setOnItemClickListener(this);
mListItem = new ArrayList<Item>();
ht= new Httppars();
new ParseJSonDataClass(container.getContext()).execute();
return rootView;
}
private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
public ParseJSonDataClass(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
httpwebservice htp = new httpwebservice(Link.affichertache);
try {
htp.ExecutePostRequest();
if (htp.getResponseCode() == 200) {
FinalJSonResult = htp.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
Item itm;
for (int i = 0; i < jsonArray.length(); i++) {
itm = new Item();
jsonObject = jsonArray.getJSONObject(i);
idlist.add(jsonObject.getString("idt").toString());
itm.setNomt(jsonObject.getString("nomt"));
itm.setDatet(jsonObject.getString("datet"));
itm.setHeuredebut(jsonObject.getString("heuredebut"));
itm.setTempstotal(jsonObject.getString("tempstotal"));
itm.setDescription(jsonObject.getString("description"));
mListItem.add(itm);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, htp.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (mListItem != null) {
progressBar.setVisibility(View.GONE);
listview.setVisibility(View.VISIBLE);
adapter = new ItemAdapter(mListItem, context);
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
registerForContextMenu(listview);
} else {
progressBar.setVisibility(View.GONE);
txtmen.setVisibility(View.VISIBLE);
img.setVisibility(View.VISIBLE);
}
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
final Item selectitem = (Item) adapter.getItem(info.position);
switch (item.getItemId()){
case R.id.supprimer:
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage("Voulez vous supprimer cette tache" + " " + selectitem.getNomt()+" !")
.setCancelable(false)
.setPositiveButton("Oui", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mListItem.remove(selectitem);
adapter.notifyDataSetChanged();
}
})
.setNegativeButton("Non", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
return true;
default:
return super.onContextItemSelected(item);
}
}
I have listview All the values are delete and update properly but only the last value is not delete in the listview.
Added a full fragment code. Take a look
For example
If I have three values in the listview If I delete 1 and 2 its removing and listview refresh properly but the last one is not refreshed in the listview
private SwipeMenuListView mylistview;
String userid;
private EditText txtsearch;
private ArrayList<JobItem> jobitems;
private JobListAdapter adapter;
SwipeMenuCreator creator;
ImageLoader imageLoader;
DisplayImageOptions options;
public Fragment_Employer_MyJobList() {
}
public static float dp2px(Context context, int dipValue) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.layoutjoblist, container, false);
imageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder().cacheInMemory(true)
.displayer(new RoundedBitmapDisplayer(1000))
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.img_app_icon)
.showImageOnFail(R.drawable.img_app_icon)
.showImageOnLoading(R.drawable.img_app_icon).build();
mylistview = (SwipeMenuListView) rootView.findViewById(R.id.mylistview);
creator = new SwipeMenuCreator() {
#Override
public void create(SwipeMenu menu) {
// create "open" item
SwipeMenuItem openItem = new SwipeMenuItem(
getActivity());
// set item background
openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
0xCE)));
// set item width
openItem.setWidth((int) dp2px(getActivity(), 90));
// set item title
openItem.setTitle("DELETE");
// set item title fontsize
openItem.setTitleSize(18);
// set item title font color
openItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(openItem);
}
};
txtsearch = (EditText) rootView.findViewById(R.id.txtsearch);
txtsearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable theWatchedText) {
String text = txtsearch.getText().toString().toLowerCase(Locale.getDefault());
if (adapter != null)
adapter.filter(text);
}
});
return rootView;
}
SharedPreferences settings;
#Override
public void onResume() {
super.onResume();
jobitems = new ArrayList<JobItem>();
jobitems.clear();
adapter.notifyDataSetChanged();
settings = getActivity().getSharedPreferences(AppUtils.PREFS_NAME, Context.MODE_PRIVATE);
userid = settings.getString("userid", "");
AuthController.getStaticInstance().
employer_joblist(getActivity(), userid, APIConstants
.POST, new AuthControllerInterface.AuthControllerCallBack()
{
#Override
public void onSuccess(String message) {
Log.e("==response==>", "==response==>" + message);
try {
JSONArray mainarray = new JSONArray(message);
for (int i = 0; i < mainarray.length(); i++) {
JSONObject json_job = mainarray.getJSONObject(i);
JobItem item = new JobItem();
item.Id = json_job.getString("ID");
item.EMPID = json_job.getString("EMPID");
item.TITLE = json_job.getString("TITLE");
item.DESC = json_job.getString("DESC");
item.CID = json_job.getString("CID");
item.PRICE = json_job.getString("PRICE");
item.LOCAT = json_job.getString("LOCAT");
item.ADATE = json_job.getString("ADATE");
item.FOLLOW = json_job.getString("FOLLOW");
JSONArray array = json_job.getJSONArray("IMAGES");
if (array.length() > 0) {
if (!array.isNull(0))
item.IMG1 = array.getString(0);
if (!array.isNull(1))
item.IMG2 = array.getString(1);
if (!array.isNull(2))
item.IMG3 = array.getString(2);
if (!array.isNull(3))
item.IMG4 = array.getString(3);
if (!array.isNull(4))
item.IMG5 = array.getString(4);
}
jobitems.add(item);
}
adapter = new JobListAdapter(getActivity(), jobitems);
mylistview.setAdapter(adapter);
mylistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
JobItem item = jobitems.get(position);
Intent intent = new Intent(getActivity(), Activity_Emp_jobdetail.class);
Bundle bundle = new Bundle();
bundle.putSerializable("jobitem", item);
intent.putExtras(bundle);
startActivity(intent);
}
});
mylistview.setMenuCreator(creator);
mylistview.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
switch (index) {
case 0:
// unfollow
userid = settings.getString("userid", "");
AuthController.getStaticInstance().employer_delete_job(getActivity(), userid, jobitems.get(position).Id, APIConstants.POST, new AuthControllerInterface.AuthControllerCallBack() {
#Override
public void onSuccess(String message) {
Log.e("==response==>", "==response==>" + message);
try {
JSONObject obj = new JSONObject(message);
Toast.makeText(getActivity(), obj.getString("ERROR") + "", Toast.LENGTH_LONG).show();
// onResume();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), message + "", Toast.LENGTH_LONG).show();
// onResume();
}
//setup
onResume();
}
#Override
public void onFailed(String error) {
Log.e("==error==>", "==error==>" + error);
}
}, Fragment_Employer_MyJobList.this);
break;
}
// false : close the menu; true : not close the menu
return false;
}
});
} catch (JSONException e) {
e.printStackTrace();
try {
JSONObject obj = new JSONObject(message);
Toast.makeText(getActivity(), obj.getString("ERROR") + "", Toast.LENGTH_LONG).show();
} catch (JSONException e1) {
e1.printStackTrace();
Toast.makeText(getActivity(), message + "", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onFailed(String error) {
Log.e("==error==>", "==error==>" + error);
}
}, Fragment_Employer_MyJobList.this);
}
#Override
public void showLoading() {
AppUtils.showProgress(getActivity(), "Please wait...");
// onResume();
}
#Override
public void stopLoading() {
AppUtils.dismissProgress();
// onResume();
}
public class OnItemClickListner implements View.OnClickListener {
int mposition;
JobItem item;
public OnItemClickListner(int position, JobItem item) {
this.mposition = position;
this.item = item;
}
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Activity_Emp_jobdetail.class);
Bundle bundle = new Bundle();
bundle.putSerializable("jobitem", item);
intent.putExtras(bundle);
startActivity(intent);
}
}
private class JobListAdapter extends BaseAdapter {
LayoutInflater _inflater;
private List<JobItem> worldpopulationlist = null;
private ArrayList<JobItem> arraylist;
public JobListAdapter(Context context, List<JobItem> worldpopulationlist) {
_inflater = LayoutInflater.from(context);
this.worldpopulationlist = worldpopulationlist;
this.arraylist = new ArrayList<JobItem>();
this.arraylist.addAll(worldpopulationlist);
}
public int getCount() {
// TODO Auto-generated method stub
return worldpopulationlist.size();
}
public JobItem getItem(int position) {
// TODO Auto-generated method stub
return worldpopulationlist.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder _holder;
if (convertView == null) {
convertView = _inflater.inflate(R.layout.layout_job_row, null);
_holder = new ViewHolder();
_holder.txtjobtitle = (TextView) convertView
.findViewById(R.id.txtjobtitle);
_holder.txtjobbudget = (TextView) convertView
.findViewById(R.id.txtjobbudget);
_holder.txtjobdesc = (TextView) convertView
.findViewById(R.id.txtjobdesc);
_holder.imageviewjob = (ImageView) convertView
.findViewById(R.id.imageviewjob);
_holder.txtlocation = (TextView) convertView
.findViewById(R.id.txtlocation);
convertView.setTag(_holder);
} else {
_holder = (ViewHolder) convertView.getTag();
}
_holder.txtjobtitle.setText(worldpopulationlist.get(position).TITLE.trim());
_holder.txtjobbudget.setText(worldpopulationlist.get(position).PRICE.trim());
_holder.txtjobdesc.setVisibility(View.VISIBLE);
_holder.txtjobbudget.setVisibility(View.GONE);
_holder.txtjobdesc.setText(worldpopulationlist.get(position).DESC);
imageLoader.displayImage(worldpopulationlist.get(position).IMG1, _holder.imageviewjob, options);
_holder.txtlocation.setText(worldpopulationlist.get(position).LOCAT.trim());
//convertView.setOnClickListener(new OnItemClickListner(position, worldpopulationlist.get(position)));
return convertView;
}
private class ViewHolder {
ImageView imageviewjob;
TextView txtjobtitle, txtjobdesc;
TextView txtlocation, txtjobbudget;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
} else {
for (JobItem wp : arraylist) {
if (wp.TITLE.toLowerCase(Locale.getDefault())
.contains(charText)) {
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
}
you have to tell your ListView that something changed in it's former List by calling notifyDataSetChanged() method of your adapter
Also you should not create a new instance of ArrayList, but only clear the old instance. Don't forget to check for null before clearing.
try calling the adapter again with a null like.
setListAdapter()
Here is my CartRowHolder
class CartRowHolder {
ImageView icon;
TextView txtprice,txttitle,personalize;
TextView txtquantity;
ImageView imgdelete,imgedit,image;
public CartRowHolder(View v) {
icon=(ImageView)v.findViewById(R.id.imageicon);
txtprice=(TextView)v.findViewById(R.id.txtoprice);
txttitle=(TextView)v.findViewById(R.id.txtotitle);
txtquantity=(TextView)v.findViewById(R.id.txtoquantity);
personalize=(TextView)v.findViewById(R.id.txtpersonalize);
imgdelete=(ImageView)v.findViewById(R.id.imgdelete);
imgedit=(ImageView)v.findViewById(R.id.edit);
}
}
Now in the ListView a ImageView and Delete Button, Edit button is there So as i click on the Edit a Dialogbox is open and in the Dialogbox i want to pass the imageView.....and i have the ImageUrl
class CartAdapter extends BaseAdapter {
Activity activity;
List<CartItem> cartItemList;
ImageLoader imageLoader;
LayoutInflater layoutInflater;
CartItem cartItem;
AppPreferenceManager appPreferenceManager;
public CartAdapter(Activity activity,List<CartItem>cartItemList) {
this.activity=activity;
this.cartItemList=cartItemList;
appPreferenceManager=new AppPreferenceManager(activity);
}
public int getCount() {
return cartItemList.size();
}
#Override
public Object getItem(int position) {
return cartItemList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
cartItem=cartItemList.get(position);
CartRowHolder cartRowHolder;
Bundle extras = getIntent().getExtras();
TextView tk;
if (extras != null) {
}
if(imageLoader==null) {
imageLoader=new ImageLoader(activity);
}
if(layoutInflater==null) {
layoutInflater=(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if(convertView==null) {
convertView=layoutInflater.inflate(R.layout.order_row,null);
cartRowHolder=new CartRowHolder(convertView);
cartRowHolder.imgdelete.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CartItem cartItem=cartItemList.get(position);
deletCartItem(cartItem.getPid());
}
});
cartRowHolder.imgedit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final CartItem cartItem=cartItemList.get(position);
ImageView image;
final EditText personalise;
Button update;
final TextView quan,title1;
final ImageButton plusd,minusd;
final AlertDialog alertDialog;
View view=getLayoutInflater().inflate(R.layout.activity_edit,null);
final AlertDialog.Builder builder=new AlertDialog.Builder(CartActivity.this).setView(view);
update = (Button)view.findViewById(R.id.update);
quan=(TextView)view.findViewById(R.id.quan);
minusd=(ImageButton)view.findViewById(R.id.minus);
plusd=(ImageButton)view.findViewById(R.id.plus);
alertDialog=builder.create();
title1=(TextView)view.findViewById(R.id.TitleView);
title1.setText(cartItemList.get(position).getName());
personalise=(EditText)view.findViewById(R.id.editpersonalize);
personalise.setText(cartItemList.get(position).getPersonalize());
quan.setText(cartItemList.get(position).getQunatity());
image=(ImageView)view.findViewById(R.id.image1);
//imageLoader.DisplayImage(Bitmap.get);
final int num=Integer.parseInt(quan.getText().toString());
final int[] counter = {num};
plusd.setOnClickListener(new View.OnClickListener() {
//int counter=0;
#Override
public void onClick(View v) {
//Toast.makeText(CartActivity.this, "Positive is click", Toast.LENGTH_SHORT).show();
counter[0]++;
quan.setText(""+ counter[0]);
minusd.setClickable(true);
plusd.setClickable(true);
if(counter[0] ==10){
plusd.setClickable(false);
minusd.setClickable(true);
Toast.makeText(CartActivity.this, "it's maxium limit", Toast.LENGTH_SHORT).show();
}
//Toast.makeText(SingleItem_Activity.this, "it's maxium limit", Toast.LENGTH_SHORT).show();
if(counter[0] >=10) {
plusd.setClickable(false);
minusd.setClickable(true);
Toast.makeText(CartActivity.this, "it's maxium limit", Toast.LENGTH_SHORT).show();
}
}
});
minusd.setOnClickListener(new View.OnClickListener() {
// int counter=0;
#Override
public void onClick(View v) {
if(counter[0] ==1) {
minusd.setClickable(false);
}
else{
counter[0] = counter[0] -1;
quan.setText(""+ counter[0]);
if(counter[0] <=1){
minusd.setClickable(false);
plusd.setClickable(true);}
}
}
});
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String update_quan=quan.getText().toString();
String update_personalise = personalise.getText().toString();
updateCartItem(update_quan,cartItem.getPid(),update_personalise);
//Toast.makeText(CartActivity.this, "it's maxium limit", Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
}
});
alertDialog.show();
}
});
cartRowHolder.txttitle.setText(cartItem.getName());
cartRowHolder.txtprice.setText(cartItem.getSubtotal());
cartRowHolder.txtquantity.setText(cartItem.getQunatity());
cartRowHolder.personalize.setText(cartItem.getPersonalize());
imageLoader.DisplayImage(cartItem.getImage(), cartRowHolder.icon);
}
return convertView;
}
OK, you will need to following code:
1) add permission for internet in your manifest
<uses-permission android:name="android.permission.INTERNET" />
2) You will need to update your list adapter
private static final int MIN_RECORDS_NUMBER = 11;
private Context _con;
private List<Person> _data;
public PersonAdapter(Context context, List<Person> data)
{
_con = context;
_data = data;
}
#Override
public int getCount()
{
return _data.size();
}
#Override
public Person getItem(int position)
{
return _data.get(position);
}
#Override
public long getItemId(int position)
{
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
Holder h = null;
if (convertView == null)
{
h = new Holder();
convertView = LayoutInflater.from(_con).inflate(R.layout.item_layout, parent, false);
h._backgroundItem = (LinearLayout) convertView.findViewById(R.id.item_layout);
h._fName = (TextView) convertView.findViewById(R.id.f_name);
h._lName = (TextView) convertView.findViewById(R.id.l_name);
h._age = (TextView) convertView.findViewById(R.id.age);
h._editBtn = (Button) convertView.findViewById(R.id.edit_btn);
convertView.setTag(h);
}
else
{
h = (Holder) convertView.getTag();
}
final Person p = getItem(position);
h._fName.setText(p._fName);
h._lName.setText(p._lName);
h._age.setText(String.valueOf(p._age));
h._backgroundItem.setActivated(p._selected);
h._editBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
((MainActivity)_con).onEditClick(p._url);
}
});
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Person p = getItem(position);
Intent i = new Intent(_con,SecondActivity.class);
i.putExtra("DATA", p._fName);
_con.startActivity(i);
}
});
return convertView;
}
public void setData(List<Person> data)
{
_data = data;
notifyDataSetChanged();
}
private static class Holder
{
public LinearLayout _backgroundItem;
public TextView _fName;
public TextView _lName;
public TextView _age;
public Button _editBtn;
}
public interface IDialog
{
public void onEditClick(String url);
}
3) update your mainactivity
public class MainActivity extends Activity implements IDialog
{
private ListView _listView;
private PersonAdapter _adapter;
private Button _sortBtn;
private List<Person> _data;
private int _sort;
private int _selectedItemIndex;
private Bitmap _bit;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_listView = (ListView) findViewById(R.id.list);
_sortBtn = (Button) findViewById(R.id.sort_list_btn);
_selectedItemIndex = -1;
_sort = 1;
_data = new ArrayList<Person>();
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","abc", "defg", 1));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","aaa", "defg", 12));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","ccc", "defg", 13));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","bb", "defg", 14));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","aa", "defg", 144));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","fff", "defg", 199));
_adapter = new PersonAdapter(this, _data);
_listView.setAdapter(_adapter);
_listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
if(position<_data.size())
{
if(_selectedItemIndex>-1)
{
_data.get(_selectedItemIndex)._selected = false;
}
_selectedItemIndex = position;
_data.get(position)._selected = true;
_adapter.setData(_data);
}
}
});
_sortBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if(_selectedItemIndex>-1)
{
_listView.clearChoices();
String fName = _adapter.getItem(_selectedItemIndex)._fName;
Comparator<Person> sortById = Person.getComperatorByFirstName(_sort);
Collections.sort(_data, sortById);
int newSelectedItemIndex = getSelectedItemIndexByFName(fName);
_selectedItemIndex = newSelectedItemIndex;
_adapter.setData(_data);
if(newSelectedItemIndex>-1)
{
_listView.setItemChecked(newSelectedItemIndex, true);
}
_sort = -_sort;
}
else
{
Comparator<Person> sortById = Person.getComperatorByFirstName(_sort);
Collections.sort(_data, sortById);
_adapter.setData(_data);
_sort = -_sort;
}
}
});
}
private int getSelectedItemIndexByFName(String name)
{
for(int index=0;index<_data.size();index++)
{
if(_data.get(index)._fName.equals(name))
{
return index;
}
}
return -1;
}
public static class Person
{
public String _url;
public String _fName;
public String _lName;
public int _age;
public boolean _selected;
public Person(String url,String fName, String lName, int age)
{
_url = url;
_fName = fName;
_lName = lName;
_age = age;
}
public static Comparator<Person> getComperatorByFirstName(final int ascendingFlag)
{
return new Comparator<Person>()
{
#Override
public int compare(Person patient1, Person patient2)
{
return patient1._fName.compareTo(patient2._fName) * ascendingFlag;
}
};
}
}
public Bitmap getBitmapFromURL(String src) {
try
{
URL url = new URL(src);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setInstanceFollowRedirects(true);
Bitmap image = BitmapFactory.decodeStream(httpCon.getInputStream());
return image;
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public void onEditClick(final String url)
{
new Thread(new Runnable()
{
#Override
public void run()
{
_bit = getBitmapFromURL(url);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_image);
ImageView image = (ImageView) dialog.findViewById(R.id.image);
if(_bit!=null)
{
image.setImageBitmap(_bit);
}
dialog.setTitle("This is my custom dialog box");
dialog.setCancelable(true);
//there are a lot of settings, for dialog, check them all out!
dialog.show();
}
});
}
}).start();
}
4) custom image layout
<?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" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/image"/>
</LinearLayout>
A bit of explanation:
there is an interface between the activity and the list adapter (IDialog)
as part of the data, each item(person) has a field URL, when the user is clicking on the button, the activity is "notified" by the interface and downloading the appropriate image and showing it in the dialog
After so any hour I find out the Soloution. Now In the Dialog-box i can again download the image.....
imageFileURL="url";
String imageFileURL=cartItemList.get(position).getImage();
try {
URL url = new URL(imageFileURL);
URLConnection conn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)conn;
httpConn.connect();
InputStream inputStream = httpConn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
inputStream.close();
image.setImageBitmap(bitmap);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Hello and greetings i am developing one app that accept multiple images from user and upload to server but images upload to server is ok.I just added one edittext to enter quantity of image but i am unable to get value from that respective edittext.so give me suggestion in my code.
i have edittext in gridview so i want to get text from edittext that is quantity of image so please help me
uploadphoto.java
public class UploadPhotos extends AppCompatActivity {
Context context;
SelectPaper paperSession;
private CoordinatorLayout coordinatorLayout;
ProgressDialog progressDialog;
SelectLab labSession;
SessionManager session;
String strSize,strType,str_username,strMRP,strPrice,strlab,strcity,strdel_type;
MaterialEditText ppr_size,ppr_type,mrp,disPrice;
SelectedAdapter_Test selectedAdapter;
long totalprice=0;
int i=0;
String imageName,user_mail,total;
GridView UploadGallery;
Handler handler;
ArrayList<CustomGallery> listOfPhotos;
ImageLoader imageLoader;
String Send[];
Snackbar snackbar;
Button btnGalleryPickup, btnUpload;
TextView noImage;
String abc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_photos);
context = this;
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
final ActionBar ab = getSupportActionBar();
assert ab != null;
ab.setDisplayHomeAsUpEnabled(true);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id
.main_content);
labSession = new SelectLab(getApplicationContext());
paperSession = new SelectPaper(getApplicationContext());
session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
user_mail = user.get(SessionManager.KEY_EMAIL);
noImage = (TextView)findViewById(R.id.noImage);
final String symbol = getResources().getString(R.string.rupee_symbol);
HashMap<String, String> paper = paperSession.getPaperDetails();
strSize = paper.get(SelectPaper.KEY_SIZE);
strType = paper.get(SelectPaper.KEY_TYPE);
strdel_type=paper.get(SelectPaper.DEL_TYPE);
HashMap<String, String> lab = labSession.getLabDetails();
strMRP = lab.get(SelectLab.KEY_MRP);
strPrice = lab.get(SelectLab.KEY_PRICE);
strlab = lab.get(SelectLab.KEY_LAB);
strcity = lab.get(SelectLab.KEY_CITY);
str_username=lab.get(SelectLab.KEY_USERNAME);
//Toast.makeText(getApplicationContext(),""+strSize+"\n"+strType+"\n"+strMRP+"\n"+strPrice+"\n"+strlab+"\n"+strcity,Toast.LENGTH_LONG).show();
ppr_size = (MaterialEditText) findViewById(R.id.paper_size);
ppr_type = (MaterialEditText) findViewById(R.id.paper_type);
mrp = (MaterialEditText) findViewById(R.id.MRP);
disPrice = (MaterialEditText) findViewById(R.id.discount_price);
ppr_size.setText(strSize);
ppr_type.setText(strType);
mrp.setText(symbol + " " + strMRP);
disPrice.setText(symbol + " " + strPrice);
initImageLoader();
init();
}
private void initImageLoader() {
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc().imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
.bitmapConfig(Bitmap.Config.RGB_565).build();
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
this).defaultDisplayImageOptions(defaultOptions).memoryCache(
new WeakMemoryCache());
ImageLoaderConfiguration config = builder.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
}
private void init() {
handler = new Handler();
UploadGallery = (GridView) findViewById(R.id.uploadGallery);
UploadGallery.setFastScrollEnabled(true);
selectedAdapter = new SelectedAdapter_Test(getApplicationContext(), imageLoader);
UploadGallery.setAdapter(selectedAdapter);
btnGalleryPickup = (Button) findViewById(R.id.btnSelectPhoto);
btnGalleryPickup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Action.ACTION_MULTIPLE_PICK);
startActivityForResult(i, 200);
}
});
btnUpload = (Button) findViewById(R.id.btn_upload);
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listOfPhotos = selectedAdapter.getAll();
if (listOfPhotos != null && listOfPhotos.size() > 0) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
abc = sdf.format(new Date());
abc="EPP"+abc;
Toast.makeText(getApplicationContext(),""+abc,Toast.LENGTH_LONG).show();
//progressDialog = ProgressDialog.show(UploadPhotos.this, "", "Uploading files to server.....", false);
progressDialog=new ProgressDialog(UploadPhotos.this);
progressDialog.setMessage("Images is Uploading.......");
progressDialog.setCancelable(false);
progressDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.mp3));
progressDialog.show();
Thread thread = new Thread(new Runnable() {
public void run() {
doFileUpload();
runOnUiThread(new Runnable() {
public void run() {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
totalprice=0;
}
Intent i=new Intent(UploadPhotos.this,Digital_Cart.class);
startActivity(i);
}
});
}
});
thread.start();
}else{
Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
}
}
});
UploadGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CustomGallery objDetails = (CustomGallery) selectedAdapter.getItem(position);
Toast.makeText(getApplicationContext(), "Position : " + position + " Path : " + objDetails.sdcardPath, Toast.LENGTH_SHORT).show();
selectedAdapter.changeSelection(view, position);
}
});
}
private void doFileUpload() {
for( i = 0 ; i<listOfPhotos.size();i++) {
final CustomGallery objDetails = (CustomGallery) selectedAdapter.getItem(i);
File f = new File(objDetails.sdcardPath);
imageName = f.getName();
totalprice=totalprice+Long.parseLong(strPrice);
total=String.valueOf(totalprice);
Log.v("Abhijit",""+totalprice);
// Toast.makeText(getApplicationContext(),""+totalprice,Toast.LENGTH_LONG).show();
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://eeee.com/aaaaa/UploadFile?foldername="+abc); //TODO - to hit URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
// publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(listOfPhotos.get(i).sdcardPath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
entity.addPart("foldername", new StringBody(abc));
entity.addPart("size",
new StringBody(strSize));
Log.v("svbh", strSize);
entity.addPart("type",
new StringBody(strType));
entity.addPart("username",
new StringBody(user_mail));
entity.addPart("total",
new StringBody(total));
entity.addPart("mrp",
new StringBody(strMRP));
entity.addPart("price",
new StringBody(strPrice));
entity.addPart("lab",
new StringBody(strlab));
entity.addPart("city",
new StringBody(strcity));
entity.addPart("imagename",
new StringBody(imageName));
entity.addPart("deltype",
new StringBody(strdel_type));
String initflag=String.valueOf(i+1);
entity.addPart("initflag",
new StringBody(initflag));
entity.addPart("lab_username",
new StringBody(str_username));
// totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
final String response_str = EntityUtils.toString(r_entity);
if (r_entity != null) {
Log.i("RESPONSE", response_str + "" + imageName);
runOnUiThread(new Runnable(){
public void run() {
try {
snackbar = Snackbar
.make(coordinatorLayout, i+" image "+response_str, Snackbar.LENGTH_LONG)
.setAction("OK", new View.OnClickListener() {
#Override
public void onClick(View view) {
snackbar.dismiss();
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
//Toast.makeText(getApplicationContext(),i+" image "+response_str, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 200 && resultCode == Activity.RESULT_OK) {
String[] all_path = data.getStringArrayExtra("all_path");
noImage.setVisibility(View.GONE);
UploadGallery.setVisibility(View.VISIBLE);
ArrayList<CustomGallery> dataT = new ArrayList<CustomGallery>();
for (String string : all_path) {
CustomGallery item = new CustomGallery();
item.sdcardPath = string;
dataT.add(item);
}
Log.d("DATAt",dataT.toString());
selectedAdapter.addAll(dataT);
}
}
}
and selected_adapter_test
public class SelectedAdapter_Test extends BaseAdapter{
private Context mContext;
private LayoutInflater inflater;
private ArrayList<CustomGallery> data = new ArrayList<CustomGallery>();
ImageLoader imageLoader;
private boolean isActionMultiplePick;
public SelectedAdapter_Test(Context c, ImageLoader imageLoader) {
mContext = c;
inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.imageLoader = imageLoader;
// clearCache();
}
public class ViewHolder {
ImageView imgQueue;
ImageView imgEdit;
EditText qty;
Button ok;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int i) {
return data.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
public void changeSelection(View v, int position) {
if (data.get(position).isSeleted) {
data.get(position).isSeleted = false;
((ViewHolder) v.getTag()).imgEdit.setVisibility(View.GONE);
((ViewHolder) v.getTag()).qty.setVisibility(View.GONE);
((ViewHolder) v.getTag()).ok.setVisibility(View.GONE);
} else {
data.get(position).isSeleted = true;
((ViewHolder) v.getTag()).qty.setVisibility(View.VISIBLE);
((ViewHolder) v.getTag()).ok.setVisibility(View.VISIBLE);
((ViewHolder) v.getTag()).imgEdit.setVisibility(View.VISIBLE);
}
}
#Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.inflate_photo_upload, null);
holder = new ViewHolder();
holder.imgQueue = (ImageView) convertView.findViewById(R.id.imgQueue);
holder.imgEdit = (ImageView) convertView.findViewById(R.id.imgedit);
holder.qty = (EditText)convertView.findViewById(R.id.quantity);
holder.ok = (Button)convertView.findViewById(R.id.btn_ok);
holder.imgEdit.setVisibility(View.GONE);
holder.qty.setVisibility(View.GONE);
holder.ok.setVisibility(View.GONE);
holder.ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data.get(i).qty= 1;
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//holder.imgQueue.setTag(position);
imageLoader.displayImage("file://" + data.get(i).sdcardPath, holder.imgQueue, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
holder.imgQueue.setImageResource(R.drawable.no_media);
super.onLoadingStarted(imageUri, view);
}
});
if (isActionMultiplePick) {
holder.imgEdit.setSelected(data.get(i).isSeleted);
holder.qty.setSelected(data.get(i).isSeleted);
holder.ok.setSelected(data.get(i).isSeleted);
Log.d("Position Data", data.get(i).toString());
Log.d("Position", String.valueOf(i));
}
return convertView;
}
public void addAll(ArrayList<CustomGallery> files) {
try {
this.data.clear();
this.data.addAll(files);
} catch (Exception e) {
e.printStackTrace();
}
notifyDataSetChanged();
}
public ArrayList getAll(){
return data;
}
}
And customGallery.java
public class CustomGallery {
public String sdcardPath;
public int qty;
EditText aaa;
public boolean isSeleted;
}
so please help to get text from edittext that is quantity.i cant figure out the problem from last one week.
Thanks in advance
Here is the code :
#Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.inflate_photo_upload, null);
holder = new ViewHolder();
holder.imgQueue = (ImageView) convertView.findViewById(R.id.imgQueue);
holder.imgEdit = (ImageView) convertView.findViewById(R.id.imgedit);
holder.qty = (EditText)convertView.findViewById(R.id.quantity);
holder.ok = (Button)convertView.findViewById(R.id.btn_ok);
holder.imgEdit.setVisibility(View.GONE);
holder.qty.setVisibility(View.GONE);
holder.ok.setVisibility(View.GONE);
holder.qty.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
// save your text here
data.get(i).qty= 1;
}
});
holder.ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data.get(i).qty= 1;
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//holder.imgQueue.setTag(position);
imageLoader.displayImage("file://" + data.get(i).sdcardPath, holder.imgQueue, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
holder.imgQueue.setImageResource(R.drawable.no_media);
super.onLoadingStarted(imageUri, view);
}
});
if (isActionMultiplePick) {
holder.imgEdit.setSelected(data.get(i).isSeleted);
holder.qty.setSelected(data.get(i).isSeleted);
holder.ok.setSelected(data.get(i).isSeleted);
Log.d("Position Data", data.get(i).toString());
Log.d("Position", String.valueOf(i));
}
return convertView;
}