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);
}
});
Related
I have Recycler view in app I use recycler view in navigation drawer means fragment
when reyclerview is empty and when I add item in recycler view that not show but after I refresh fragment and after I add item then is showing immediately but not show first time why. I am stuck.
here is my code-:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.activity_consultant_note_fragment, container, false);
mSp = getActivity().getSharedPreferences(Constant.PREF, Context.MODE_PRIVATE);
consulatantnoterecyclerView = v.findViewById(R.id.consulatantnote_display_recycler);
swipeRefreshLayout = v.findViewById(R.id.swipeContainer);
nodatafound = v.findViewById(R.id.nodatafound);
// GetConsulatantNote();
RecyclerView.LayoutManager manager = new LinearLayoutManager(getActivity());
consulatantnoterecyclerView.setLayoutManager(manager);
consulatantnoterecyclerView.setItemAnimator(new DefaultItemAnimator());
return v;
}
void GetConsulatantNote() {
dialog = new ProgressDialog(getActivity());
dialog.show();
if (!Utils.isInternetAvailable(getActivity(), true))
return;
final ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
ConsultantNote request = new ConsultantNote();
request.setActionBy(Integer.valueOf(mSp.getString(Constant.ActionBy, "")));
request.setInPatientID(Integer.valueOf(mSp.getString(Constant.InPatientID, "")));
request.setToken(mSp.getString(Constant.TOKEN, ""));
request.setCreatedBy(Integer.valueOf(mSp.getString(Constant.MasterUserID, "")));
request.setIsActive(1);
ServiceRequest serviceRequest = new ServiceRequest();
serviceRequest.setOppID(**);
serviceRequest.setParameters(request);
Call<ConsultantNoteResponse> consultantNoteResponseCall = apiInterface.SaveConsulatantNote(serviceRequest);
consultantNoteResponseCall.enqueue(new Callback<ConsultantNoteResponse>() {
#Override
public void onResponse(Call<ConsultantNoteResponse> call, Response<ConsultantNoteResponse> response) {
if (response.body().getSuccess() == true && response.body().getValidated() == false) {
if (!response.body().getValidationErrors().isEmpty()) {
Nodatafound = true;
List<ValidationError> validationErrors = response.body().getValidationErrors();
for (int i = 0; i < validationErrors.size(); i++) {
ValidationError error = new ValidationError();
error.setErrorMessage(validationErrors.get(i).getErrorMessage());
Log.d("error", "" + validationErrors.get(i).getErrorMessage());
}
// Toast.makeText(DoctorCollection.this, "Records not found for opd", Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
}
if (response.body().getSuccess() == true && response.body().getValidated() == true) {
//data
consultantNotes = new ArrayList<>();
consultantNotes.clear();
List<ConsultantNote> notes = response.body().getConsultantNotes();
consulatantnoterecyclerView.setVisibility(View.VISIBLE);
nodatafound.setVisibility(View.GONE);
for (int i = 0; i < notes.size(); i++) {
ConsultantNote note = new ConsultantNote();
note.setCreatedByUserFullName(notes.get(i).getCreatedByUserFullName());
note.setConsultantNotesDateTime(notes.get(i).getConsultantNotesDateTime());
note.setPatientProgress(notes.get(i).getPatientProgress());
note.setCreatedBy(notes.get(i).getCreatedBy());
note.setInPatientConsultantNoteID(notes.get(i).getInPatientConsultantNoteID());
note.setProblemsAndInterventions(notes.get(i).getProblemsAndInterventions());
consultantNotes.add(note);
}
//consulatantnoterecyclerView.setAdapter(consultantNoteAdpater);
setAdapterData(consultantNotes);
onItemDelete();
if (dialog.isShowing()) {
dialog.dismiss();
}
}
if (Nodatafound) {
consulatantnoterecyclerView.setVisibility(View.GONE);
nodatafound.setVisibility(View.VISIBLE);
}
}
#Override
public void onFailure(Call<ConsultantNoteResponse> call, Throwable t) {
}
});
dialog.dismiss();
}
void onItemDelete() {
final ConsultantNoteAdpater noteAdpater = new ConsultantNoteAdpater(context, consultantNotes);
consulatantnoterecyclerView.setAdapter(noteAdpater);
noteAdpater.setOnItemDeleteClickListener(new ConsultantNoteAdpater.OnItemClickDeleteListener() {
#Override
public void onItemClick(final int position, final Integer NoteId) {
final AlertDialog.Builder innermsg = new AlertDialog.Builder(context);
innermsg.setMessage("Are you sure you want to delete this consultant note ?");
innermsg.setCancelable(false);
innermsg.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
consultantNotes.remove(position);
noteAdpater.notifyItemRemoved(position);
noteAdpater.notifyItemRangeChanged(position, consultantNotes.size());
DeleteConsulatantNote(NoteId);
noteAdpater.notifyDataSetChanged();
GetConsulatantNote();
}
});
innermsg.setNegativeButton("cancle", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
innermsg.show();
}
});
}
private void setAdapterData(List<ConsultantNote> data) {
if (data != null) {
ArrayList<ConsultantNote> notes = new ArrayList<>();
notes.clear();
notes.addAll(consultantNotes);
adapter = new ConsultantNoteAdpater(getActivity(), notes);
adapter.notifyItemRangeChanged(0, consultantNotes.size());
// adapter.notifyDataSetChanged();
consulatantnoterecyclerView.setAdapter(adapter);
}
}
Here is my adapter code of recyclerview-:
public class ConsultantNoteAdpater extends RecyclerView.Adapter<ConsultantNoteAdpater.holder> {
LayoutInflater layoutInflater;
Context context;
List<ConsultantNote> consultantNotes;
private SharedPreferences mSp;
public OnItemClickDeleteListener onItemClickDeleteListener;
public ConsultantNoteAdpater(Context c, List<ConsultantNote> notes) {
context = c;
consultantNotes = notes;
notifyDataSetChanged();
}
#NonNull
#Override
public holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = layoutInflater.inflate(R.layout.activity_consultant_note_adpater, parent, false);
mSp = context.getSharedPreferences(Constant.PREF, Context.MODE_PRIVATE);
return new holder(v);
}
public interface OnItemClickDeleteListener {
void onItemClick(int position, Integer NoteId);
}
public void setOnItemDeleteClickListener(OnItemClickDeleteListener onItemClickDeleteListener) {
this.onItemClickDeleteListener = onItemClickDeleteListener;
}
#Override
public void onBindViewHolder(#NonNull holder holder, final int position) {
final ConsultantNote note = consultantNotes.get(position);
holder.createdby.setText(Html.fromHtml(createdby + "" + note.getCreatedByUserFullName()));
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onItemClickDeleteListener != null) {
//get pateint consulatant note id
onItemClickDeleteListener.onItemClick(position, note.getInPatientConsultantNoteID());
}
}
});
}
#Override
public int getItemCount() {
return consultantNotes.size();
}
class holder extends RecyclerView.ViewHolder {
TextView date, createdby;
ImageView delete;
public holder(View itemView) {
super(itemView);
date = itemView.findViewById(R.id.consulatant_datetime);
createdby = itemView.findViewById(R.id.consulatant_createdby);
delete = itemView.findViewById(R.id.deleteconsultant);
}
}
}
I am using retrofit to get data from api so if any one can help!!
Thanks in advance!!!
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>
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()
Main Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] answers = new String[]{"choice0","choice2","choice0","choice1","choice3","choice3"};
Question[] questions = new Question[6];
for(int i=0; i<6; i++){
questions[i] = new Question("Question"+(1+i),new String[]{"choice0","choice1","choice2","choice3"},answers[i]);
}
ListView listView = (ListView)findViewById(R.id.listQuestions);
QuestionAdapter questionAdapter = new QuestionAdapter(this, R.layout.list_item_row_qs, questions);
listView.setAdapter(questionAdapter);
}
}
Adapter
public class QuestionAdapter extends ArrayAdapter {
Context context;
Question[] questions;
View view;
public QuestionAdapter(Context context, int id, Question[] questions){
super(context, id, questions);
this.context = context;
this.questions = questions;
}
private class ViewHolder{
TextView chapName;
RadioButton rb0;
RadioButton rb1;
RadioButton rb2;
RadioButton rb3;
Button button;
RadioGroup rg;
TextView hiddenAnswer;
}
#Override
public View getView(int pos, View row, ViewGroup parent){
this.view = row;
ViewHolder viewHolder = null;
if(row == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(R.layout.list_item_row_qs, null);
viewHolder = new ViewHolder();
viewHolder.chapName=(TextView) row.findViewById(R.id.question);
viewHolder.rb0 = (RadioButton) row.findViewById(R.id.choice0);
viewHolder.rb1 = (RadioButton) row.findViewById(R.id.choice1);
viewHolder.rb2 = (RadioButton) row.findViewById(R.id.choice2);
viewHolder.rb3 = (RadioButton) row.findViewById(R.id.choice3);
viewHolder.button = (Button) row.findViewById(R.id.check);
viewHolder.hiddenAnswer = (TextView) row.findViewById(R.id.answer);
row.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder)row.getTag();
}
viewHolder.chapName.setText(questions[pos].getQuestionDescr());
viewHolder.rb0.setText(questions[pos].getChoice()[0]);
viewHolder.rb1.setText(questions[pos].getChoice()[1]);
viewHolder.rb2.setText(questions[pos].getChoice()[2]);
viewHolder.rb3.setText(questions[pos].getChoice()[3]);
viewHolder.hiddenAnswer.setText(questions[pos].getAnswer());
viewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View rowView = (ViewGroup) v.getParent();
RadioGroup group = (RadioGroup) rowView.findViewById(R.id.rg);
int selectedId = group.getCheckedRadioButtonId();
if (selectedId == -1) {
Toast.makeText(context, "Please choose the correct option", Toast.LENGTH_LONG).show();
} else {
RadioButton radioButton = (RadioButton) group.findViewById(selectedId);
String answer = String.valueOf(((TextView) rowView.findViewById(R.id.answer)).getText());
if (radioButton.getText().equals(answer)) {
Toast.makeText(context, "Correct Answer", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Wrong Answer", Toast.LENGTH_LONG).show();
}
}
}
});
return row;
}
}
Problem
First item in the list maps to 5th item. 2nd item to sixth item. I mean if I change radio button at the first item, Same radio button gets selected at the 5th list item also.
Any suggestions?
Is it because of recycling?
How do I resolve it?
I tried saving in Question object and retrieving it. I used pos to retrieve and set. But same problem still exist.
Adapter:
public class PersonAdapter extends BaseAdapter
{
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);
}
}
Activity
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);
RedirectToMainActivityTask task = new RedirectToMainActivityTask();
task.execute();
_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();
}
private class RedirectToMainActivityTask extends AsyncTask<Void, Void, Void>
{
protected Void doInBackground(Void... params)
{
try
{
Thread.sleep( 2 * 1000 );
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
Intent intent = new Intent( getApplicationContext(), SecondActivity.class );
intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
startActivity( intent );
}
}
}
I am saving the state of the person view inside of person object
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();
}