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.
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 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 need help to find out why it wont go to the next activity (case R.id.Signin_Btn), I've got this issue in another Activity which was perfectly working before this class was made.
I've been through and checked everything and cant find a way to resolve this issue.
public class Login extends ActionBarActivity implements View.OnClickListener {
ArrayList<Driver> DriverArrayList;
DriverAdapter Dadapter;
ArrayList<Vehicle> VehicleArrayList;
VehicleAdapter Vadapter;
ArrayList<Plot> PlotArrayList;
PlotAdapter Padapter;
ImageButton Driver_Btn;
ImageButton Vehicle_Btn;
ImageButton Plot_Btn;
Button Signin_Btn;
private Intent myIntent;
private int DriverID = 0;
private int VehicleID = 0;
private int PlotID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Driver_Btn = (ImageButton) findViewById(R.id.Select_Driver);
Driver_Btn.setOnClickListener(this);
Vehicle_Btn = (ImageButton) findViewById(R.id.Select_Vehicle);
Vehicle_Btn.setOnClickListener(this);
Plot_Btn = (ImageButton) findViewById(R.id.Select_Plot);
Plot_Btn.setOnClickListener(this);
Signin_Btn = (Button) findViewById(R.id.Signin_Btn);
Signin_Btn.setOnClickListener(this);
//ArrayList
DriverArrayList = new ArrayList<Driver>();
VehicleArrayList = new ArrayList<Vehicle>();
PlotArrayList = new ArrayList<Plot>();
new JSONAsyncTask().execute("N/A");
ListView DlistView = (ListView) findViewById(R.id.DriverList);
ListView VlistView = (ListView) findViewById(R.id.VehicleList);
ListView PlistView = (ListView) findViewById(R.id.PlotList);
Dadapter = new DriverAdapter(getApplicationContext(), R.layout.driver_row, DriverArrayList);
Vadapter = new VehicleAdapter(getApplicationContext(), R.layout.vehicle_row, VehicleArrayList);
Padapter = new PlotAdapter(getApplicationContext(), R.layout.plot_row, PlotArrayList);
DlistView.setAdapter(Dadapter);
VlistView.setAdapter(Vadapter);
PlistView.setAdapter(Padapter);
Driver_Btn.setBackgroundColor(Color.GREEN);
DlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
ListView VehicleListView = (ListView) findViewById(R.id.VehicleList);
DriverID = DriverArrayList.get(position).getID();
ResetButtonColours();
arg1.setSelected(true);
Vehicle_Btn.setBackgroundColor(Color.GREEN);
VehicleListView.setVisibility(View.VISIBLE);
//Toast.makeText(getApplicationContext(), DriverArrayList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
VlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
VehicleID = VehicleArrayList.get(position).getID();
ListView PlotListView = (ListView) findViewById(R.id.PlotList);
ResetButtonColours();
Plot_Btn.setBackgroundColor(Color.GREEN);
PlotListView.setVisibility(View.VISIBLE);
//Toast.makeText(getApplicationContext(), DriverArrayList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
PlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
PlotID = PlotArrayList.get(position).getID();
}
});
}
private void ResetButtonColours() {
ListView DriverListView = (ListView) findViewById(R.id.DriverList);
ListView VehicleListView = (ListView) findViewById(R.id.VehicleList);
ListView PlotListView = (ListView) findViewById(R.id.PlotList);
DriverListView.setVisibility(View.GONE);
VehicleListView.setVisibility(View.GONE);
PlotListView.setVisibility(View.GONE);
Driver_Btn.setBackgroundColor(Color.TRANSPARENT);
Vehicle_Btn.setBackgroundColor(Color.TRANSPARENT);
Plot_Btn.setBackgroundColor(Color.TRANSPARENT);
}
#Override
public void onClick(View v) {
ListView DriverListView = (ListView) findViewById(R.id.DriverList);
ListView VehicleListView = (ListView) findViewById(R.id.VehicleList);
ListView PlotListView = (ListView) findViewById(R.id.PlotList);
switch (v.getId()) {
case R.id.Select_Driver:
this.ResetButtonColours();
Driver_Btn.setBackgroundColor(Color.GREEN);
DriverListView.setVisibility(View.VISIBLE);
break;
case R.id.Select_Vehicle:
this.ResetButtonColours();
Vehicle_Btn.setBackgroundColor(Color.GREEN);
VehicleListView.setVisibility(View.VISIBLE);
break;
case R.id.Select_Plot:
this.ResetButtonColours();
Plot_Btn.setBackgroundColor(Color.GREEN);
PlotListView.setVisibility(View.VISIBLE);
break;
case R.id.Signin_Btn:
if (DriverID == 0) {
Toast.makeText(getApplicationContext(), "You haven't selected a Driver!", Toast.LENGTH_LONG).show();
} else if (VehicleID == 0) {
Toast.makeText(getApplicationContext(), "You haven't selected a Vehicle!", Toast.LENGTH_LONG).show();
} else if (PlotID == 0) {
Toast.makeText(getApplicationContext(), "You haven't selected a Plot!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Just a minute!", Toast.LENGTH_LONG).show();
myIntent = new Intent(this, Dashboard.class);
//myIntent.putExtra("key", value); //Optional parameters
startActivity(myIntent);
}
break;
}
}
public class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(Login.this);
dialog.setMessage("Loading, Please Wait");
dialog.setTitle("Connecting to Server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet HttpPost = new HttpGet(urls[0]);
HttpClient HttpClient = new DefaultHttpClient();
HttpResponse Response = HttpClient.execute(HttpPost);
int Status = Response.getStatusLine().getStatusCode();
//if (Status == 200) {
HttpEntity Entity = Response.getEntity();
String Data = EntityUtils.toString(Entity);
JSONObject Object = new JSONObject(Data);
JSONArray DriverArray = Object.getJSONArray("drivers");
for (int i = 0; i < DriverArray.length(); i++) {
JSONObject Current = DriverArray.getJSONObject(i);
Driver Driver = new Driver();
Driver.setID(Current.getInt("id"));
Driver.setName(Current.getString("name"));
DriverArrayList.add(Driver);
}
JSONArray VehicleArray = Object.getJSONArray("vehicles");
for (int i = 0; i < VehicleArray.length(); i++) {
JSONObject Current = VehicleArray.getJSONObject(i);
Vehicle Vehicle = new Vehicle();
Vehicle.setID(Current.getInt("id"));
Vehicle.setName(Current.getString("make") + ' ' + Current.getString("model"));
Vehicle.setReg("(" + Current.getString("reg") + ")");
VehicleArrayList.add(Vehicle);
}
JSONArray PlotArray = Object.getJSONArray("plots");
for (int i = 0; i < PlotArray.length(); i++) {
JSONObject Current = PlotArray.getJSONObject(i);
Plot Plot = new Plot();
Plot.setID(Current.getInt("id"));
Plot.setName(Current.getString("name"));
PlotArrayList.add(Plot);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
Dadapter.notifyDataSetChanged();
if (result == false) {
Toast.makeText(getApplicationContext(), "Unable to Fetch Content from Server", Toast.LENGTH_LONG).show();
}
}
}
}
Have you added the new Activity to the manifest file?
Add this
<activity
android:name=".Dashboard"
android:label="Dashboard" />
I want to implement Load-More feature in my ListView.
Here is my code:
public class MainActivity extends Activity {
int url_page = 0;
private static String URL = "http://MyURL&page_no=";
ArrayList<ItemInfo> products = new ArrayList<ItemInfo>();
BoxAdapter boxAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTaskParseJson().execute();
}
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
JsonParser jParser = new JsonParser();
JSONObject json = jParser.getJSONFromUrl(URL+"0");
dataJsonArr = json.getJSONArray("data");
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
String nickname = c.getString("nickname");
String description = c.getString("description");
products.add(new ItemInfo(nickname, description));
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg)
{
SetAdapter();
}
}
public void SetAdapter()
{
boxAdapter = new BoxAdapter(this, products);
ListView lvMain = (ListView) findViewById(R.id.list);
lvMain.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
ListView lvMain = (ListView) findViewById(R.id.list);
int pos = lvMain.getPositionForView(view);
ItemInfo p = boxAdapter.getItem(pos);
//
String username = p.username;
String description = p.description;
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
OnClickActivity.class);
in.putExtra("username", username);
in.putExtra("description", description);
startActivity(in);
}
});
lvMain.setAdapter(boxAdapter);
lvMain.setOnScrollListener(new OnScrollListener()
{
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
ListView lvMain = (ListView) findViewById(R.id.list);
if(firstVisibleItem + visibleItemCount >= totalItemCount) {
boxAdapter.loadAdditionalItems();
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I added this to onScroll event:
if (lvMain.getLastVisiblePosition() >= lvMain.getCount())
{
url_page = url_page + 1;
new LoadLastestPost().execute();
}
And asyntask:
public class LoadLastestPost extends AsyncTask<String, String, String> {
final String TAG = "LoadLastestPost.java";
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
JsonParser jParser = new JsonParser();
String newURL = URL + String.valueOf(url_page);
JSONObject json = jParser.getJSONFromUrl(newURL);
dataJsonArr = json.getJSONArray("data");
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
String nickname = c.getString("nickname");
String description = c.getString("description");
products.add(new ItemInfo(nickname, description));
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg)
{
LoadMoreItem();
}
}
private void LoadMoreItem()
{
ListView lvMain = (ListView) findViewById(R.id.list);
boxAdapter = null;
boxAdapter = new BoxAdapter(this, products);
lvMain.setAdapter(boxAdapter);
boxAdapter.notifyDataSetChanged();
}
But it is not working ;( That needs fixing?
P.S i display 10 item, and load more 10 response of an already loaded.
I want load items in the end of listview.