I populated a GridView with a Custom Adapter of images. I added a button to sort the images. I'm trying to figure out how to do this properly. As of right now, I'm trying to delete all the images by using the clear() method and repopulating it with the sorted images. However, I can't seem to delete the images. It just adds to the sorted images to the original. Please help
public class MainActivity extends AppCompatActivity {
private ImageView mImageView;
private TextView mTextView;
String githubSearchResults;
String default_sort = "http://api.themoviedb.org/3/movie/top_rated?api_key=(MY OWN API KEY)";
ArrayList<String> listdata = new ArrayList<String>();
List<String> posterData = new ArrayList<String>();
JSONObject results;
private MovieAdapter movieAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView) findViewById(R.id.movie_image);
getURL(default_sort);
}
JSONArray getResults(String JSONString) throws JSONException {
JSONObject movieResults = new JSONObject(JSONString);
JSONArray jArray = (JSONArray)movieResults.getJSONArray("results");
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.getString(i));
}
}
return jArray;
}
void getPosterPath() throws JSONException {
for(int i = 0;i<listdata.size();i++) {
results = new JSONObject(listdata.get(i));
String poster_path = results.getString("poster_path");
posterData.add(poster_path);
Log.d("myTag", poster_path);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.sort_popular, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.popular:
movieAdapter.clear();
movieAdapter.notifyDataSetChanged();
String sort_popular = "http://api.themoviedb.org/3/movie/popular?api_key=(MY OWN API KEY)";
getURL(sort_popular);
return true;
default:
super.onOptionsItemSelected(item);
}
return true;
}
private void getURL(String string){
URL getURL = NetworkUtils.buildUrl(string);
new GithubQueryTask().execute(getURL);
}
public class GithubQueryTask extends AsyncTask<URL, Void, String> {
// COMPLETED (2) Override the doInBackground method to perform the query. Return the results. (Hint: You've already written the code to perform the query)
#Override
protected String doInBackground(URL... params) {
URL searchUrl = params[0];
String githubSearchResults = null;
try {
githubSearchResults = NetworkUtils.getResponseFromHttpUrl(searchUrl);
getResults(githubSearchResults);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return githubSearchResults;
}
// COMPLETED (3) Override onPostExecute to display the results in the TextView
#Override
protected void onPostExecute(String githubSearchResults) {
try {
getPosterPath();
} catch (JSONException e) {
e.printStackTrace();
}
movieAdapter = new MovieAdapter(MainActivity.this, posterData);
GridView listView = (GridView) findViewById(R.id.listview_flavor);
listView.setAdapter(movieAdapter);
}
}
}
Here's my custom adapter:
public class MovieAdapter extends ArrayAdapter<String> {
private ImageView mImageView;
public MovieAdapter(Activity context, List<String> movieArray) {
super(context, 0, movieArray);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String androidFlavor = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_detail, parent, false);
}
mImageView= (ImageView) convertView.findViewById(R.id.movie_image);
Picasso.with(getContext()).load("http://image.tmdb.org/t/p/w185/"+androidFlavor).into(mImageView);
return convertView;
}
}
If I'm not mistaking, the problem is you never clear posterData list (what about listdata as well). You just keep adding to it. I would suggest to change the getPosterPath method like this:
void getPosterPath() throws JSONException {
posterData.Clear();
for(int i = 0;i<listdata.size();i++) {
results = new JSONObject(listdata.get(i));
String poster_path = results.getString("poster_path");
posterData.add(poster_path);
Log.d("myTag", poster_path);
}
movieAdapter.notifyDataSetChanged();
}
And in public boolean onOptionsItemSelected you don't need to call
movieAdapter.clear();
movieAdapter.notifyDataSetChanged();
since any change in the list the adapter is bound to should reflect in the adapter after getPosterPath() gets executed.
EDIT:
The reason you get this error is because
movieAdapter = new MovieAdapter(MainActivity.this, posterData);
happens after the call to getPosterPath().
Just alter the onPostExectute() a bit:
protected void onPostExecute(String githubSearchResults) {
movieAdapter = new MovieAdapter(MainActivity.this, posterData);
try {
getPosterPath();
} catch (JSONException e) {
e.printStackTrace();
}
GridView listView = (GridView) findViewById(R.id.listview_flavor);
listView.setAdapter(movieAdapter);
}
Related
The app doesn't show anything in the recycler view the first time I open it, but it shows the items after I press the home button and then press the overview button and open the app from there
here is the code in mainActivity
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mlayoutManager;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<String> countryNmaeList =new ArrayList<>();
final ArrayList<countryItem> countryList = new ArrayList<>();
final ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("Loading data");
mRecyclerView = findViewById(R.id.recyclerView);
mAdapter=new countryAdapter(countryList);
mlayoutManager=new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mlayoutManager);
dialog.show();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://covid-193.p.rapidapi.com/statistics")
.get()
.addHeader("x-rapidapi-host", "covid-193.p.rapidapi.com")
.addHeader("x-rapidapi-key", "xxxxxxxxxxxxx")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
dialog.dismiss();
String response1=response.body().string();
try {
//geting Jason object
JSONObject jsonObject=new JSONObject(response1);
JSONArray jsonArray = jsonObject.getJSONArray("response");
for (int i=0;i<jsonArray.length();i++){
JSONObject country = jsonArray.getJSONObject(i);
JSONObject cases = country.getJSONObject("cases");
int activecaseint = cases.getInt("active");
int recoveredint =cases.getInt("recovered");
JSONObject death= country.getJSONObject("deaths");
int dtotal = death.getInt("total");
//adding items into country items
countryList.add(new countryItem(country.getString("country"),String.valueOf(activecaseint),String.valueOf(recoveredint),String.valueOf(dtotal)));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
//nottifying the dataset changed
mAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter);
}
}
here is my adapter activity
countryAdapter.java
public class countryAdapter extends RecyclerView.Adapter<countryAdapter.countryViewHolder> {
private ArrayList<countryItem> mCountryList;
public static class countryViewHolder extends RecyclerView.ViewHolder{
public TextView mCountryName;
public TextView mActivePatients;
public TextView mRecovered;
public TextView mDeath;
public countryViewHolder(#NonNull View itemView) {
super(itemView);
mCountryName=itemView.findViewById(R.id.CountyNameTv);
mActivePatients=itemView.findViewById(R.id.activePatientsTv);
mRecovered=itemView.findViewById(R.id.recoveredTv);
mDeath=itemView.findViewById(R.id.deathTv);
}
}
public countryAdapter(ArrayList<countryItem> countryList){
mCountryList = countryList;
}
#NonNull
#Override
public countryViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.itemview,parent,false);
countryViewHolder cvh =new countryViewHolder(v);
return cvh;
}
#Override
public void onBindViewHolder(#NonNull countryViewHolder holder, int position) {
countryItem currentItem=mCountryList.get(position);
holder.mCountryName.setText(currentItem.getCountryname());
holder.mActivePatients.setText(currentItem.getActivePatients());
holder.mRecovered.setText(currentItem.getRecovered());
holder.mDeath.setText(currentItem.getDeath());
}
#Override
public int getItemCount() {
return mCountryList.size();
}
public void swapData(ArrayList<countryItem> list) {
if (list != null) {
this.mCountryList.clear();
this.mCountryList.addAll(list);
notifyDataSetChanged();
}
}
}
i have tried putting notifyDataSetChanged inside the try but that didn't work. i hope you can find a way to fix this.
When you have new datalist update after adding it in list as:
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
dialog.dismiss();
String response1=response.body().string();
try {
//geting Jason object
JSONObject jsonObject=new JSONObject(response1);
JSONArray jsonArray = jsonObject.getJSONArray("response");
for (int i=0;i<jsonArray.length();i++){
JSONObject country = jsonArray.getJSONObject(i);
JSONObject cases = country.getJSONObject("cases");
int activecaseint = cases.getInt("active");
int recoveredint =cases.getInt("recovered");
JSONObject death= country.getJSONObject("deaths");
int dtotal = death.getInt("total");
//adding items into country items
countryList.add(new countryItem(country.getString("country"),String.valueOf(activecaseint),String.valueOf(recoveredint),String.valueOf(dtotal)));
}
//adapter.swapData(countryList);
updateData(countryList);
} catch (JSONException e) {
e.printStackTrace();
}
}
you can comment out following line:
mAdapter.notifyDataSetChanged();
Add this function in your adapter class and call it when you need to update list:
public void swapData(ArrayList<countryItem> list) {
if (list != null) {
this.arrayList.clear();
this.arrayList.addAll(list);
notifyDataSetChanged();
}
}
In your global object declaration change type of adapter to:
private countryAdapter mAdapter;
add this method in mainActivity and call when you want to update data:
public void updateData(ArrayList<countryItem> countryList) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
mAdapter.swapData(countryList);
}
});
}
Instead of calling mAdapter.notifyDataSetChanged() at the end of onCreate() you should call it in onRespone() when the new data got set.
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
dialog.dismiss();
String response1=response.body().string();
try {
//geting Jason object
JSONObject jsonObject=new JSONObject(response1);
JSONArray jsonArray = jsonObject.getJSONArray("response");
for (int i=0;i<jsonArray.length();i++){
JSONObject country = jsonArray.getJSONObject(i);
JSONObject cases = country.getJSONObject("cases");
int activecaseint = cases.getInt("active");
int recoveredint =cases.getInt("recovered");
JSONObject death= country.getJSONObject("deaths");
int dtotal = death.getInt("total");
//adding items into country items
countryList.add(new countryItem(country.getString("country"),String.valueOf(activecaseint),String.valueOf(recoveredint),String.valueOf(dtotal)));
}
mAdapter.notifyDataSetChanged(); // ← notify adapter here!
} catch (JSONException e) {
e.printStackTrace();
}
}
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'm new in Android programming and I want to create a custom Filter in my Baseadapter.
Honestly it's kinda confusing when I check the other questions because they mostly use Arraylists. I already created a custom View (getView) that sets small pictogramms into my ListView. I already tried many ways to implement these custom Filter from Arraylist examples, but somehow I get into a blockade.
It would be very helpful if someone could atleast give me some direction for a Custom Filter with Objects
cryptoListAdapter.java
public class cryptoListAdapter extends BaseAdapter {
private Context context;
LayoutInflater mInlfater;
ArrayList<HashMap<String,String>> currencyList;
TextView name;
// Constructor
public cryptoListAdapter(Context context,ArrayList<HashMap<String,String>> currencyList)
{
mInlfater = LayoutInflater.from(context);
this.currencyList = currencyList;
}
#Override
public int getCount() {
return currencyList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
cryptoPicto cp = new cryptoPicto();
View newView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_crypto_items, null);
name = (TextView) newView.findViewById(R.id.name);
TextView symbol = (TextView) newView.findViewById(R.id.symbol);
ImageView image_list_icon = (ImageView)newView.findViewById(cryptopicto);
//cp.createFinalFileName(name);
HashMap<String, String> map;
map = currencyList.get(position);
name.setText(map.get("name"));
symbol.setText(map.get("symbol"));
Picasso.with(newView.getContext()).load(map.get("cryptopicto")).into(image_list_icon);
return newView;
}
currencyTableView.java
public class currencyTableView extends AppCompatActivity {
private String TAG = currencyTableView.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
private SearchView sv;
private ImageView im;
private static String url = "https//myURLToJSON";
Context context;
cryptoListAdapter adapter;
ArrayList<HashMap<String, String>> currencyList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_currency_table_view);
sv = (SearchView) findViewById(R.id.search_currency);
currencyList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
im = (ImageView) findViewById(R.id.cryptopicto);
new GetCurrencies().execute();
}
// URL to get currencies JSON
private class GetCurrencies extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(currencyTableView.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
databasehandler sh = new databasehandler();
cryptoPicto cp = new cryptoPicto();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jsonArray = new JSONArray(jsonStr);
// looping through currencies
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String name = c.getString("name");
String symbol = c.getString("symbol");
Double price_usd = c.getDouble("price_usd");
Double price_eur = c.getDouble("price_eur");
Double price_btc = c.getDouble("price_btc");
Double volume_eur = c.getDouble("volume_eur");
Double market_cap_usd = c.getDouble("market_cap_usd");
Double percent_change_1h = c.getDouble("percent_change_1h");
Double percent_change_24h = c.getDouble("percent_change_24h");
Double percent_change_7d = c.getDouble("percent_change_7d");
// tmp hash map for single currency
HashMap<String, String> currency = new HashMap<>();
// create Path to picto Filename
cp.createFinalFileName(name);
// adding each child node to HashMap key => value
currency.put("cryptopicto", cp.getFinalFileName());
currency.put("name", name);
currency.put("symbol", symbol);
// adding currency to currencyList
currencyList.add(currency);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
adapter = new cryptoListAdapter(
currencyTableView.this, currencyList) {
};
lv.setAdapter(adapter);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String currencyList) {
adapter.getFilter().filter(currencyList);
return false;
}
});
}
}
}
Thanks in Advance :)
Make your BaseAdapder implements Filterable
then add
List<HashMap<String,String>> mOriginalValues;
after
ArrayList<HashMap<String,String>> currencyList;
in your adapter class
and then add this method at the bottom before the closing braces "}"
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
currencyList = (ArrayList<HashMap<String,String>>) results.values;
notifyDataSetChanged();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<HashMap<String, String>> FilteredArrList = new ArrayList<HashMap<String, String>>();
if (mOriginalValues == null) {
mOriginalValues = new ArrayList<HashMap<String, String>>(currencyList); // saves
}
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = mOriginalValues.size();
results.values = mOriginalValues;
} else {
Locale locale = Locale.getDefault();
constraint = constraint.toString().toLowerCase(locale);
for (int i = 0; i < mOriginalValues.size(); i++) {
HashMap<String, String> currency = mOriginalValues.get(i);
String data = currency.get("name");
if (data.toLowerCase(locale).startsWith(constraint.toString())) {
FilteredArrList.add(currency);
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
Let me know if that helps
I have problem to set data into listview. Problem occurs after set message, message is set first after come 8th message from thread.
**below is my whole code :****(Here is my "Activity and adapter")**
public class Inboxreadmsg extends ActionBarActivity {
// <strong>Here is my global variable</strong>
ListView lv;
Handler h;
Custom_Inbox_Adapter ccAdpt;
Custom_Inbox_Adapter inadapter;
Runnable checker;
List<Dataset> dataset;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.messagesublistlayout);
// map id from layout</strong>
lv =(ListView)findViewById(R.id.readmessagelist);
/*****************************call thread of webservice with database****************************/
runThread();
startHandler();
/*****************************call thread of webservice with database****************************/
}
public void runThread()
{
h=new Handler();
checker=new Runnable()
{
#Override
public void run() {
// call webservice for fetch data
forthread();
h.postDelayed(checker,15000);
}
};
}
public void forthread()
{
// call webservice to fetch data
new InboxReadChat(null, InboxReadChat.TotalMessagesOfSingleSenderUser.geturl( recipientid,InAppUserid), InboxReadChat.TYPE_GET, InboxReadChat.TYPE_RECEIVE_MESSAGE_INBOX, new ServiceHitListenerInboxChat() {
#Override
public void onSuccess(Object Result, int id)
{
// After success of webservice response come this function
callFxnInSuccess(Result);
}
#Override
public void onError(String Error, int id)
{
// AfterError of webservice response come this function
// By this fxn set data from local database to listview
DBvaluesSet();
}
});
}
private void callFxnInSuccess(Object Result) {
dataset = new ArrayList<Dataset>();
String message="",alldatetime="",time="",date="",type="";
InboxDeliveredModel ibx=(InboxDeliveredModel) Result;
if(ibx.getTotalMessagesOfSingleSenderUser().size()>0)
{
// here webservice response data will add on local database
dbObject.Open();
for(int i=0;i<ibx.getTotalMessagesOfSingleSenderUser().size();i++)
{
message =ibx.getTotalMessagesOfSingleSenderUser().get(i).getMessage();
.....
dbObject.InboxMessageAll(message,InAppUsermobile,time,recipientid,type,date);
}
dbObject.close();
// After add data into database call below fxn to fetch data from database and set data in listview with adapter
try
{
DBvaluesSet();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public void DBvaluesSet() {
dataset = new ArrayList<Dataset>();
try
{
// By this code fetch data from local database
Cursor c;
dbObject.Open();
c=dbObject.getallmessages(recipientid);
int countRow = c.getCount();
int counter = 0;
while(c.moveToNext())
{
msgboxitem = c.getString(0);
// number = c.getString(1);
timeitem = c.getString(2);
typeitem = c.getString(4);
datedbitem = c.getString(5);
try {
dataset.add(db.new Dataset(datedbitem, msgboxitem, timeitem, typeitem));
} catch (Exception e) {
e.printStackTrace();
}
}
dbObject.close();
// by below set data into listview into adapter
lv.setAdapter(ccAdpt=new Custom_Inbox_Adapter( getApplicationContext(),dataset,R.layout.row));
ccAdpt.notifyDataSetChanged();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Here my adapter coding...
public class Custom_Inbox_Adapter extends BaseAdapter{
private Context gContext;
private List<Dataset> gData;
private int rEsource;
public Custom_Inbox_Adapter(Context cnt, List<Dataset> data ,int resource){
this.gData = data;
this.gContext = cnt;
this.rEsource = resource;
}
#Override
public int getCount() {
return gData.size();
}
#Override
public Dataset getItem(int position) {
return gData.get(position);
}
#Override
public long getItemId(int position) {> return gData.get(position).hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) gContext.getSystemService(gContext.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(rEsource, null);
TextView txtReceiveMsg = (TextView) convertView.findViewById(R.id.ReceiveMsg);
TextView txtReceiveTime = (TextView) convertView.findViewById(R.id.ReceiveTime);
TextView txtSendMsg = (TextView) convertView.findViewById(R.id.sendMsg);
TextView txtSendTime = (TextView) convertView.findViewById(R.id.senttime);
TextView date = (TextView) convertView.findViewById(R.id.date);
// layout text chat
RelativeLayout relSend = (RelativeLayout) convertView.findViewById(R.id.LinearReceive);
RelativeLayout relreceive = (RelativeLayout) convertView.findViewById(R.id.LinearSend);
// layout date chat
RelativeLayout LinearDATE= (RelativeLayout) convertView.findViewById(R.id.LinearDATE);
if(position == 0){
fetchdata= gData.get(position).getDate().trim();
date.setText(fetchdata);
}
else{
fetchdata = gData.get(position).getDate().trim();
dd = gData.get((position-1)).getDate().trim();
if(fetchdata.equalsIgnoreCase(dd))
{
LinearDATE.setVisibility(View.GONE);
}
else
{
LinearDATE.setVisibility(View.VISIBLE);
Log.w("INBOX READ", "INBOX_READ_ADAPTER::::(date for position '1'):"+fetchdata);
date.setText(fetchdata);
}
}
relreceive.setVisibility(View.GONE);
relSend.setVisibility(View.VISIBLE);
//txtReceiveNumber.setText(number);
txtReceiveMsg.setText(cutmsg);
txtReceiveTime.setText(time);
}
return convertView;
}
}
What I am doing::
I have three buttons
When I click any one of the button, it must clear adapter & Assign
the newvalues.
The newvalues must reflect in the listview
Problem::
My listview is not reflecting the changes onclick of Button
No log Errors
DisplayBuffet_NotifyDataSetChanged_Fragment.java
public class DisplayBuffet_NotifyDataSetChanged_Fragment extends Fragment implements View.OnClickListener{
// Declaration
static ListView xmlFragmentListView;
static View layout;
static DisplayBuffetAsyncTask downloadTask=null;
Button btnRating,btnPrice,btnDistance;
private FileCache fileCache=null;
private MemoryCache memoryCache=null;
DisplayBuffetAdapter listViewAdapter;
static Bundle bundle=null;
DisplayBuffet_Json_Fragment fragment=null;
ArrayList<HashMap<String, String>> arrayListBuffet=null;
FindMyBuffetDatabaseHelper mHelper=null;;
SQLiteDatabase database=null;
public static DisplayBuffet_NotifyDataSetChanged_Fragment newInstance(FileCache _fileCache,MemoryCache _memoryCache) {
DisplayBuffet_NotifyDataSetChanged_Fragment fragment = new DisplayBuffet_NotifyDataSetChanged_Fragment();
bundle = new Bundle();
bundle.putSerializable(FindMyBuffetConstants.BUFFET_FILECACHE_KEY, _fileCache);
bundle.putSerializable(FindMyBuffetConstants.BUFFET_MEMORYCACHE_KEY, _memoryCache);
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retain this fragment across configuration changes.
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
layout = inflater.inflate(R.layout.display_buffets_fragment,container, false);
return layout;
}
private void initViews() {
fileCache = (FileCache) getArguments().getSerializable(FindMyBuffetConstants.BUFFET_FILECACHE_KEY);
memoryCache = (MemoryCache) getArguments().getSerializable(FindMyBuffetConstants.BUFFET_MEMORYCACHE_KEY);
xmlFragmentListView = ((ListView) layout.findViewById(R.id.sortrestaurantlistview));
btnRating=(Button) getActivity().findViewById(R.id.btnRating);
btnPrice=(Button) getActivity().findViewById(R.id.btnPrice);
btnDistance=(Button) getActivity().findViewById(R.id.btnDistance);
}
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
arrayListBuffet = new ArrayList<HashMap<String, String>>();
mHelper = new FindMyBuffetDatabaseHelper(FindMyBuffetApplication.currentActivityContext);
database = mHelper.getWritableDatabase();
initViews();
btnRating.setOnClickListener(this);
btnPrice.setOnClickListener(this);
btnDistance.setOnClickListener(this);
setListViewAdapter();
}
#Override
public void onClick(View v) {
String strOrder="asc";
if (FindMyBuffetApplication.isRatingOrderByDesc == false && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_RATING)){
btnRating.setBackgroundResource(R.drawable.tab_button_foucs_asc);
btnPrice.setBackgroundResource(R.drawable.tab_button_default);
btnDistance.setBackgroundResource(R.drawable.tab_button_default);
}
else if (FindMyBuffetApplication.isPriceOrderByDesc == false && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_PRICE)){
btnPrice.setBackgroundResource(R.drawable.tab_button_foucs_asc);
btnRating.setBackgroundResource(R.drawable.tab_button_default);
btnDistance.setBackgroundResource(R.drawable.tab_button_default);
}
else if (FindMyBuffetApplication.isDistanceOrderByDesc == false && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_DISTANCE)){
btnDistance.setBackgroundResource(R.drawable.tab_button_foucs_asc);
btnRating.setBackgroundResource(R.drawable.tab_button_default);
btnPrice.setBackgroundResource(R.drawable.tab_button_default);
}
else if (FindMyBuffetApplication.isRatingOrderByDesc == true && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_RATING)){
btnRating.setBackgroundResource(R.drawable.tab_button_foucs_dec);
btnDistance.setBackgroundResource(R.drawable.tab_button_default);
btnPrice.setBackgroundResource(R.drawable.tab_button_default);
}
else if (FindMyBuffetApplication.isPriceOrderByDesc == true && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_PRICE)){
btnPrice.setBackgroundResource(R.drawable.tab_button_foucs_dec);
btnDistance.setBackgroundResource(R.drawable.tab_button_default);
btnRating.setBackgroundResource(R.drawable.tab_button_default);
}
else if (FindMyBuffetApplication.isDistanceOrderByDesc == true && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_DISTANCE)){
btnDistance.setBackgroundResource(R.drawable.tab_button_foucs_dec);
btnPrice.setBackgroundResource(R.drawable.tab_button_default);
btnRating.setBackgroundResource(R.drawable.tab_button_default);
}
switch(v.getId()) {
case R.id.btnRating:
FindMyBuffetApplication.sortBy = FindMyBuffetConstants.TAB_NAME_RATING;
if (FindMyBuffetApplication.isRatingOrderByDesc == false)
FindMyBuffetApplication.isRatingOrderByDesc = true;
else
FindMyBuffetApplication.isRatingOrderByDesc = false;
//displayView();
if(FindMyBuffetApplication.isRatingOrderByDesc==true)strOrder="desc";
sortListView(FindMyBuffetConstants.SORT_BY_RATING_1,strOrder);
break;
case R.id.btnPrice:
FindMyBuffetApplication.sortBy = FindMyBuffetConstants.TAB_NAME_PRICE;
if (FindMyBuffetApplication.isPriceOrderByDesc == false)
FindMyBuffetApplication.isPriceOrderByDesc = true;
else
FindMyBuffetApplication.isPriceOrderByDesc = false;
//displayView();
if(FindMyBuffetApplication.isPriceOrderByDesc==true)strOrder="desc";
sortListView(FindMyBuffetConstants.SORT_BY_PRICE_1,strOrder);
break;
case R.id.btnDistance:
FindMyBuffetApplication.sortBy = FindMyBuffetConstants.TAB_NAME_DISTANCE;
if (FindMyBuffetApplication.isDistanceOrderByDesc == false)
FindMyBuffetApplication.isDistanceOrderByDesc = true;
else
FindMyBuffetApplication.isDistanceOrderByDesc = false;
//displayView();
if(FindMyBuffetApplication.isPriceOrderByDesc==true)strOrder="desc";
sortListView(FindMyBuffetConstants.SORT_BY_DISTANCE_1,strOrder);
break;
}
}
private void setListViewAdapter(){
downloadTask = new DisplayBuffetAsyncTask();
if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_RATING){
if (FindMyBuffetApplication.isDownloading) {
downloadTask.initilizeAsyncTask(
getFragmentManager(), xmlFragmentListView,downloadTask,
fileCache,memoryCache);
downloadTask.execute();
}
}
else if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_PRICE){
if (FindMyBuffetApplication.isDownloading) {
downloadTask.initilizeAsyncTask(
getFragmentManager(), xmlFragmentListView,
downloadTask,
fileCache,memoryCache);
downloadTask.execute();
}
}
else if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_DISTANCE){
if (FindMyBuffetApplication.isDownloading) {
downloadTask.initilizeAsyncTask(
getFragmentManager(), xmlFragmentListView,
downloadTask,
fileCache,memoryCache);
downloadTask.execute();
}
}
listViewAdapter = new DisplayBuffetAdapter(arrayListBuffet, fileCache,memoryCache);
xmlFragmentListView.setAdapter(listViewAdapter);
}
private void sortListView(String strSortBy,String strOrder) {
arrayListBuffet.clear();
if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_RATING) {
SortBuffets(FindMyBuffetConstants.SORT_BY_RATING_1, strOrder);
} else if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_PRICE) {
SortBuffets(FindMyBuffetConstants.SORT_BY_PRICE_1, strOrder);
} else if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_DISTANCE) {
SortBuffets(FindMyBuffetConstants.SORT_BY_DISTANCE_1, strOrder);
}
listViewAdapter.notifyDataSetChanged();
}
/*#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
}*/
private void displayView() {
Fragment objFragment = getFragmentManager().findFragmentById(getId());
if (objFragment != null) {
getFragmentManager().beginTransaction().remove(objFragment).commit();
//objFragment = new SortBuffetRating();
objFragment = DisplayBuffet_Json_Fragment.newInstance(fileCache,memoryCache);
getFragmentManager().beginTransaction().add(R.id.frame_container, objFragment).commit();
} else {
//objFragment = new SortBuffetRating();
objFragment = DisplayBuffet_Json_Fragment.newInstance(fileCache,memoryCache);
getFragmentManager().beginTransaction().add(R.id.frame_container, objFragment).commit();
}
}
/*
* Displays data from SQLite
*/
private void SortBuffets(String strSortBy,String strOrder){
Cursor mCursor = database.rawQuery("select * from " + BuffetTable.TABLE_NAME_BUFFET + " order by " + strSortBy +" "+strOrder, null);
try {
// looping through all rows and adding to list
if (mCursor.moveToFirst()) {
do {
HashMap<String, String> map=new HashMap<String, String>();
map.put(BuffetTable.COLUMN_ID,mCursor.getString(0));
map.put(BuffetTable.COLUMN_BUF_OFF_ID,mCursor.getString(1));
map.put(BuffetTable.COLUMN_FROM_TIME,mCursor.getString(2));
map.put(BuffetTable.COLUMN_TO_TIME,mCursor.getString(3));
map.put(BuffetTable.COLUMN_ONLINE_PRICE,mCursor.getString(4));
map.put(BuffetTable.COLUMN_RESERVED_PRICE,mCursor.getString(5));
map.put(BuffetTable.COLUMN_BUF_IMAGE_FILE_NAME,mCursor.getString(6));
map.put(BuffetTable.COLUMN_RES_NAME,mCursor.getString(7));
map.put(BuffetTable.COLUMN_RATING,mCursor.getString(8));
map.put(BuffetTable.COLUMN_LATITUDE,mCursor.getString(9));
map.put(BuffetTable.COLUMN_LONGITUDE,mCursor.getString(10));
map.put(BuffetTable.COLUMN_BUF_TYPE_NAME,mCursor.getString(11));
arrayListBuffet.add(map);
} while (mCursor.moveToNext());
}
}catch (SQLiteException e){
Log.i(FindMyBuffetApplication.applicationName+"."+FindMyBuffetConstants.PACKAGE_NAME+"."+FindMyBuffetConstants.PACKAGE_NAME,"Error Druing Sorting Buffets "+ e.getMessage());
e.printStackTrace();
Toast.makeText(FindMyBuffetApplication.currentActivityContext, "Error Druing Sorting The Buffets By" +strSortBy,Toast.LENGTH_LONG).show();
}catch (Exception e) {
Log.i(FindMyBuffetApplication.applicationName+"."+FindMyBuffetConstants.PACKAGE_NAME+"."+FindMyBuffetConstants.PACKAGE_NAME,"Error Druing Sorting Buffets "+ e.getMessage());
e.printStackTrace();
Toast.makeText(FindMyBuffetApplication.currentActivityContext, "Error Druing Sorting The Buffets By" +strSortBy,Toast.LENGTH_LONG).show();
}finally {
// Release the memory
mCursor.close();
}
}
#Override
public void onDestroy() {
super.onDestroy();
database.close();
//layout = null; // now cleaning up!
//bundle = null;
/*fragment = null;
if (downloadTask != null && downloadTask.getStatus() != AsyncTask.Status.FINISHED)
downloadTask=null;*/
}
}
DisplayBuffetAdapter.java
public class DisplayBuffetAdapter extends BaseAdapter {
// Declare Variables
ImageLoader imageLoader;
ArrayList<HashMap<String, String>> arrayListBuffet;
LayoutInflater inflater;
FileCache fileCache=null;
MemoryCache memoryCache=null;
int tmpLoopCnt=0;
public DisplayBuffetAdapter(ArrayList<HashMap<String, String>> _arraylist,FileCache _fileCache,MemoryCache _memoryCache) {
this.arrayListBuffet = _arraylist;
this.fileCache=_fileCache;
this.memoryCache=_memoryCache;
this.imageLoader=new ImageLoader(FindMyBuffetApplication.currentActivityContext,fileCache,memoryCache);
tmpLoopCnt=0;
}
public int getCount() {
return arrayListBuffet.size();
}
public Object getItem(int position) {
return arrayListBuffet.get(position);
}
public long getItemId(int position) {
return position;
}
private class ViewHolder {
// Declare Variables
ImageView imgRestBuffLogo;
TextView txtResName;
TextView txtRestBufType;
TextView txtRestTime;
TextView txtRestDistance;
TextView txtReservePrice;
TextView txtOnlinePrice;
RatingBar restRatingBar;
Button btnOnlinePrice;
Button btnReservedPrice;
}
public View getView(int position, View convertView, ViewGroup parent) {
tmpLoopCnt = tmpLoopCnt + 1;
Log.i("LIST VIEW ADAPATER COUNT", ""+tmpLoopCnt);
ViewHolder holder;
LayoutInflater inflater;
if (convertView == null) {
inflater = (LayoutInflater) FindMyBuffetApplication.currentActivityContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.display_buffet_listview, null);
holder = new ViewHolder();
Typeface txtResnameFontFace=Typeface.createFromAsset(FindMyBuffetApplication.currentActivityContext.getAssets(), "Roboto-Bold.ttf");
Typeface txtRestBufTypeFontFace=Typeface.createFromAsset(FindMyBuffetApplication.currentActivityContext.getAssets(), "Roboto-Medium.ttf");
Typeface txtRestTimeFontFace=Typeface.createFromAsset(FindMyBuffetApplication.currentActivityContext.getAssets(), "Roboto-Bold.ttf");
//Typeface txtReservePrice=Typeface.createFromAsset(FindMyBuffetApplicationCls.currentActivityContext.getAssets(),"Roboto-Bold.ttf");
//Typeface txtOnlinePrice=Typeface.createFromAsset(FindMyBuffetApplicationCls.currentActivityContext.getAssets(),"Roboto-Bold.ttf");
Typeface btnPrice=Typeface.createFromAsset(FindMyBuffetApplication.currentActivityContext.getAssets(), "Roboto-Bold.ttf");
Typeface txtRestDistanceFontFace=Typeface.createFromAsset(FindMyBuffetApplication.currentActivityContext.getAssets(),"Roboto-Light.ttf");
// Locate the TextViews in listview_item.xml
holder.txtResName = (TextView) convertView.findViewById(R.id.txtRestName);
holder.txtResName.setTypeface(txtResnameFontFace);
holder.txtRestBufType = (TextView) convertView.findViewById(R.id.txtRestBufType);
holder.txtRestBufType.setTypeface(txtRestBufTypeFontFace);
holder.txtRestTime = (TextView) convertView.findViewById(R.id.txtRestTime);
holder.txtRestTime.setTypeface(txtRestTimeFontFace);
holder.txtRestDistance = (TextView) convertView.findViewById(R.id.txtRestDistance);
holder.txtRestDistance.setTypeface(txtRestDistanceFontFace);
holder.restRatingBar=(RatingBar) convertView.findViewById(R.id.restRatingBar);
//holder.txtReservePrice = (TextView) convertView.findViewById(R.id.txtReservePrice);
//holder.txtReservePrice.setTypeface(txtReservePrice);
//holder.txtOnlinePrice = (TextView) convertView.findViewById(R.id.txtOnlinePrice);
//holder.txtOnlinePrice.setTypeface(txtOnlinePrice);
holder.btnOnlinePrice=(Button) convertView.findViewById(R.id.btnOnlinePrice);
holder.btnOnlinePrice.setTypeface(btnPrice);
holder.btnReservedPrice=(Button) convertView.findViewById(R.id.btnReservedPrice);
holder.btnOnlinePrice.setTypeface(btnPrice);
// Locate the ImageView in listview_item.xml
holder.imgRestBuffLogo = (ImageView) convertView.findViewById(R.id.imgRestBuffetLogo);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
HashMap<String, String> objMap= arrayListBuffet.get(position);
holder.txtResName.setText(objMap.get(BuffetTable.COLUMN_RES_NAME));
holder.txtRestBufType.setText(objMap.get(BuffetTable.COLUMN_BUF_TYPE_NAME));
holder.restRatingBar.setRating(Float.valueOf(objMap.get(BuffetTable.COLUMN_RATING)));
holder.txtRestTime.setText(formatTime(objMap.get(BuffetTable.COLUMN_FROM_TIME))+" to "+formatTime(objMap.get(BuffetTable.COLUMN_TO_TIME)));
//txtOnlinePrice.setText(objMap.get("Online_Price"));
//txtReservePrice.setText(objMap.get("Reserved_Price"));
holder.btnOnlinePrice.setText(" Buy Now\n "+"Rs."+objMap.get(BuffetTable.COLUMN_ONLINE_PRICE)+" ");
holder.btnReservedPrice.setText(" Reserve\n "+"Rs."+objMap.get(BuffetTable.COLUMN_RESERVED_PRICE)+" ");
//double dist=objMap.get("Latitude")-objMap.get("Longitude");
//txtRestDistance.setText(String.valueOf(dist));
holder.txtRestDistance.setText(""+10+position+" Km");
String strUrl=FindMyBuffetApplication.URL+FindMyBuffetConstants.WEB_SERVER_PATH_BUF_IMAGE+objMap.get(BuffetTable.COLUMN_BUF_IMAGE_FILE_NAME);
imageLoader.DisplayImage(strUrl,holder.imgRestBuffLogo);
return convertView;
}
private String formatTime(String strTime){
//example For hour,minutes and seconds
// String strTime = "15:30:18 pm";
//SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a");
strTime=strTime.substring(0,5)+" am";
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
Date date = null;
try {
date = sdf.parse(strTime);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sdf.format(date);
}
}
in private void sortListView(
before calling notifyDataSetChanged, you should submit the new dataset to your adapter. Otherwise you are only chaining the data inside the fragment. You could this both creating a new Adapter and calling setListAdapter again, or creating a method inside the Adapter to update the dataset. For instance:
public void updateData(ArrayList<HashMap<String, String>> _arraylist) {
this.arrayListBuffet = _arraylist;
}
and call it before
listViewAdapter.notifyDataSetChanged();
When you sort you are in fact adding to arrayListBuffet but that may not be your only problem. What you're doing is sorting an array that's not inside the adapter, you need to pass the newly sorted data, in your case arrayListBuffet back to the adapter before calling notifyDataSetChanged
Why? Because if you don't, the data that the adapter is using is still the one from when you initialised it, and therefore you'll see no changes. In other words, you didn't really change the dataset it's using.
How? You can create a method in your adapter and pass the newly sorted data source as a parameter, replacing the original content, you can actually call the notifyDataSetChanged from within that same method.
Code
In your adapter:
public void updateDataSource(ArrayList<HashMap<String, String>> sortedArrayListBuffet) {
this.arrayListBuffet = sortedArrayListBuffet;
this.notifyDataSetChanged();
}