public class mychatorderdetails extends ActionBarActivity {
private MyApplication app;
private String order_id;
private String orderdate;
private String cust_name;
private String cust_address;
private String cust_pincode;
private String cust_mobile;
private String action;
private String UPI;
private Button bt;
private OrderDetailsAdapter oa;
private ListView lv;
private ArrayList<HashMap<String, String>> messageList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mychatorderdetails);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
messageList = new ArrayList<HashMap<String, String>>();
app=((MyApplication) getApplicationContext());
Bundle extras = getIntent().getExtras();
if(extras != null) {
order_id = extras.getString("order_id");
orderdate = extras.getString("orderdate");
cust_name = extras.getString("cust_name");
cust_address = extras.getString("cust_address");
cust_pincode = extras.getString("cust_pincode");
cust_mobile=extras.getString("cust_mobile");
UPI=extras.getString("UPI");
action=extras.getString("action"); //setaccepted, setdelivered
}
bt = (Button) findViewById(R.id.btnAction);
switch (action)
{
case "setdelivered":{
bt.setText("Delivered");
break;
}
case "setaccepted":{
bt.setText("Accept");
break;
}
default:
}
try {
String dpart = orderdate.substring(0, 10);
String tpart = orderdate.substring(11, 19);
orderdate = dpart.substring(8,10);
orderdate+="/"+dpart.substring(5,7);
orderdate+="/"+dpart.substring(0,4);
orderdate+=" "+tpart;
}
catch (Exception e)
{
Log.d(getString(R.string.app_name), e.getMessage());
}
HashMap<String, String> row = new HashMap<String, String>();
row.put("type", "text");
row.put("details", "Order ID:"+order_id);
messageList.add(row);
HashMap<String, String> rowd = new HashMap<String, String>();
rowd.put("type", "text");
rowd.put("details", "Order Date:"+orderdate);
messageList.add(rowd);
HashMap<String, String> row1 = new HashMap<String, String>();
row1.put("type", "text");
row1.put("details",cust_name);
messageList.add(row1);
HashMap<String, String> row2 = new HashMap<String, String>();
row2.put("type", "text");
row2.put("details",cust_address);
messageList.add(row2);
HashMap<String, String> row3 = new HashMap<String, String>();
row3.put("type", "text");
row3.put("details","Pin:"+cust_pincode);
messageList.add(row3);
HashMap<String, String> row4 = new HashMap<String, String>();
row4.put("type", "text");
row4.put("details","Mob:"+cust_mobile);
messageList.add(row4);
HashMap<String, String> row5 = new HashMap<String, String>();
row5.put("type", "text");
row5.put("details","UPI:"+UPI);
messageList.add(row5);
oa=new OrderDetailsAdapter(mychatorderdetails.this,messageList);
lv = (ListView) findViewById(R.id.lstOrderDetails);
lv.setAdapter(oa);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
HashMap<String, String> temp = new HashMap<String, String>();
temp = messageList.get(position);
if(temp.get("type")=="image")
{
//Uri uri = Uri.parse(temp.get("details"));
showImage(temp.get("details"));
}
} catch (Exception e) {
Log.d(getString(R.string.app_name), e.getMessage());
}
}
});
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONArray det = app.getMyChatOrderDetails(order_id);
for (int i = 0; i < det.length(); i++) {
JSONObject cat = det.getJSONObject(i);
HashMap<String, String> row = new HashMap<String, String>();
if(!TextUtils.isEmpty(cat.getString("msg_image").toString()))
{
row.put("type", "image");
row.put("details",cat.getString("msg_image").toString());
}
else
{
row.put("type", "text");
String mfv=cat.getString("msg_for_vendor").toString();
if(mfv.equals("1"))
{
row.put("details","Customer: "+cat.getString("msg_text").toString());
}
else{
row.put("details","Me: "+cat.getString("msg_text").toString());
}
}
messageList.add(row);
}
oa.notifyDataSetChanged();
} catch (JSONException e) {
Log.d(getString(R.string.app_name), e.getMessage());
} catch (Exception e) { //connection timeout
Log.d(getString(R.string.app_name), e.getMessage());
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
public void showImage(String imageUri) {
Dialog builder = new Dialog(this);
builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
builder.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
//nothing;
}
});
try {
ImageView imageView = new ImageView(this);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(imageUri).getContent());
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(450, 400);
imageView.setLayoutParams(layoutParams);
imageView.setVisibility(View.VISIBLE);
builder.addContentView(imageView, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
builder.show();
}
}
catch (Exception e)
{
Log.d(getString(R.string.app_name), e.getMessage());
}
}
public void doAction(View v)
{
switch (action)
{
case "setdelivered":{
if(app.setOrderDelivered(order_id)) {
Toast.makeText(this,"Order marked as delivered...",Toast.LENGTH_LONG).show();
bt.setVisibility(View.INVISIBLE);
}
break;
}
case "setaccepted":{
if(app.acceptChatOrder(order_id)){
Toast.makeText(this,"Order accepted...",Toast.LENGTH_LONG).show();
bt.setVisibility(View.INVISIBLE);
}
break;
}
default:
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_mychatorderdetails, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
Intent intent;
//noinspection SimplifiableIfStatement
if (id == R.id.action_logout) {
app = ((MyApplication) getApplicationContext());
app.logOut();
intent = new Intent(mychatorderdetails.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
mychatorderdetails.this.startActivity(intent);
}
mychatorderdetails.this.finish();
return super.onOptionsItemSelected(item);
}
}
Following is the code to display my List ITEMS. I wanted my 5th row item i.e UPI to be enabled copying when long pressed on it. How do I do this? Please edit my code for the same to happen.
Change in layout file: add the below property to your TextView:
android:textIsSelectable="true"
OR
In your Java class write this line to set it programatically:
myTextView.setTextIsSelectable(true);
Copy text:
tv.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("", tv.getText());
clipboard.setPrimaryClip(clip);
Toast.makeText(context, "Copied to clipboard", Toast.LENGTH_SHORT).show();
return true;
}
});
Make sure you have imported android.content.ClipboardManager and NOT android.text.ClipboardManager.
In your row_layout for your ListView, just add the property android:textIsSelectable to the TextView on which you want copying to be allowed.
Related
I am making an attendance system where I take the attendance using RadioGroup with two options. When I select some radio button and scroll down some other radio button gets auto-selected. If I change them upper ones also get changed.
Main class
public class TeacherAttendanceActivity extends AppCompatActivity implements AttendanceAdapter.AttendanceAdapterListner {
public static TeacherAttendanceActivity teacherAttendanceActivity;
private static final String TAG = TeacherAttendanceActivity.class.getSimpleName();
List<AttendanceModel> listItems;
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private AttendanceAdapter attendanceAdapter;
ProgressDialog progressDialog;
private SQLiteHandler db;
private SessionManager session;
private SearchView searchView;
Button btnSubmit;
JSONObject mainObj = new JSONObject();
// date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String currentDateandTime = sdf.format(new Date());
String class_id,title;
Boolean Error;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teacher_attendance);
//get data from intent
class_id = super.getIntent().getExtras().getString("id"); //class_id
title = super.getIntent().getExtras().getString("title");
getSupportActionBar().setTitle("Class: "+title+", Date: "+currentDateandTime );
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
btnSubmit=findViewById(R.id.buttonAttendanceSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Error=false;
Gson gson=new Gson();
final String newDataArray=gson.toJson(listItems); // dataarray is list aaray
for (int i = 0; i < AttendanceAdapter.listItems.size(); i++){
if(AttendanceAdapter.listItems.get(i).getAttendance()==null){
Toast.makeText(TeacherAttendanceActivity.this, "Check attendance at roll:"+AttendanceAdapter.listItems.get(i).getRoll(), Toast.LENGTH_SHORT).show();
Error =true;
break;
}
}
if (!Error){
request(class_id,currentDateandTime,newDataArray);
}
}
});
listItems = new ArrayList<>();
attendanceAdapter = new AttendanceAdapter(listItems, this, (AttendanceAdapter.AttendanceAdapterListner) this);
recyclerView = (RecyclerView) findViewById(R.id.list_attendance);
recyclerView.setLayoutManager(new LinearLayoutManager(TeacherAttendanceActivity.this));
progressDialog = new ProgressDialog(this);
teacherAttendanceActivity = this;
//refresh_list(class_id);
}
#Override
protected void onStart() {
refresh_list(class_id);
super.onStart();
}
#Override
public void onAttendanceAdapterSelected(AttendanceModel model) {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.refresh, menu);
getMenuInflater().inflate(R.menu.tool_bar, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.action_settings:
Toast.makeText(getApplicationContext(),"Sittings",Toast.LENGTH_LONG).show();
return true;
case R.id.action_logout:
logoutUser();
return true;
case R.id.action_about:
Toast.makeText(getApplicationContext(),"About",Toast.LENGTH_LONG).show();
return true;
case R.id.action_devinfo:
Toast.makeText(getApplicationContext(),"Dev info",Toast.LENGTH_LONG).show();
return true;
case R.id.refresh:
refresh_list(class_id);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
// refresh list
public void refresh_list(String id) {
// this method refresh list and get the json data
listItems.clear();
// adapter = new MyAdapter(listItems,getApplicationContext());
recyclerView.setAdapter(attendanceAdapter);
recyclerView.setItemAnimator(new DefaultItemAnimator());
progressDialog.setMessage("Loading");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, ApiConfig.URL_TEACHER_ATTENDANCE+id, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
progressDialog.hide();
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("Data"); // finding data
Log.d(TAG, String.valueOf(jsonObject));
int len = jsonArray.length();
for (int i = 0; i < len; i++) {
JSONObject o = jsonArray.getJSONObject(i);
AttendanceModel item = new AttendanceModel(
o.getString("id"),
o.getString("name"),
o.getString("roll"),
o.getString("class_id"),
o.getString("status"),
null
);
listItems.add(item);
//adapter = new MyAdapter(listItems,getApplicationContext());
recyclerView.setAdapter(attendanceAdapter); // setting them in list view
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.hide();
Toast.makeText(TeacherAttendanceActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}) {
/** Passing some request headers* */
#Override
public Map getHeaders() throws AuthFailureError {
SQLiteHandler db = new SQLiteHandler(getApplicationContext());
HashMap<String,String> userDetail= db.getUserDetails();
String userToken = userDetail.get("token");
Log.d(TAG, String.valueOf(userToken));
HashMap headers = new HashMap();
headers.put("Accept", "application/json");
headers.put("Authorization", "Bearer "+userToken);
return headers;
}
};
stringRequest.setShouldCache(false);
VolleyRequest.getInstance(TeacherAttendanceActivity.this).addToRequestQueue(stringRequest);
}
// take attendance
private void request( final String classId,final String date,final String data ) {
progressDialog.setMessage("Taking attendance");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
ApiConfig.URL_TEACHER_ATTENDANCE_STORE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response);
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
String attendance = jObj.getString("Attendance");
Toast.makeText(TeacherAttendanceActivity.this, attendance, Toast.LENGTH_LONG).show();
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("message");
Toast.makeText(TeacherAttendanceActivity.this,
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(TeacherAttendanceActivity.this, "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(TeacherAttendanceActivity.this,
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
/** Passing some request headers* */
#Override
public Map getHeaders() throws AuthFailureError {
SQLiteHandler db = new SQLiteHandler(TeacherAttendanceActivity.this);
HashMap<String,String> userDetail= db.getUserDetails();
String userToken = userDetail.get("token");
Log.d(TAG, String.valueOf(userToken));
HashMap headers = new HashMap();
headers.put("Accept", "application/json");
headers.put("Authorization", "Bearer "+userToken);
return headers;
}
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("class_id", classId);
params.put("date", date);
params.put("data", data);
return params;
}
};
strReq.setShouldCache(false);
// Adding request to request queue
VolleyRequest.getInstance(TeacherAttendanceActivity.this).addToRequestQueue(strReq);
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
Model class
'model class for convenient '
public class AttendanceModel {
String id,name,roll,classId,previousAttendance,attendance;
public AttendanceModel(String id, String name,String roll, String classId,String previousAttendance,String attedance ){
this.id = id;
this.name = name;
this.classId =classId;
this.roll=roll;
this.attendance=attedance;
this.previousAttendance=previousAttendance;
}
public String getAttendance() {
return attendance;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getRoll() {
return roll;
}
public String getClassId() {
return classId;
}
public String getPreviousAttendance(){return previousAttendance;}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setRoll(String roll) {
this.roll = roll;
}
public void setClassId(String classId) {
this.classId = classId;
}
public void setPreviousAttendance(String previousAttendance) {
this.previousAttendance = previousAttendance;
}
public void setAttendance(String attendance) {
this.attendance = attendance;
}
}
Adapter class
' adapter class '
public class AttendanceAdapter extends RecyclerView.Adapter<AttendanceAdapter.ViewHolder> implements Filterable
{
// date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String currentDateandTime = sdf.format(new Date());
private static final String TAG = AttendanceAdapter.class.getSimpleName();
public static List<AttendanceModel> listItems;
private List<AttendanceModel> listItemsFiltered;
private Context context;
private ProgressDialog dialog;
private AttendanceAdapter.AttendanceAdapterListner listner;
private ProgressDialog pDialog;
private SQLiteHandler db;
public static JSONObject jo = new JSONObject();
public static JSONArray ja = new JSONArray();
public AttendanceAdapter(List<AttendanceModel> listItems, Context context, AttendanceAdapter.AttendanceAdapterListner listner) {
this.listItems = listItems;
this.listner=listner;
this.context = context;
this.listItemsFiltered =listItems;
// SqLite database handler
db = new SQLiteHandler(context);
// Progress dialog
pDialog = new ProgressDialog(context);
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
listItemsFiltered = listItems;
} else {
List<AttendanceModel> filteredList = new ArrayList<>();
for (AttendanceModel row : listItems) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getName().toUpperCase().contains(charSequence.toString().toUpperCase())||row.getName().toLowerCase().contains(charSequence.toString().toLowerCase())) {
filteredList.add(row);
}
}
listItemsFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = listItemsFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
listItemsFiltered = (ArrayList<AttendanceModel>) filterResults.values;
notifyDataSetChanged();
}
};
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public TextView roll;
public TextView previous;
RadioGroup radioAttendance;
RadioButton radioAttendancePresent,radioAttendanceAbsent;
public CardView card_view;
public ViewHolder(View itemView) {
super(itemView);
name= (TextView) itemView.findViewById(R.id.textViewAttendanceStudentName);
roll = (TextView) itemView.findViewById(R.id.textViewAttendanceStudentRoll);
previous = (TextView) itemView.findViewById(R.id.textViewAttendanceStudentPreviousStatus);
radioAttendance = itemView.findViewById(R.id.radioAttendance);
radioAttendancePresent =itemView.findViewById(R.id.radioAttendancePresent);
radioAttendanceAbsent =itemView.findViewById(R.id.radioAttendanceAbsent);
//card_view = (CardView) itemView.findViewById(R.id.class_card_view); // card view for on click method
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View view) {
// send selected contact in callback
listner.onAttendanceAdapterSelected(listItemsFiltered.get(getAdapterPosition())); // selecting cardview and position (model)
}
});
radioAttendance.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
//Toast.makeText(TeacherAttendanceActivity.this, toString(i), Toast.LENGTH_SHORT).show();
// Toast.makeText(context,"clicked at position"+i+" "+id+""+name,Toast.LENGTH_SHORT).show();
if(radioAttendancePresent.isChecked())
{
listItems.get(getAdapterPosition()).setAttendance("present");
}
else {
listItems.get(getAdapterPosition()).setAttendance("absent");
}
}
});
}
}
#Override
public AttendanceAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.attendance_list, parent, false);
return new AttendanceAdapter.ViewHolder(v);
}
#Override
public void onBindViewHolder (final AttendanceAdapter.ViewHolder holder, final int position) {
final AttendanceModel listItem = listItemsFiltered.get(position);
holder.name.setText(listItem.getName());
holder.roll.setText(listItem.getRoll());
holder.previous.setText(listItem.getPreviousAttendance());
}
public interface AttendanceAdapterListner {
void onAttendanceAdapterSelected(AttendanceModel model); // sending cardview to say the dialoge and model for sending context
}
#Override
public int getItemCount() {
return listItemsFiltered.size();
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
Your problem would be solved by making small changes to your Recycler view adapter, please do not disable recyclable property, this makes your recycler view a glorified list view.
I can see you tried using a sparse boolean array to hold the state of the radio buttons, that is good but you do not need that too. The idea behind using a Sparse boolean array is to keep the state of each item in the recycler view so that when they are recycled you still have a reference to what the state of each item is.
In your adapter you already have something that we can use to know the state, that is the attendance property of your model, in that case, you can set the state of your checkboxes by checking if the attendance property is present or absent.
One more thing about your code is that you are using the onCheckChangedListener as a click event handler for your radio button, you should not use this because it responds to all check changed events, even if it is triggered from code and not from user action, so when you bind your view and you set any of your radio buttons as checked or unchecked, it calls this callback.
Here is a modified version of your ViewHolder class that solves this issue by applying the solution above.
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public TextView roll;
public TextView previous;
RadioGroup radioAttendance;
RadioButton radioAttendancePresent, radioAttendanceAbsent;
public CardView card_view;
public ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.textViewAttendanceStudentName);
roll = (TextView) itemView.findViewById(R.id.textViewAttendanceStudentRoll);
previous = (TextView) itemView.findViewById(R.id.textViewAttendanceStudentPreviousStatus);
radioAttendance = itemView.findViewById(R.id.radioAttendance);
radioAttendancePresent = itemView.findViewById(R.id.radioAttendancePresent);
radioAttendanceAbsent = itemView.findViewById(R.id.radioAttendanceAbsent);
radioAttendancePresent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
radioAttendancePresent.setChecked(true);
listItems.get(getAdapterPosition()).setAttendance("present");
}
});
radioAttendanceAbsent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
radioAttendanceAbsent.setChecked(true);
listItems.get(getAdapterPosition()).setAttendance("absent");
}
});
}
void bind(int position) {
// use the sparse boolean array to check
if (listItems.get(position).getAttendance() != null) {
if (listItems.get(position).getAttendance().equals("present")) {
radioAttendancePresent.setChecked(true);
} else if (listItems.get(position).getAttendance().equals("absent")) {
radioAttendanceAbsent.setChecked(true);
}
} else {
radioAttendance.clearCheck();
}
name.setText(listItems.get(position).getName());
roll.setText(listItems.get(position).getRoll());
previous.setText(listItems.get(position).getPreviousAttendance());
}
}
Notice that we have separate click listener for each radio button and set the state in the list of items and just check that state when we are binding, also we have removed the onCheckChangedListener and the sparse boolean array, one last thing is that we made sure that when there is not state set for the attendance property, we just clear the radio buttons so that no one is selected the code is much simpler and works correctly now.
You have to initialize your RadioButton based on model state like below:
#Override
public void onBindViewHolder (final AttendanceAdapter.ViewHolder holder, final int position) {
final AttendanceModel listItem = listItemsFiltered.get(position);
holder.name.setText(listItem.getName());
holder.roll.setText(listItem.getRoll());
holder.previous.setText(listItem.getPreviousAttendance());
final String id =listItem.getId();
final String class_id =listItem.getClassId();
holder.radioAttendance.setOnCheckedChangeListener(null);
if(listItem.getAttendance().equalsIgnoreCase("present")) {
radioAttendancePresent.setChecked(true);
} else {
radioAttendancePresent.setChecked(false);
}
//Add listener here and remove from holder
holder.radioAttendance.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
if(holder.radioAttendancePresent.isChecked()) {
listItemsFiltered.get(position).setAttendance("present");
} else {
listItemsFiltered.get(position).setAttendance("absent");
}
notifyDataSetChanged();
}
});
}
I have an activity in which I have used Recycle View to show all items as a list. On same activity I have given functionality to add new item. Everything is working fine. Items are adding in my database and its showing in list. I have added pagination on Recycle View it is also working fine. What I want that when user add new item at the same time when new data added to database but it is not updating in list. When user press back and again come on activity after that it is showing in list. I want to add add new item at same time without scroll the list or without go back.
TimelineActivity.java
public class TimelineActivity extends AppCompatActivity implements RecyclerView.OnScrollChangeListener {
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView listView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
private TimeLineListAdapter listAdapter;
private List<TimeLineItem> timeLineItems;
private int requestCount = 1;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timeline);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
listView = (RecyclerView) findViewById(R.id.list);
listView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
listView.setLayoutManager(layoutManager);
btnPost = (Button) findViewById(R.id.btnPost);
//Adding an scroll change listener to recyclerview
listView.setOnScrollChangeListener(this);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
cd = new ConnectionDetector(this);
isInternetPresent = cd.isConnectingToInternet();
db = new SQLiteHandler(this);
// session manager
session = new SessionManager(this);
/*pref = getApplicationContext().getSharedPreferences("MayahudiPref", 0);
editor = pref.edit();*/
buttonClickEvent();
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
id = user.get("id");
token = user.get("token");
getData();
timeLineItems = new ArrayList<>();
adapter = new TimeLineListAdapter(timeLineItems, this);
listView.setAdapter(adapter);
Timer autoRefresh;
autoRefresh=new Timer();
autoRefresh.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
getTimeLineData(token, "1");
}
});
}
}, 0, 2000);
}
public void getTimeLineData(final String token, final String page) {
String tag_string_req = "req_register";
// making fresh volley request and getting json
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.timeline, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
String message = jObj.getString("message");
if (error) {
totalPages = jObj.getInt("totalPages");
pageCount = jObj.getInt("page");
int limit = jObj.getInt("limit");
parseJsonFeed(response);
}
} catch (Exception e) {
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("page", page);
params.put("limit", "5");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void parseJsonFeed(String response) {
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray feedArray = jsonObj.getJSONArray("data");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
TimeLineItem item = new TimeLineItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
item.setLname(feedObj.getString("lname"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
if (image.equals("")) {
item.setImge(image);
} else {
item.setImge(AppConfig.storyPic + image);
}
item.setStatus(feedObj.getString("story_text"));
item.setProfilePic(AppConfig.profilePic + feedObj.getString("profile_pic"));
item.setTimeStamp(feedObj.getString("time_stamp"));
item.setIsLike(feedObj.getInt("is_like"));
item.setTotalLikes(feedObj.getString("total_likes"));
item.setTotalComment(feedObj.getString("total_comments"));
/*// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);*/
timeLineItems.add(item);
}
// notify data changes to list adapater
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
//This method will get data from the web API
private void getData() {
//Adding the method to the queue by calling the method getDataFromServer
getTimeLineData(token, String.valueOf(requestCount));
//Incrementing the request counter
requestCount++;
}
//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}
#Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//Ifscrolled at last then
if (isLastItemDisplaying(listView)) {
//Calling the method getdata again
getData();
}
}
public void buttonClickEvent() {
btnPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isInternetPresent) {
String text = txtStatusBox.getText().toString().trim();
if (!text.isEmpty()) {
if (thumbnail != null) {
String image = getStringImage(thumbnail);
JSONObject student2 = new JSONObject();
try {
student2.put("size", "1000");
student2.put("type", "image/jpeg");
student2.put("data", image);
} catch (JSONException e) {
e.printStackTrace();
}
addStory(text, token, String.valueOf(student2));
} else {
addStory(text, token, "");
}
} else {
Toast.makeText(TimelineActivity.this, "Please add some text or image.", Toast.LENGTH_SHORT).show();
}
} else {
final SweetAlertDialog alert = new SweetAlertDialog(TimelineActivity.this, SweetAlertDialog.WARNING_TYPE);
alert.setTitleText("No Internet");
alert.setContentText("No connectivity. Please check your internet.");
alert.show();
}
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
txtStatusBox.setText("");
imgImageUpload.setImageBitmap(null);
imgImageUpload.setBackgroundResource(R.drawable.image);
Toast.makeText(TimelineActivity.this, message, Toast.LENGTH_SHORT).show();
slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
}
});
imgImageUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
/*fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myDialogFragment.show(getFragmentManager(), "MyDialogFragment");
//Toast.makeText(TimelineActivity.this, "Floating Button", Toast.LENGTH_SHORT).show();
}
});*/
}
private void addStory(final String story_text, final String token, final String image) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Please wait ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.addStory, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
message = jObj.getString("message");
if (error) {
txtStatusBox.setText("");
imgImageUpload.setImageBitmap(null);
imgImageUpload.setBackgroundResource(R.drawable.image);
Toast.makeText(TimelineActivity.this, message, Toast.LENGTH_SHORT).show();
slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("message");
Toast.makeText(TimelineActivity.this, errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(TimelineActivity.this, "Oops something went wrong...", Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String
, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("story_text", story_text);
params.put("image", image);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
TimeLineListAdapter.java
public class TimeLineListAdapter extends RecyclerView.Adapter<TimeLineListAdapter.ViewHolder> {
private List<TimeLineItem> timeLineItems;
String message, storyId, token;
private Context context;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public TimeLineListAdapter(List<TimeLineItem> timeLineItems, Context context) {
super();
this.context = context;
this.timeLineItems = timeLineItems;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.timeline_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
//Getting the particular item from the list
TimeLineItem item = timeLineItems.get(position);
if (item.getTotalLikes().equals("0")){
holder.txtLike.setText("");
}else {
holder.txtLike.setText(item.getTotalLikes());
}
if (item.getTotalComment().equals("0")){
holder.txtComment.setText("");
}else {
holder.txtComment.setText("("+item.getTotalComment()+")");
}
if (item.getIsLike() == 0){
}else {
holder.imageLike.setImageBitmap(null);
holder.imageLike.setBackgroundResource(R.drawable.islike);
holder.txtLike.setTextColor(Color.parseColor("#3498db"));
}
holder.name.setText(item.getName() + " " + item.getLname());
/*Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);*/
holder.timestamp.setText(item.getTimeStamp());
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
holder.statusMsg.setText(item.getStatus());
holder.statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
holder.url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
holder.url.setMovementMethod(LinkMovementMethod.getInstance());
holder.url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
holder.url.setVisibility(View.GONE);
}
// user profile pic
holder.profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
holder.feedImageView.setImageUrl(item.getImge(), imageLoader);
holder.feedImageView.setVisibility(View.VISIBLE);
holder.feedImageView
.setResponseObserver(new TimeLineImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
holder.feedImageView.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return timeLineItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView name, timestamp, statusMsg, url, txtLike, txtComment, txtCommentLabel;
NetworkImageView profilePic;
TimeLineImageView feedImageView;
ImageView imageLike;
//Initializing Views
public ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
timestamp = (TextView) itemView.findViewById(R.id.timestamp);
statusMsg = (TextView) itemView.findViewById(R.id.txtStatusMsg);
url = (TextView) itemView.findViewById(R.id.txtUrl);
profilePic = (NetworkImageView) itemView.findViewById(R.id.profilePic);
feedImageView = (TimeLineImageView) itemView.findViewById(R.id.feedImage1);
imageLike = (ImageView) itemView.findViewById(R.id.imgLike);
txtLike = (TextView) itemView.findViewById(R.id.txtLike);
txtComment = (TextView) itemView.findViewById(R.id.txtComment);
txtCommentLabel = (TextView) itemView.findViewById(R.id.txtCommentLabel);
}
}
You have to notifiy dataset changed on listview when new feed is added so there are two things you can do :
Create a new TimeLineItem item when new feed is entered and add new item to it like this :
`
item.setStatus("New Status");
item.setProfilePic("New Profile Pic");
item.setTimeStamp("New TimeStamp");
item.setIsLike("True");
item.setTotalLikes("1000");
item.setTotalComment("2");
`
and then use timeLineItems.add(item) to add new item to ArrayList and call adapter.notifyDataSetChanged(); to get it in view .
2. Again create volley request and it will do it automatically but this is slower then above example.
If you have any query please ask .
You have to set this new list to the adapter.
You can create a setDataSet() method in your adapter and call it before notifydatasetchanged
Add below method in adapter
public void setDataSet(List<TimeLineItem> timeLineItems) {
this.timeLineItems = timeLineItems;
}
and call it before notifydatasetChanged like this:
adapter.setDataSet(timeLineItems);
adapter.notifyDataSetChanged();
i created checkoutpage then it contain total,payment due and payment balance. If give total it show the payment due amount & payment balance amount in mobile app. But it doesn't update the browser?
public class FinalCheckOutActivity extends Activity implements View.OnClickListener {
private AQuery mAQuery;
private TransparentProgressDialog mTransparentProgressDialog;
private String mStrCheckOut = "", mStrGEtData = "", mStrAddressData = "", mStrPaypAl = "";
private Spinner mSpnDefualtAddress, mSpnShipAddress;
private Button mBtnPlaceOrder;
private CheckBox mChBxSameAddres, mChkBxDiffAddress, mChkBoxAccept;
private RadioButton mRdoPayPal, mRdoCash;
private RadioGroup mRdoGroupPay;
private ImageView mIvBack;
private TextView mTvAddAddress, mTvSubTot, mTvDiscount, mTVGrandTot, mTvPendingAmt, mTvPayNow, mIvAddAddress;
private ArrayList<SpinnerData> mArrayListAddres;
private LinearLayout mLinearLayoutShiipingMethod, mLinearLayoutPayMethod, mLinearLayoutOrderDetails;
private RadioGroup mRbnOptionshippingmethods;
private ArrayList<UserAddressData> mArrayListshippingMethod;
private ArrayList<UserAddressData> mArrayListPaymentMethods;
private String shippingMethodId;
private RadioGroup mRbnOptionPaymentMethods;
private String shippingPaymentID;
private View viewOrderData;
private JSONObject mJsonObject, jsonObjectData;
private LinearLayout mLinearLayoutTabShiping;
private RadioButton newRadioButton;
private ArrayList<SpinnerData> mArrayListBilign;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_final_check_out);
//setUI();
}
private void setUI() {
mAQuery = new AQuery(this);
mTransparentProgressDialog = new TransparentProgressDialog(this, R.drawable.ic_loader_image);
mSpnDefualtAddress = (Spinner) findViewById(R.id.spn_default_address);
mSpnShipAddress = (Spinner) findViewById(R.id.spn_ship_address);
mBtnPlaceOrder = (Button) findViewById(R.id.btn_place_order);
mRdoGroupPay = (RadioGroup) findViewById(R.id.rdo_payment);
mRdoCash = (RadioButton) findViewById(R.id.rdo_cash);
mRdoPayPal = (RadioButton) findViewById(R.id.rdo_paypal);
mLinearLayoutTabShiping = (LinearLayout) findViewById(R.id.layout_shiping);
mChBxSameAddres = (CheckBox) findViewById(R.id.chk_ship_to_same_address);
mChkBxDiffAddress = (CheckBox) findViewById(R.id.chk_diff_ship_address);
mChkBoxAccept = (CheckBox) findViewById(R.id.chk_acceept);
mLinearLayoutShiipingMethod = (LinearLayout) findViewById(R.id.layout_shipping_method);
mLinearLayoutPayMethod = (LinearLayout) findViewById(R.id.layout_payment_method);
mLinearLayoutOrderDetails = (LinearLayout) findViewById(R.id.lv_shipping_order_view);
mIvAddAddress = (TextView) findViewById(R.id.img_add_address);
mTvSubTot = (TextView) findViewById(R.id.tv_subtotal);
mTvDiscount = (TextView) findViewById(R.id.tv_discount);
mTVGrandTot = (TextView) findViewById(R.id.tv_grand_tot);
mTvPendingAmt = (TextView) findViewById(R.id.tv_pending_pay);
mTvPayNow = (TextView) findViewById(R.id.tv_payable_now);
mIvBack = (ImageView) findViewById(R.id.img_back_one_page);
mArrayListAddres = new ArrayList<>();
mArrayListshippingMethod = new ArrayList<>();
mArrayListPaymentMethods = new ArrayList<>();
mArrayListBilign = new ArrayList<>();
mBtnPlaceOrder.setOnClickListener(this);
mIvAddAddress.setOnClickListener(this);
// mTvAddAddress.setOnClickListener(this);
mIvBack.setOnClickListener(this);
ajaxCallback.setTimeout(Integer.parseInt(getString(R.string.ajax_timeout)));
mChBxSameAddres.setChecked(true);
mLinearLayoutTabShiping.setVisibility(View.GONE);
mChBxSameAddres.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mLinearLayoutTabShiping.setVisibility(View.GONE);
//mSpnShipAddress.setVisibility(View.GONE);
// perform logic
}
}
});
mChkBxDiffAddress.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mChBxSameAddres.setChecked(false);
mLinearLayoutTabShiping.setVisibility(View.VISIBLE);
}
}
});
SpinnerData data = new SpinnerData();
data.setmStrName("Select Address");
mArrayListAddres.add(data);
mSpnDefualtAddress.setAdapter(new SpinnerAdapter(this, mArrayListAddres));
getFinalCheckOutData();
}
#Override
protected void onResume() {
super.onResume();
setUI();
//getAddressData();
}
/**
* get user address web service call
**/
private void getAddressData() {
mStrAddressData = getString(R.string.WS_HOST) + getString(R.string.WS_GET_MULTIPLE_ADDRESS);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("customer_id", SessionClass.getUserId(this));
Log.e("Hash map final data", "Hash map->" + hashMap.toString());
if (AvailableNetwork.isConnectingToInternet(this)) {
mAQuery.progress(mTransparentProgressDialog).ajax(mStrAddressData, hashMap, JSONObject.class, ajaxCallback);
} else {
// showAlert(getString(R.string.no_internt_connection), -1);
Snackbar snackbar = Snackbar
.make(MainActivity.coordinatorLayout, R.string.no_internt_connection, Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
//setUI(view);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) sbView.getLayoutParams();
params.gravity = Gravity.TOP;
sbView.setLayoutParams(params);
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
/**
* get user address web service call
**/
private void getPaypalData() {
mStrPaypAl = getString(R.string.WS_HOST) + getString(R.string.WS_PAYPAL);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("order_increment_id", orderID);
Log.e("Hash map final data", "Hash map->" + hashMap.toString());
if (AvailableNetwork.isConnectingToInternet(this)) {
mAQuery.progress(mTransparentProgressDialog).ajax(mStrPaypAl, hashMap, JSONObject.class, ajaxCallback);
} else {
// showAlert(getString(R.string.no_internt_connection), -1);
Snackbar snackbar = Snackbar
.make(MainActivity.coordinatorLayout, R.string.no_internt_connection, Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
//setUI(view);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) sbView.getLayoutParams();
params.gravity = Gravity.TOP;
sbView.setLayoutParams(params);
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
/**
* Get final checkout data
**/
private void getFinalCheckOutData() {
mStrGEtData = getString(R.string.WS_HOST) + getString(R.string.WS_FINAL_CHECKOUT_DETAIls);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("cart_id", IntermediateCheckoutActivity.cartId);
Log.e("Hash map final data", "Hash map->" + hashMap.toString());
if (AvailableNetwork.isConnectingToInternet(this)) {
mAQuery.progress(mTransparentProgressDialog).ajax(mStrGEtData, hashMap, JSONObject.class, ajaxCallback);
} else {
// showAlert(getString(R.string.no_internt_connection), -1);
Snackbar snackbar = Snackbar
.make(MainActivity.coordinatorLayout, R.string.no_internt_connection, Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
//setUI(view);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) sbView.getLayoutParams();
params.gravity = Gravity.TOP;
sbView.setLayoutParams(params);
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
/**
* Place order web service call
**/
private void placeOrder() {
mStrCheckOut = getString(R.string.WS_HOST) + getString(R.string.WS_PLACE_ORDER);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("cart_id", IntermediateCheckoutActivity.cartId);
hashMap.put("checkoutdetails", jsonObjectData.toString());
Log.e("Place order", "hash map-->" + hashMap.toString());
if (AvailableNetwork.isConnectingToInternet(this)) {
mAQuery.progress(mTransparentProgressDialog).ajax(mStrCheckOut, hashMap, JSONObject.class, ajaxCallback);
} else {
//showAlert(getString(R.string.no_internt_connection), -1);
Snackbar snackbar = Snackbar
.make(MainActivity.coordinatorLayout, R.string.no_internt_connection, Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
//setUI(view);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) sbView.getLayoutParams();
params.gravity = Gravity.TOP;
sbView.setLayoutParams(params);
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
private boolean checkValidationn() {
if (mSpnDefualtAddress.getSelectedItemPosition() == 0) {
showAlert("Please select billing address first.", -1);
mSpnDefualtAddress.requestFocus();
return false;
} else if (mRbnOptionshippingmethods.getCheckedRadioButtonId() == -1) {
showAlert("Please select shipping method first.", -1);
mRbnOptionshippingmethods.requestFocus();
return false;
} else if (mRdoGroupPay.getCheckedRadioButtonId() == -1) {
showAlert("Please select payment method first.", -1);
mRdoGroupPay.requestFocus();
return false;
} else if (!mChkBoxAccept.isChecked()) {
showAlert("Please select terms and conditions first.", -1);
mChkBoxAccept.requestFocus();
return false;
}
return true;
}
private void showAlert(String message, final int flg) {
AlertDialog.Builder aBuilder = new AlertDialog.Builder(this);
aBuilder.setCancelable(false);
aBuilder.setMessage(message);
aBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
setNxtFlg(flg);
}
});
aBuilder.create();
aBuilder.show();
}
private void setNxtFlg(int flg) {
switch (flg) {
case 3:
Intent intent = new Intent(FinalCheckOutActivity.this, PayPalPaymentActivity.class);
intent.putExtra("key", urlMain);
intent.putExtra("order_id", orderID);
overridePendingTransition(R.anim.anim_left_in, R.anim.anim_left_out);
startActivity(intent);
break;
case 1:
Intent intent1 = new Intent(FinalCheckOutActivity.this, MainActivity.class);
intent1.putExtra("key", "4");
startActivity(intent1);
overridePendingTransition(R.anim.anim_left_in, R.anim.anim_left_out);
break;
}
}
#Override
public void onClick(View v) {
Intent intent;
switch (v.getId()) {
case R.id.btn_place_order:
getCheckOutData();
if (checkValidationn()) {
placeOrder();
}
break;
case R.id.img_back_one_page:
onBackPressed();
//finish();
overridePendingTransition(R.anim.anim_left_in, R.anim.anim_left_out);
break;
case R.id.img_add_address:
intent = new Intent(FinalCheckOutActivity.this, CheckoutActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.anim_left_in, R.anim.anim_left_out);
break;
/*case R.id.txt_add_address:
intent = new Intent(FinalCheckOutActivity.this, AddUserAddressActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.anim_left_in, R.anim.anim_left_out);
//finish();
break;*/
}
}
private void getCheckOutData() {
mJsonObject = new JSONObject();
jsonObjectData = new JSONObject();
try {
if (mChBxSameAddres.isChecked()) {
jsonObjectData.put("billing_id", mArrayListAddres.get(mSpnDefualtAddress.getSelectedItemPosition()).getmStrId());
jsonObjectData.put("shipping_id", mArrayListAddres.get(mSpnDefualtAddress.getSelectedItemPosition()).getmStrId());
} else {
// jsonObjectData.put("shipping_id", mArrayListAddres.get(mSpnShipAddress.getSelectedItemPosition()).getmStrId());
}
if (mChkBxDiffAddress.isChecked()) {
jsonObjectData.put("billing_id", mArrayListAddres.get(mSpnDefualtAddress.getSelectedItemPosition()).getmStrId());
jsonObjectData.put("shipping_id", mArrayListAddres.get(mSpnShipAddress.getSelectedItemPosition()).getmStrId());
} else {
jsonObjectData.put("shipping_id", mArrayListAddres.get(mSpnDefualtAddress.getSelectedItemPosition()).getmStrId());
}
JSONObject mJsonObjectPay = new JSONObject();
if (mRdoCash.isChecked()) {
shippingPaymentID = "checkmo";
mJsonObjectPay.put("method", shippingPaymentID);
} else if (mRdoPayPal.isChecked()) {
shippingPaymentID = "paypaladaptive";
mJsonObjectPay.put("method", shippingPaymentID);
}
jsonObjectData.put("payment", mJsonObjectPay);
jsonObjectData.put("shipping_method", shippingMethodId);
jsonObjectData.put("checkout_method", "customer");
jsonObjectData.put("onestepcheckout_feedback_freetext", "");
jsonObjectData.put("accept_terms", 1);
jsonObjectData.put("customer_id", SessionClass.getUserId(FinalCheckOutActivity.this));
mJsonObject.put("checkoutdetails", jsonObjectData);
//showAlert("place order array" + jsonObjectData.toString(), -1);
//Log.e("Place order", "Data-->" + jsonObjectData.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
private String orderID;
private String urlMain;
/**
* web service responce
**/
AjaxCallback<JSONObject> ajaxCallback = new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject object, AjaxStatus status) {
super.callback(url, object, status);
Log.e("Check out", "Url-->" + url);
Log.e("Check out", "Responce-->" + object);
if (object != null) {
if (status.getCode() == 200) {
if (mTransparentProgressDialog.isShowing()) {
mTransparentProgressDialog.dismiss();
}
if (url.equalsIgnoreCase(mStrAddressData)) {
try {
if (object.getString("errorcode").equalsIgnoreCase("0")) {
setAddressData(object.getJSONArray("data"));
//getFinalCheckOutData();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else if (url.equalsIgnoreCase(mStrGEtData)) {
try {
String now = getIntent().getExtras().getString("pay_now");
String due = getIntent().getExtras().getString("pay_due");
if (object.getString("errorcode").equalsIgnoreCase("0")) {
JSONObject mJsonObject = object.getJSONObject("data");
setShippingMethods(mJsonObject.getJSONArray("shippingmethods"));
setPaymentMethods(mJsonObject.getJSONArray("paymentmethods"));
if (!mJsonObject.isNull("items")) {
setOrderView(mJsonObject.getJSONArray("items"));
}
mTvSubTot.setText(mJsonObject.getString("subtotal"));
mTvDiscount.setText(mJsonObject.getString("discount"));
mTVGrandTot.setText(mJsonObject.getString("grandtotal"));
// mTvPendingAmt.setText(mJsonObject.getString("pendingpayment"));
// mTvPayNow.setText(mJsonObject.getString("payablenow"));
mTvPendingAmt.setText(now);
mTvPayNow.setText(due);
getAddressData();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else if (url.equalsIgnoreCase(mStrCheckOut)) {
try {
if (object.getString("errorcode").equalsIgnoreCase("0")) {
//showAlert("Your order placed successfully.", -1);
if (shippingPaymentID.equalsIgnoreCase("paypaladaptive")) {
JSONObject mJsonObject = object.getJSONObject("data");
orderID = mJsonObject.getString("order_increment_id");
getPaypalData();
} else {
showAlert("Your order placed successfully.", 1);
}
//SessionClass.logout(FinalCheckOutActivity.this);
SessionClass.setUrerCartId(FinalCheckOutActivity.this, "");
} else if (object.getString("errorcode").equalsIgnoreCase("1")) {
showAlert("There is error in order creation.", -1);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else if (url.equalsIgnoreCase(mStrPaypAl)) {
try {
if (object.getString("errorcode").equalsIgnoreCase("0")) {
JSONObject mJsonObject = object.getJSONObject("data");
urlMain = mJsonObject.getString("url").replace("/\\/", "");
Log.e("Final url", "Url-->" + urlMain);
showAlert("Click on ok to continue.", 3);
} else if (object.getString("errorcode").equalsIgnoreCase("2")) {
showAlert("Paypal API call failed. Account not found. Unilateral receiver not allowed in chained payment is restricted.", -1);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
// showAlert(getString(R.string.no_connection_server), -1);
Snackbar snackbar = Snackbar
.make(MainActivity.coordinatorLayout, R.string.no_connection_server, Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
//setUI(view);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) sbView.getLayoutParams();
params.gravity = Gravity.TOP;
sbView.setLayoutParams(params);
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
}
};
/**
* Set order view data from web servicie responce
**/
private void setOrderView(JSONArray items) {
try {
mLinearLayoutOrderDetails.removeAllViews();
//mArrayListMethod.clear();
for (int i = 0; i < items.length(); i++) {
JSONObject mJsonObject = items.getJSONObject(i);
viewOrderData = getLayoutInflater().inflate(R.layout.single_chkout_order_listing, null);
TextView mTvName = (TextView) viewOrderData.findViewById(R.id.tv_order_name);
TextView mTvPrice = (TextView) viewOrderData.findViewById(R.id.tv_order_price);
TextView mTvQuan = (TextView) viewOrderData.findViewById(R.id.tv_order_quantity);
TextView mTvSubTot = (TextView) viewOrderData.findViewById(R.id.tv_order_sub_total);
mTvName.setText(mJsonObject.getString("name"));
mTvPrice.setText(mJsonObject.getString("price"));
mTvQuan.setText(mJsonObject.getString("quantity"));
mTvSubTot.setText(mJsonObject.getString("rowtotal"));
mLinearLayoutOrderDetails.addView(viewOrderData);
}
} catch (Exception e) {
e.printStackTrace();
}
}
i have an activity with recyclerview that extends fragment activity.
When an item is clicked from a recyerview, i want to get the title and display it as a pop up message.
i tried several ways but noting works. cam some one help me to do this TNX.
PickupActivity
public class PickupActivity extends AppCompatActivity implements View.OnClickListener{
private Toolbar toolbar;
private navigationDrawerFragment drawerFragment;
ApplicationEnvironmentURL applicationEnvironment;
ProgressDialog pDialog;
Context context;
String BASEURL;
String FilteredData;
String AllAgents;
public String ProfileId;
public String companyId;
public String profileToken;
private com.github.clans.fab.FloatingActionButton pik_fab1;
private com.github.clans.fab.FloatingActionButton pik_fab2;
private com.github.clans.fab.FloatingActionButton pik_fab3;
private com.github.clans.fab.FloatingActionButton pik_fab4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Dashboard");
setContentView(R.layout.activity_pickup);
applicationEnvironment = new ApplicationEnvironmentURL(this.context);
context = this.getApplicationContext();
toolbar = (Toolbar) findViewById(R.id.app_bar_dashboard);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (navigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setup(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
pik_fab1 = (com.github.clans.fab.FloatingActionButton) findViewById(R.id.pickup_delete);
pik_fab2 = (com.github.clans.fab.FloatingActionButton) findViewById(R.id.pickup_close);
pik_fab3 = (com.github.clans.fab.FloatingActionButton) findViewById(R.id.pickup_assignto);
pik_fab4 = (com.github.clans.fab.FloatingActionButton) findViewById(R.id.pickup_pickup);
pik_fab1.setOnClickListener(this);
pik_fab2.setOnClickListener(this);
pik_fab3.setOnClickListener(this);
pik_fab4.setOnClickListener(this);
SharedPreferences prefs = getSharedPreferences("zupportdesk", MODE_PRIVATE);
String islogged = prefs.getString("islogged", "Not defined");
String userid = prefs.getString("userid", "Not defined");
profileToken = prefs.getString("profileToken", "Not defined");
companyId = prefs.getString("companyId", "Not defined");
String companyName = prefs.getString("companyName", "Not defined");
ProfileId = prefs.getString("ProfileId", "Not defined");
Log.d("islogged : ", islogged);
Log.d("userid : ", userid);
Log.d("profileToken : ", profileToken);
Log.d("companyId : ", companyId);
Log.d("companyName : ", companyName);
Log.d("ProfileId : ", ProfileId);
getTickets(ProfileId, companyId, profileToken);
View newTicket = findViewById(R.id.newtic);
newTicket.setOnClickListener(onClickListener);
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.pickup_pickup:
Log.d("Fab_clicked", "Pickup Ticket");
pickupTicketMessage("Are you sure you want to pickup the selected tickets?", "Confirm?");
break;
case R.id.pickup_close:
Log.d("Fab_clicked", "close tickets");
closeTicketMessage("Are you sure you want to close the selected tickets?", "Confirm?");
break;
case R.id.pickup_delete:
Log.d("Fab_clicked", "close tickets");
DeleteTicketMessage("Are you sure you want to delete the selected tickets?", "Confirm?");
break;
case R.id.pickup_assignto:
Log.d("Fab_clicked", "Assign to Agent");
try {
assignTicketstMessage("Select an agent");
} catch (JSONException e) {
e.printStackTrace();
}
break;
}
}
/* Multiple Button on click event handle */
private View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(final View v) {
switch(v.getId()){
case R.id.newtic:
// Create a login URl, before starting anything
if(isNetworkAvailable()){
Intent intentTicket = new Intent(PickupActivity.this, NewTicket.class);
startActivity(intentTicket);
} else {showErrorMessage("Please check your internet connection.", "No Connectivity!"); }
break;
}
}
};
public void getTickets(String profileId, String companyId, String profileToken) {
if (isNetworkAvailable()) {
try {
setFilteredDataURL(companyId, profileId);
FilteredData = new getFilteredData().execute(profileToken).get();
// adding the filtered data to shared preferences for further use.
//adding user data to shared preferences.
SharedPreferences.Editor editor = getSharedPreferences("zupportdesk", MODE_PRIVATE).edit();
editor.putString("FilteredData", FilteredData);
editor.commit();
Log.d("ZF-Filtered_Data", FilteredData);
setTicketsURL(profileId, companyId);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
new getNewTickets().execute(profileToken);
} else {
showErrorMessage("Please check your internet connection.", "No Connectivity!");
}
}
private void PickupTicket() throws JSONException {
JSONObject jsonObject = new JSONObject();
JSONArray TicketsArray = new JSONArray();
List<Integer> selected_item = new ArrayList<>();
for (PickupTicketsItemObject ticket : PickupActivityFragment.support_ticket) {
if (ticket.isSelected()) {
selected_item.add(Integer.valueOf(ticket.getTicket_id()));
TicketsArray.put(Integer.valueOf(ticket.getTicket_id()));
}
}
Log.d("pickup_ticket_size", String.valueOf(selected_item.size()));
if(selected_item.size() < 1){
Log.d("pickup_ticket_size", "empty");
//Show Error Message
}else {
Log.d("pickup_ticket_size", "have tickets");
jsonObject.put("TicketID", TicketsArray);
jsonObject.put("ProfileId", ProfileId);
jsonObject.put("CompanyID", companyId);
setPickupTicketURI();
Log.d("ZF-PickupTicket", String.valueOf(jsonObject));
new TicketPickupRequest().execute(String.valueOf(jsonObject), profileToken);
}
}
private void showSuccessMessage(String data, String title){
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(data)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// restart Activity
finish();
startActivity(getIntent());
}
})
.setIcon(R.drawable.notification_success)
.show();
}
private void assignTicketstMessage(String title) throws JSONException {
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle(title);
final List<String> agentList = new ArrayList<String>();
final List<String> agentProfileIDList = new ArrayList<String>();
if(AllAgents != null && !AllAgents.isEmpty() && !AllAgents.equals("null")) {
JSONArray jsonarray = new JSONArray(AllAgents);
int count = jsonarray.length();
Log.d("Full Agents", String.valueOf(count));
for (int k = 0; k < jsonarray.length(); k++) {
JSONObject jsonobject5 = jsonarray.getJSONObject(k);
Log.d("Agent object ", String.valueOf(jsonobject5));
agentList.add(jsonobject5.getString("FirstName"));
agentProfileIDList.add(jsonobject5.getString("ProfileId"));
}
String[] types = new String[agentList.size()];
for (int j = 0; j < agentList.size(); j++) {
types[j] = agentList.get(j);
}
b.setItems(types, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d("Selected_no ", String.valueOf(which));
Log.d("Selected_agent ", String.valueOf(agentList.get(which)));
Log.d("Selected_profile_id ", String.valueOf(agentProfileIDList.get(which)));
dialog.dismiss();
assignTicketstMessage2(String.valueOf(agentList.get(which)), String.valueOf(agentProfileIDList.get(which)));
}
});
b.show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent i = new Intent(getApplicationContext(),Settings.class);
startActivity(i);
return true;
}
if(id == R.id.home){
NavUtils.navigateUpFromSameTask(this);
}
//noinspection SimplifiableIfStatement
if (id == R.id.notification){
Intent i = new Intent(getApplicationContext(), Notifications.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private void showErrorMessage(String data, String title) {
new AlertDialog.Builder(this.context)
.setTitle(title)
.setMessage(data)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.setIcon(R.drawable.notification_red)
.show();
}
private void showErrorMessageNoInbox(String data, String title) {
new AlertDialog.Builder(this.context)
.setTitle(title)
.setMessage(data)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
Intent i = new Intent(getApplicationContext(), Login.class);
startActivity(i);
}
})
.setIcon(R.drawable.notification_red)
.show();
}
public HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
......................... More
PickupActivityFragment
public class PickupActivityFragment extends Fragment {
public static ArrayList<PickupTicketsItemObject> support_ticket;
public static RecyclerView Ticketslist;
PickupActivity pick_up_activity;
public PickupActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_pickup_fragment, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
pick_up_activity = new PickupActivity();
Ticketslist = (RecyclerView) view.findViewById(R.id.pickup_list);
Ticketslist.setLayoutManager(new LinearLayoutManager(getActivity()));
Ticketslist.setHasFixedSize(true);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
pick_up_activity = new PickupActivity();
}
}
PickupTicketsAdapter
public class PickupTicketsAdapter extends RecyclerView.Adapter<PickupTicketsAdapter.ViewHolder> {
ArrayList<PickupTicketsItemObject> all_tickets;
public PickupTicketsAdapter(List<PickupTicketsItemObject> tickets) {
this.all_tickets = new ArrayList<>(tickets);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_pick_tickets, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.bindData(all_tickets.get(position));
//in some cases, it will prevent unwanted situations
holder.checkbox.setOnCheckedChangeListener(null);
//if true, your checkbox will be selected, else unselected
holder.checkbox.setChecked(all_tickets.get(position).isSelected());
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
all_tickets.get(holder.getAdapterPosition()).setSelected(isChecked);
}
});
}
#Override
public int getItemCount() {
return all_tickets.size();
}
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public ImageView priority;
public TextView sts_open;
public TextView sts_overdue;
public TextView tkt_from;
public TextView tkt_subject;
public TextView tkt_assignedto;
public TextView tkt_created_date;
public TextView txt_ticket_id;
public CheckBox checkbox;
public ViewHolder(View v) {
super(v);
checkbox = (CheckBox) v.findViewById(R.id.pick_checkbox);
priority = (ImageView) v.findViewById(R.id.priority_status_icon);
sts_open= (TextView) v.findViewById(R.id.tv_Tk_opn_status);
sts_overdue = (TextView) v.findViewById(R.id.tv_Tk_overdue);
tkt_from = (TextView) v.findViewById(R.id.tv_Tk_from);
tkt_subject = (TextView) v.findViewById(R.id.tv_Tk_subject);
tkt_assignedto = (TextView) v.findViewById(R.id.tv_Tk_Assignedto);
tkt_created_date = (TextView) v.findViewById(R.id.tv_Tk_Created_date);
txt_ticket_id = (TextView) v.findViewById(R.id.tv_Tk_TicketID);
}
public void bindData(PickupTicketsItemObject ticket) {
priority.setImageResource(ticket.getStatus_priority());
sts_open.setText(ticket.getStatus_open());
sts_overdue.setText(ticket.getStatus_overdue());
tkt_from.setText(ticket.getTicket_from());
tkt_subject.setText(ticket.getTicket_subject());
tkt_assignedto.setText(ticket.getTicket_assignedto());
tkt_created_date.setText(ticket.getTicket_created_date());
txt_ticket_id.setText(ticket.getTicket_id());
}
}
}
PickupTicketsItemObject
public class PickupTicketsItemObject {
private int status_priority;
private String status_open;
private String status_overdue;
private String ticket_from;
private String ticket_subject;
private String ticket_assignedto;
private String ticket_created_date;
private String ticket_id;
private boolean isSelected;
public PickupTicketsItemObject(){
}
public int getStatus_priority() {
return status_priority;
}
public String getStatus_open() {
return status_open;
}
public String getStatus_overdue() {
return status_overdue;
}
public String getTicket_from() {
return ticket_from;
}
public String getTicket_subject() {
return ticket_subject;
}
public String getTicket_assignedto() {
return ticket_assignedto;
}
public String getTicket_created_date(){return ticket_created_date;}
public String getTicket_id(){return ticket_id;}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public void setStatus_priority(int status_priority) {
this.status_priority = status_priority;
}
public void setStatus_open(String status_open) {
this.status_open = status_open;
}
public void setStatus_overdue(String status_overdue) {
this.status_overdue = status_overdue;
}
public void setTicket_from(String ticket_from) {
this.ticket_from = ticket_from;
}
public void setTicket_subject(String ticket_subject) {
this.ticket_subject = ticket_subject;
}
public void setTicket_assignedto(String ticket_assignedto) {
this.ticket_assignedto = ticket_assignedto;
}
public void setTicket_created_date(String ticket_created_date) {
this.ticket_created_date = ticket_created_date;
}
public void setTicket_id(String ticket_id) {
this.ticket_id = ticket_id;
}
}
public void onBindViewHolder(.....)
for particular TextView and use AlertDialog to show message inside adapter.
All you need to do is make changes in your adapter class
In your ViewHolder class, declare a CardView object as well.
Then in the onBindViewHolder method you can set the holder.cardview.onClickListener
You can use alert dialog builder for showing popups
I have implemented a small shopping cart project, there is a list of products with a button. When i click a "ADD" button it will change the button name "ADD" to "REMOVE" and color also changing Green to Red. Here my problem is if i revisit the products form clicked button should be "REMOVE" and red color. So how to add clicked button position to session.
My code:
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
#Override
public View getView(final int position, View convertView, ViewGroup arg2) {
final ViewHolderGrid holderForGrid;
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.consumer_catalog_list_item, null);
holderForGrid = new ViewHolderGrid(convertView);
convertView.setTag(holderForGrid);
} else {
holderForGrid = (ViewHolderGrid) convertView.getTag();
}
final BusinessCatalogVariables Catalog = catalogList.get(position);
holderForGrid.AddtoCart.setClickable(false);
holderForGrid.AddtoCart.setTag(position);
if (catalogList.get(position).isAdded()) {
holderForGrid.AddtoCart.setText("Remove");
holderForGrid.AddtoCart.setBackgroundResource(R.drawable.btnred);
} else {
holderForGrid.AddtoCart.setText("Add to Cart");
holderForGrid.AddtoCart.setBackgroundResource(R.drawable.buttonsignup);
}
if (Pref_Storage.checkDetail(context, Items)) {
holderForGrid.AddtoCart.setText("Remove");
holderForGrid.AddtoCart.setBackgroundResource(R.drawable.btnred);
Toast.makeText(context, Items, Toast.LENGTH_SHORT).show();
} else {
holderForGrid.AddtoCart.setText("Add to Cart");
holderForGrid.AddtoCart.setBackgroundResource(R.drawable.buttonsignup);
}
holderForGrid.AddtoCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Position = (Integer) v.getTag();
Log.d("ADD BUTTON POSITION:", "position=" + position);
if (holderForGrid.AddtoCart.getText().equals("Add to Cart")) {
catalogList.get(position).setAdded(true);
holderForGrid.AddtoCart.setText("Remove");
holderForGrid.AddtoCart.setBackgroundResource(R.drawable.btnred);
Items = String.valueOf(Position);
Pref_Storage.setDetail(context, Items, "added");
//
} else if (holderForGrid.AddtoCart.getText().equals("Remove")) {
catalogList.get(position).setAdded(false);
holderForGrid.AddtoCart.setBackgroundResource(R.drawable.buttonsignup);
holderForGrid.AddtoCart.setText("Add to Cart");
Items = String.valueOf(Position);
Pref_Storage.deleteKey(context,Items);
}
}
});
return convertView;
}
You have to use setTag(),getTag() method,
Class Pref_Storage.java [For storing products id]
public class Pref_Storage {
private static SharedPreferences sharedPreferences = null;
public static void openPref(Context context) {
sharedPreferences = context.getSharedPreferences(context.getResources().getString(R.string.app_name),
Context.MODE_PRIVATE);
}
public static void deleteKey(Context context, String key) {
HashMap<String, String> result = new HashMap<String, String>();
Pref_Storage.openPref(context);
for (Entry<String, ?> entry : Pref_Storage.sharedPreferences.getAll()
.entrySet()) {
result.put(entry.getKey(), (String) entry.getValue());
}
boolean b = result.containsKey(key);
if (b) {
Pref_Storage.openPref(context);
Editor prefsPrivateEditor = Pref_Storage.sharedPreferences.edit();
prefsPrivateEditor.remove(key);
prefsPrivateEditor.commit();
prefsPrivateEditor = null;
Pref_Storage.sharedPreferences = null;
}
}
public static void setDetail(Context context, String key, String value) {
Pref_Storage.openPref(context);
Editor prefsPrivateEditor = Pref_Storage.sharedPreferences.edit();
prefsPrivateEditor.putString(key, value);
prefsPrivateEditor.commit();
prefsPrivateEditor = null;
Pref_Storage.sharedPreferences = null;
}
public static Boolean checkDetail(Context context, String key) {
HashMap<String, String> result = new HashMap<String, String>();
Pref_Storage.openPref(context);
for (Entry<String, ?> entry : Pref_Storage.sharedPreferences.getAll()
.entrySet()) {
result.put(entry.getKey(), (String) entry.getValue());
}
boolean b = result.containsKey(key);
return b;
}
}
And in Adapter Class you have to check:
if(Pref_Storage.checkDetail(context, pid)){
holderForGrid.AddtoCart.setText("Remove");
}
else{
holderForGrid.AddtoCart.setText("Add to Cart");
}
holderForGrid.AddtoCart.setTag(position);
holderForGrid.AddtoCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int pos = (int) v.getTag();
Button btn=(Button)v;
if (btn.getText().equals("Add to Cart")) {
catalogList.get(position).setAdded(true);
btn.setText("Remove");
btn.setBackgroundResource(R.drawable.btnred);
Pref_Storage.setDetail(context, pid, "added");
} else if (btn.getText().equals("Remove")) {
catalogList.get(position).setAdded(false);
btn.setBackgroundResource(R.drawable.buttonsignup);
btn.setText("Add to Cart");
Pref_Storage.deleteKey(context,pid);
}
}
});
Try this.
if (catalogList.get(position).isAdded()) {
holderForGrid.AddtoCart.setText("Remove");
holderForGrid.AddtoCart.setBackgroundResource(R.drawable.btnred);
} else {
holderForGrid.AddtoCart.setText("Add to Cart");
holderForGrid.AddtoCart.setBackgroundResource(R.drawable.buttonsignup);
}