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
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();
}
});
}
My app has an itinerary function, the part where you create a new itinerary involves selecting from 2 spinners which drop down to present different options. The data coming from MQsql database and the JSON response is correct for both sets. Currently i have been able to get either one set of the data to load in the correct spinner (being which either just transport info or attraction info but not both), or i have been able to get both sets of data to load but both are displayed in the same 2 spinners. I need them to be separated into there allocated spinners but need help doing this as i dont undertand what im doing wrong.
createItinerary class:
public class CreateItinerary extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
TextView txtDate;
private Spinner spinnerAttraction;
private Spinner spinnerTransport;
// array list for spinner adapter
private ArrayList<Category> categoriesList;
ProgressDialog pDialog;
List<String> lables = new ArrayList<String>();
private ArrayList<ItineraryAdapter>Entities;
private ArrayList<ItineraryAdapter>finalEntities;
LayoutInflater myInflator;
View myView;
DBManager db;
myAdapter adapter;
String NAME;
String LOCATION;
String TIME;
static final int DIALOG_ID = 0;
int hour_x;
int min_x;
TextView TextTime;
String ItineraryName;
private String URL_ATTRACTIONS = "http://10.0.2.2/TravelApp/get_all_spinner.php";
private String URL_TRANSPORT = "http://10.0.2.2/TravelApp/get_all_transport_minor.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_itinerary);
txtDate = (TextView) findViewById(R.id.tvSelectDate);
myInflator = getLayoutInflater();
myView = myInflator.inflate(R.layout.list_create_itinerary, null);
spinnerAttraction = (Spinner) findViewById(R.id.spinnerAttraction);
spinnerTransport = (Spinner) findViewById(R.id.spinnerTransport);
db = new DBManager(this);
categoriesList = new ArrayList<Category>();
Entities = new ArrayList<ItineraryAdapter>();
finalEntities = new ArrayList<ItineraryAdapter>();
// spinner item select listener
spinnerAttraction.setOnItemSelectedListener(this);
spinnerTransport.setOnItemSelectedListener(this);
new GetAttractions().execute();
new GetTransport().execute();
showTimePickerDialog();
Bundle bundle = getIntent().getExtras();
ItineraryName = bundle.getString("Itinerary Name");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_button, 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.go_home){
final TextView alertMessage = new TextView(this);
alertMessage.setText(" All changes will be lost are you sure you want to return back to the home page? ");
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Unsaved changes")
.setView(alertMessage)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getApplicationContext(), QavelNav.class);
startActivity(i);
}
})
.setNegativeButton("No", null)
.create();
dialog.show();
}
return super.onOptionsItemSelected(item);
}
public void pickDate(View v) {
DatePickerClass datepicker = new DatePickerClass();
datepicker.setText(v);
datepicker.show(getSupportFragmentManager(), "datepicker");
System.out.println(getDate());
}
public String getDate() {
String date;
date = txtDate.getText().toString();
return date;
}
public void addAttractionToItinerary(View v){
Entities.add(new ItineraryAdapter(NAME,LOCATION,null));
loadAttractions();
System.out.println(ItineraryName);
}
public void loadAttractions(){
adapter = new myAdapter(Entities);
ListView ls = (ListView) findViewById(R.id.listCreateItinerary);
ls.setAdapter(adapter);
for(int i =0; i < finalEntities.size(); i++){
System.out.println(finalEntities.get(i).NAME + " " + finalEntities.get(i).LOCATION + " " + finalEntities.get(i).TIME);
}
}
public void onSave(View v){
ContentValues values = new ContentValues();
for(int i = 0; i <finalEntities.size();i++) {
values.put(DBManager.ColItineraryName,ItineraryName);
values.put(DBManager.ColDate,txtDate.getText().toString());
values.put(DBManager.ColName,finalEntities.get(i).NAME );
values.put(DBManager.ColLocation,finalEntities.get(i).LOCATION);
values.put(DBManager.ColTime,finalEntities.get(i).TIME);
long id = db.Insert("Itinerary",values);
if (id > 0)
Toast.makeText(getApplicationContext(),"Added to Itinerary", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(),"cannot insert", Toast.LENGTH_LONG).show();
}
}
public void showTimePickerDialog(){
TextTime = (TextView) myView.findViewById(R.id.tvCreateItineraryTime);
TextTime.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
showDialog(DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id){
if(id== DIALOG_ID)
return new TimePickerDialog(CreateItinerary.this,KTimePickerListner, hour_x, min_x,false);
return null;
}
protected TimePickerDialog.OnTimeSetListener KTimePickerListner = new TimePickerDialog.OnTimeSetListener(){
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute){
hour_x = hourOfDay;
min_x = minute;
Toast.makeText(CreateItinerary.this,hour_x+" : " + min_x, Toast.LENGTH_LONG).show();
setTime(hour_x, min_x);
TIME = hour_x + ":" + min_x;
finalEntities.add(new ItineraryAdapter(NAME,LOCATION,TIME));
}
};
public void setTime(int hour, int min){
TextTime.setText(hour_x+":"+min_x);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
Toast.makeText(
getApplicationContext(),
parent.getItemAtPosition(position).toString() + " Selected" ,
Toast.LENGTH_LONG).show();
NAME = categoriesList.get(position).getName();
LOCATION = categoriesList.get(position).getLocation();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
/**
* Adding spinner data
* */
private void populateSpinner() {
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName() + " - " + categoriesList.get(i).getLocation());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
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
spinnerAttraction.setAdapter(spinnerAdapter);
spinnerTransport.setAdapter(spinnerAdapter);
}
/**
* Async task to get all food categories
* */
private class GetAttractions extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CreateItinerary.this);
pDialog.setMessage("Fetching attraction categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_ATTRACTIONS, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("attraction");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("Id"),
catObj.getString("Name"), catObj.getString("Location"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
private class GetTransport extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CreateItinerary.this);
pDialog.setMessage("Fetching transport categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_TRANSPORT, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("transport");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("Id"),
catObj.getString("Name"), catObj.getString("Location"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
class myAdapter extends BaseAdapter {
public ArrayList<ItineraryAdapter> listItem;
ItineraryAdapter ac;
public myAdapter(ArrayList<ItineraryAdapter> listItem) {
this.listItem = listItem;
}
#Override
public int getCount() {
return listItem.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
ac = listItem.get(position);
TextView Name = (TextView) myView.findViewById(R.id.tvCreateItineraryName);
Name.setText(ac.NAME);
TextView Location = (TextView) myView.findViewById(R.id.tvCreateItineraryLocation);
Location.setText(ac.LOCATION);
/*
Button buttonDelete = (Button)myView.findViewById(R.id.buttonDelete);
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Entities.remove(position);
finalEntities.remove(position);
loadAttractions();
}
});*/
return myView;
}
}
}
Thank you to anyone who can help me with this.
I'm creating an app that has an add to cart feature. I follow this tutorial and it works fine, but when i try to add the add to cart in the profile of the product instead in listview, i got an error which is IndexOutOfBoundsException Invalid index 51, size is 0
ProductDetails.java
public class ProductDetails extends Fragment {
static ConnectivityManager cm;
AlertDialog dialog2;
AlertDialog.Builder build;
TextView txtproduct,
txtprice,
txtcategorytype,
txtpieces,
txtdescription;
ImageView imgimage;
Button btncart,
btnview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.product_details, container, false);
final Controller ct = (Controller) getActivity().getApplicationContext();
cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);// checking
build = new AlertDialog.Builder(getActivity()); // connectivity
// Create default options which will be used for every
// displayImage(...) call if no options will be passed to this method
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity())
.defaultDisplayImageOptions(defaultOptions)
.build();
if (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)// if connection is
// there screen goes
// to next screen
// else shows
// message
.isConnectedOrConnecting()
|| cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
.isConnectedOrConnecting()) {
Log.e("cm value",
""
+ cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.isConnectedOrConnecting());
int teaProfileId = getArguments().getInt("teaProfileId");
String teaProfileName = getArguments().getString("teaProfileName");
Float teaProfilePrice = getArguments().getFloat("teaProfilePrice");
String teaProfileImage = getArguments().getString("teaProfileImage");
String teaProfileLabel = getArguments().getString("teaProfileLabel");
int teaProfilePieces = getArguments().getInt("teaProfilePieces");
String teaProfilePiecesType = getArguments().getString("teaProfilePiecesType");
String teaProfileDescription = getArguments().getString("teaProfileDescription");
try {
JSONObject jsonObject1 = new JSONObject(String.valueOf(teaProfileId));
JSONObject jsonObject2 = new JSONObject(teaProfileName);
JSONObject jsonObject3 = new JSONObject(Float.toString(teaProfilePrice));
JSONObject jsonObject4 = new JSONObject(teaProfileImage);
JSONObject jsonObject5 = new JSONObject(teaProfileLabel);
JSONObject jsonObject6 = new JSONObject(String.valueOf(teaProfilePieces));
JSONObject jsonObject7 = new JSONObject(teaProfilePiecesType);
JSONObject jsonObject8 = new JSONObject(teaProfileDescription);
} catch (JSONException e) {
e.printStackTrace();
}
txtproduct = (TextView) rootView.findViewById(R.id.txtproduct);
txtprice = (TextView) rootView.findViewById(R.id.txtprice);
txtcategorytype = (TextView) rootView.findViewById(R.id.txtcategorytype);
txtpieces = (TextView) rootView.findViewById(R.id.txtpieces);
txtdescription = (TextView) rootView.findViewById(R.id.txtdescription);
txtproduct.setText(teaProfileName);
txtprice.setText(("PHP ") + String.format("%.2f", teaProfilePrice));
txtcategorytype.setText(teaProfileLabel);
txtpieces.setText((teaProfilePieces)+" "+(teaProfilePiecesType));
txtdescription.setText(teaProfileDescription.replaceAll("<br />",""));
imgimage = (ImageView)rootView.findViewById(R.id.imgimage);
final ProgressBar progressBar = (ProgressBar)rootView.findViewById(R.id.progressBar);
ImageLoader.getInstance().displayImage(teaProfileImage, imgimage, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
progressBar.setVisibility(View.GONE);
}
});
}
else {
build.setMessage("This application requires Internet connection. Would you connect to internet ?");
build.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
});
build.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
getActivity().finish();
}
});
dialog2 = build.create();
dialog2.show();
}
btncart = (Button) rootView.findViewById(R.id.btncart);
btncart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int teaProfileId = getArguments().getInt("teaProfileId");
String teaProfileName = getArguments().getString("teaProfileName");
Float teaProfilePrice = getArguments().getFloat("teaProfilePrice");
String teaProfileImage = getArguments().getString("teaProfileImage");
String teaProfileLabel = getArguments().getString("teaProfileLabel");
int teaProfilePieces = getArguments().getInt("teaProfilePieces");
String teaProfilePiecesType = getArguments().getString("teaProfilePiecesType");
String teaProfileDescription = getArguments().getString("teaProfileDescription");
Toast.makeText(getActivity(), teaProfileName+" was added to cart.", Toast.LENGTH_LONG).show();
ProductModel productsObject = ct.getProducts(teaProfileId);
ct.getCart().setProducts(productsObject);
}
});
btnview = (Button) rootView.findViewById(R.id.btnview);
btnview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(getActivity(),Screen1.class);
startActivity(in);
}
});
return rootView;
}
}
Controller.java
public class Controller extends Application {
private ArrayList<ProductModel> myproducts = new ArrayList<ProductModel>();
private ModelCart myCart = new ModelCart();
public ProductModel getProducts(int id){
return myproducts.get(id);
}
public void setProducts(ProductModel products){
myproducts.add(products);
}
public ModelCart getCart(){
return myCart;
}
}
ModelCart.java
public class ModelCart {
private ArrayList<ProductModel> cartItems = new ArrayList<ProductModel>();
public ProductModel getProducts(int position){
return cartItems.get(position);
}
public void setProducts(ProductModel Products){
cartItems.add(Products);
}
public int getCartsize(){
return cartItems.size();
}
public boolean CheckProductInCart(ProductModel aproduct){
return cartItems.contains(aproduct);
}
}
This is the error in logcat.
java.lang.IndexOutOfBoundsException: Invalid index 51, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
.Controller.getProducts(Controller.java:19)
.ProductDetails$4.onClick(ProductDetails.java:192)
This is line 19: return myproducts.get(id);
This is line 192: ProductModel productsObject = ct.getProducts(teaProfileId);
I'm trying to make a reminder app and I used the phones internal storage to store the data being inputted. How do I read the file from the internal storage and place the strings in title in the listview of ReminderListActivity.java?
ReminderListActivity.java
public class ReminderListActivity extends ListActivity {
private static final int ACTIVITY_CREATE = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_reminder_list);
String[] items = new String[]{"Title"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.reminder_row, R.id.text1, items);
setListAdapter(adapter);
registerForContextMenu(getListView());
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, ReminderEditActivity.class);
i.putExtra("RowId", id);
startActivity(i);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.list_menu_item_longpress, menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.list_menu, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_insert:
createReminder();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
private void createReminder() {
Intent i = new Intent(this, ReminderEditActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_delete:
return true;
}
return super.onContextItemSelected(item);
}
public void onClickSave(View view) {
Intent f = new Intent(this, ReminderEditActivity.class);
startActivity(f);
}
}
Heres the Activity I used to save the strings into the json file in the internal storage
ReminderEditActivity.java
public class ReminderEditActivity extends Activity {
private Button mDateButton;
private Button mTimeButton;
private static final int DATE_PICKER_DIALOG = 0;
private static final int TIME_PICKER_DIALOG = 1;
private Calendar mCalendar;
private static final String DATE_FORMAT = "yyyy-MM-dd";
private static final String TIME_FORMAT = "kk:m";
private static final String FILENAME = "hello.json";
private EditText TitleEditText;
private EditText BodyEditText;
private Button EditTime;
private Button EditDate;
private ArrayList<Data> data =
new ArrayList<Data>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_reminder_edit);
mCalendar = Calendar.getInstance();
mDateButton = (Button) findViewById(R.id.reminder_date);
mTimeButton = (Button) findViewById(R.id.reminder_time);
TitleEditText = (EditText) findViewById(R.id.title);
BodyEditText = (EditText) findViewById(R.id.body);
EditTime = (Button) findViewById(R.id.reminder_time);
EditDate = (Button) findViewById(R.id.reminder_date);
if (getIntent() != null) {
Bundle extras = getIntent().getExtras();
int rowId = extras != null ? extras.getInt("RowId") : -1;
registerButtonListenersAndSetDefaultText();
}
readData();
}
public void readData() {
try {
FileInputStream fis = openFileInput(FILENAME);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
JsonReader jsonReader = new JsonReader(isr);
String title = "";
String body = "";
String time = "";
String date = "";
jsonReader.beginArray(); // [
while (jsonReader.hasNext()) {
jsonReader.beginObject(); // {
while (jsonReader.hasNext()) {
String key = jsonReader.nextName();
if (key.equals("Title")) {
title = jsonReader.nextString();
} else if (key.equals("Body")) {
body = jsonReader.nextString();
} else if (key.equals("Date")) {
date = jsonReader.nextString();
} else if (key.equals("Time")) {
time = jsonReader.nextString();
}
}
jsonReader.endObject(); // }
Data content = new Data(
title, body, date, time
);
data.add(content);
}
jsonReader.endArray();
jsonReader.close();
} catch (IOException ex) {
Toast.makeText(this, "cannot read file", Toast.LENGTH_SHORT).show();
}
}
public void addFile(View view) {
String title = TitleEditText.getText().toString();
String body = BodyEditText.getText().toString();
String time = EditTime.getText().toString();
String date = EditDate.getText().toString();
Toast.makeText(this, "File written", Toast.LENGTH_SHORT).show();
Data content = new Data(
title, body, date, time
);
data.add(content);
writeAllData();
}
public void writeAllData() {
try {
FileOutputStream fos = openFileOutput(FILENAME,
Context.MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
JsonWriter jsonWriter = new JsonWriter(osw);
jsonWriter.setIndent(" ");
jsonWriter.beginArray();
for (int i = 0; i < data.size(); i++) {
Data con = data.get(i);
jsonWriter.beginObject();
jsonWriter.name("Title").value(con.GetTitle());
jsonWriter.name("Body").value(con.GetBody());
jsonWriter.name("Date").value(con.GetDate());
jsonWriter.name("Time").value(con.GetTime());
jsonWriter.endObject();
}
jsonWriter.endArray();
jsonWriter.close();
} catch (IOException ex) {
Toast.makeText(this, "Cant write file", Toast.LENGTH_LONG).show();
}
}
private void registerButtonListenersAndSetDefaultText() {
mTimeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(TIME_PICKER_DIALOG);
}
});
mDateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATE_PICKER_DIALOG);
}
});
updateDateButtonText();
updateTimeButtonText();
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_PICKER_DIALOG:
return showDatePicker();
case TIME_PICKER_DIALOG:
return showTimePicker();
}
return super.onCreateDialog(id);
}
private DatePickerDialog showDatePicker() {
DatePickerDialog datePicker = new DatePickerDialog(ReminderEditActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, monthOfYear);
mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDateButtonText();
}
}, mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH));
return datePicker;
}
private TimePickerDialog showTimePicker() {
TimePickerDialog timePicker = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
mCalendar.set(Calendar.MINUTE, minute);
updateTimeButtonText();
}
}, mCalendar.get(Calendar.HOUR_OF_DAY), mCalendar.get(Calendar.MINUTE), true);
return timePicker;
}
private void updateDateButtonText() {
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
String dateForButton = dateFormat.format(mCalendar.getTime());
mDateButton.setText(dateForButton);
}
private void updateTimeButtonText() {
SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT);
String timeForButton = timeFormat.format(mCalendar.getTime());
mTimeButton.setText(timeForButton);
}
}
I tried to add textwatcher with filter class but it do not work plz help. I get the json array through the server using the url. the search(filter) doesnt work well.
public class CallDetails extends Activity {
SessionManager session;
ArrayList<Drivers> driverList = new ArrayList<Drivers>();
private List<Drivers> driverlist = null;
ListView listview;
ImageButton btback;
DriverAdapter dadapter;
String uid;
String name;
String email;
String odtyp;
static String oid;
Drivers driver;
private EditText editTextFilter;
private static String OUTBOX_URL ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calldetails);
Intent i = getIntent();
oid =i.getStringExtra("orderId");
odtyp =i.getStringExtra("ordertype");
OUTBOX_URL ="http://www.gdrive.com/api/calldetails.php?id="+oid;
//managing session...
session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
name = user.get(SessionManager.KEY_NAME);
email = user.get(SessionManager.KEY_EMAIL);
uid = user.get(SessionManager.KEY_UID);
btback =(ImageButton)findViewById(R.id.btnBack);
btback.setVisibility(View.INVISIBLE);
// Locate the EditText in listview_main.xml
editTextFilter = (EditText)findViewById(R.id.editTextFilter);
editTextFilter.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
String text = editTextFilter.getText().toString().toLowerCase(Locale.getDefault());
dadapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3){ /* to do*/ }
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) { /*to do*/ }
});
//populating view with data...
//driverList = new ArrayList<Drivers>();
new JSONAsyncTask().execute(OUTBOX_URL);
listview = (ListView)findViewById(R.id.drlist);
dadapter = new DriverAdapter(CallDetails.this, R.layout.list_item, driverList);
listview.setItemsCanFocus(false);
listview.setAdapter(dadapter);
//populating list ends
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), driverList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
}
public void back(View v){
Intent back = new Intent(getApplicationContext(), SafetyDrive.class);
startActivity(back);
finish();
}
private class DriverAdapter extends ArrayAdapter<Drivers> {
Context context;
int Resource;
LayoutInflater inflater;
ArrayList<Drivers> driverList = new ArrayList<Drivers>();
public DriverAdapter(Context context, int layoutResourceId,ArrayList<Drivers> drs) {
super(context, layoutResourceId, drs);
//inflater = ((Activity) context).getLayoutInflater();
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = layoutResourceId;
driverList = drs;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//Log.d("in ", "view start");
View item = convertView;
DriverWrapper DriverWrapper = null;
if (item == null) {
DriverWrapper = new DriverWrapper();
item = inflater.inflate(Resource, null);
DriverWrapper.ename = (TextView) item.findViewById(R.id.textName);
DriverWrapper.ephone = (TextView) item.findViewById(R.id.textPhone);
DriverWrapper.mkcall = (ImageButton) item.findViewById(R.id.btnphone);
item.setTag(DriverWrapper);
} else {
DriverWrapper = (DriverWrapper) item.getTag();
}
Drivers driver = driverList.get(position);
DriverWrapper.ename.setText("Name: " + driver.getName());
DriverWrapper.ephone.setText("Phone: " + driver.getPhone());
final String dp = driver.getPhone().trim();
DriverWrapper.mkcall.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//making call..
//Log.e("no is", dp);
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" +dp));
//callIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(callIntent);
//finish();
}
});
return item;
}
class DriverWrapper {
TextView ename;
TextView ephone;
ImageButton mkcall;
//ImageButton msg;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
driverList.clear();
if (charText.length() == 0) {
driverList.addAll(driverList);
} else {
for (Drivers driver : driverList) {
if (driver.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
driverList.add(driver);
}
}
}
notifyDataSetChanged();
}
}
class JSONAsyncTask extends AsyncTask {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(CallDetails.this);
dialog.setMessage("Loading, please wait");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//Log.d("in at-", "asynctask");
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("drivers");
if(jarray.length()!=0){
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Drivers driver = new Drivers();
driver.setPhone(object.getString("phone"));
driver.setName(object.getString("emp_name"));
driverList.add(driver);
}
}else{
driver = new Drivers();
driver.setPhone(" ");
driver.setName(" No Driver Place yet");
driverList.add(driver);
}
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
btback.setVisibility(View.VISIBLE);
dadapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
public class Drivers {
private String name;
private String phone;
public Drivers() {
}
public Drivers(String name, String phone) {
super();
this.name = name;
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
actually it wont filter because youve cleared the driverList and then in the else statement you loop to driverList which is already empty. the only thing you can do is create a backup list for the driversList and then use the backup list to get all data for filtering to the driverList.
Example Here:
// here is the backuplist
ArrayList<Drivers> backupList = new ArrayList<Drivers>();
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
// actually its easy to just clear the backup list
// but due to reasons where users press backspace you have to load backup list only once
if(backupList.isEmpty()) {
backupList.addAll(driverList);
}
driverList.clear();
if (charText.length() == 0) {
driverList.addAll(backupList);
} else {
for (Drivers driver : backupList) {
if (driver.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
driverList.add(driver);
}
}
}
notifyDataSetChanged();
}
Hope it helps :)