I want add multiple Data Items of same date in single Card View in Android - android-studio

I want data to be displayed as shown in imageenter image description here
I want to add multiple item of same date in single card view instead of creating another card view for the item of same date
I have tried in Android Studio grouping recycler view called as sanctioned Recycler view where I used date as header but it's not the solution
My Adapter Class
private Context mContext;
List<ListItem> consolidatedList = new ArrayList<>();
public AttendanceAdapter(Context context, List<ListItem>
consolidatedList) {
this.consolidatedList = consolidatedList;
this.mContext = context;
}
#Override
public RecyclerView.ViewHolder
onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater =
LayoutInflater.from(parent.getContext());
switch (viewType) {
case ListItem.TYPE_GENERAL:
View v1 =
inflater.inflate(R.layout.attendance_adapter_layout, parent,
false);
viewHolder = new GeneralViewHolder(v1);
break;
case ListItem.TYPE_DATE:
View v2 =
inflater.inflate(R.layout.attn_item_header, parent, false);
viewHolder = new DateViewHolder(v2);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder
viewHolder, int position)
{
switch (viewHolder.getItemViewType()) {
case ListItem.TYPE_GENERAL:
GeneralItem generalItem = (GeneralItem)
consolidatedList.get(position);
GeneralViewHolder generalViewHolder=
(GeneralViewHolder) viewHolder;
//generalViewHolder.txt_date.setText(
generalItem.getAttendance_data().getDate());
generalViewHolder.txt_month.setText(
generalItem.getAttendance_data().getMonth_name());
generalViewHolder.txt_date.setText(
generalItem.getAttendance_data().getDate_no());
generalViewHolder.txt_out.setText(
generalItem.getAttendance_data().getAttn_out_time());
generalViewHolder.txt_in.setText(
generalItem.getAttendance_data().getAttn_In_time());
generalViewHolder.txtreason.setText
(generalItem.getAttendance_data().getRemark());
break;
case ListItem.TYPE_DATE:
DateItem dateItem = (DateItem)
consolidatedList.get(position);
DateViewHolder dateViewHolder = (DateViewHolder) viewHolder;
dateViewHolder.txtTitle.setText(dateItem.getDate());
// Populate date item data here
break;
}
}
class DateViewHolder extends RecyclerView.ViewHolder {
protected TextView txtTitle;
public DateViewHolder(View v) {
super(v);
this.txtTitle = (TextView)
v.findViewById(R.id.attn_date);
}
}
// View holder for general row item
class GeneralViewHolder extends RecyclerView.ViewHolder {
protected TextView
txt_in,txtreason,txt_out,txt_date,txt_month;
public GeneralViewHolder(View v) {
super(v);
this.txt_in =v.findViewById(R.id.attn_in_txt);
this.txt_out=v.findViewById(R.id.attn_out_txt);
this.txtreason=v.findViewById(R.id.attn_reason_txt);
this.txt_date=v.findViewById(R.id.date_view);
this.txt_month=v.findViewById(R.id.month_view);
}
}
#Override
public int getItemViewType(int position) {
return consolidatedList.get(position).getType();
}
#Override
public int getItemCount() {
return consolidatedList != null ? consolidatedList.size() : 0;
}
}
MainActivity.Java
public class CurrentMonth extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... voids) {
attn_list_data_cur_month();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
updateUi();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
public void attn_list_data_cur_month(){
try {
this.connection=createConnection();
Statement stmt=connection.createStatement();
Calendar current_month_data = Calendar.getInstance();
current_month_data.add(Calendar.MONTH, 0);
//Calendar current_month_date = Calendar.getInstance();
//current_month_date.set(Calendar.DAY_OF_MONTH,0);
n=current_month_data.get(Calendar.DAY_OF_MONTH);
String current_month_year = new SimpleDateFormat("MMM-
yyyy").format(current_month_data.getTime());
String month_name=currentMonth.getText().toString();
for (int i=1;i<=n;i++) {
String date = i + "-" + current_month_year;
ResultSet resultSet = stmt.executeQuery("Select * from
MATTN_MAS where ATTN_DATE='" + date + "' and Username='" +
Username + "'");
String Attn_Type;
if (resultSet.next()) {
while (resultSet.next()) {
Attn_Type = resultSet.getString(8);
String Time = null;
String Reason = resultSet.getString(11);
if (Attn_Type.equals("I")) {
String Attn_Type_In = "I";
String Attn_Type_Out = null;
StringBuilder stringBuilder = new StringBuilder("" + i);
String date_no = stringBuilder.toString();
myOptions.add(new Attendance_Data(Attn_Type_In,
date, Reason, Attn_Type_Out, i, date_no, month_name));
} else {
String Attn_Type_Out = "O";
String Attn_Type_In = null;
StringBuilder stringBuilder = new StringBuilder("" + i);
String date_no = stringBuilder.toString();
myOptions.add(new Attendance_Data(Attn_Type_In,
date, Reason, Attn_Type_Out, i, date_no, month_name));
}
}
} else {
Attn_Type = "Absent";
String Time = null;
String Reason = null;
String out = null;
StringBuilder stringBuilder = new StringBuilder("" + i);
String date_no = stringBuilder.toString();
myOptions.add(new Attendance_Data(Attn_Type, date, Reason,
out, i, date_no, month_name));
}
}
}catch (Exception e){
System.out.println("my Error"+e);
}
}
public void updateUi(){
//sortedData= (List<PojoOfJsonArray>)
PojoOfJsonArray.sortList(myOptions);
HashMap<String, List<Attendance_Data>> groupedHashMap =
groupDataIntoHashMap(myOptions);
for (String date1 : groupedHashMap.keySet()) {
DateItem dateItem = new DateItem();
dateItem.setDate(date1);
consolidatedList.add(dateItem);
for (Attendance_Data pojoOfJsonArray : groupedHashMap.get(date1))
{
GeneralItem generalItem = new GeneralItem();
generalItem.setAttendance_data(pojoOfJsonArray);
consolidatedList.add(generalItem);
}
}
adapter = new AttendanceAdapter(this, consolidatedList);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
attn_report_view.setLayoutManager(layoutManager);
attn_report_view.setAdapter(adapter);
}
private HashMap<String, List<Attendance_Data>>
groupDataIntoHashMap(List<Attendance_Data> listOfPojosOfJsonArray) {
HashMap<String, List<Attendance_Data>> groupedHashMap = new HashMap<>
();
for (Attendance_Data pojoOfJsonArray : listOfPojosOfJsonArray) {
String hashMapKey = pojoOfJsonArray.getDate();
if (groupedHashMap.containsKey(hashMapKey)) {
// The key is already in the HashMap; add the pojo object
// against the existing key.
groupedHashMap.get(hashMapKey).add(pojoOfJsonArray);
} else {
List<Attendance_Data> list = new ArrayList<>();
list.add(pojoOfJsonArray);
groupedHashMap.put(hashMapKey, list);
}
}
return groupedHashMap;
}
I want to add multiple items of same date in same single single card view but instead it is creating multiple Card View for multiple items of same date

You have to use RecyclerView Multiple ViewTypes. for detail please check this example.
Also visit this example.

Yeah I found the solution it worked perfect for Me.....we
have to just make changes to the card View by removing
spaces..
.
like this below...
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardMaxElevation="0.1dp"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:background="#303030"
card_view:cardElevation="5dp"
android:foreground="?android:attr/selectableItemBackground"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_marginLeft="#dimen/dp_2"
android:layout_marginRight="#dimen/dp_2">
<...Your All Text Boxes and further Layout inside this
cardView...>
</android.support.v7.widget.CardView>
and I have add Header for each CardView....and it looks like
this
Outout is shown in below image

Related

How to save the content of custom array class and adapter in list view save into text in android

I need your help I am new in android programming. How can I save all the content in the list view save into text file this is my code of try to save the file but the problem is how can i put the listview array list to get the data i don't know how to put it where to put it please help how to do it to save the content of my listview
Button code:
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
for (int i = 0; i < ChatBubbles.length; i++) {
myOutWriter.append(ChatBubbles[i] +"\n");
}
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
Chatbubble class:
package com.example.ezminute;
public class ChatBubble {
private String content;
private boolean myMessage;
public ChatBubble(String content, boolean myMessage) {
this.content = content;
this.myMessage = myMessage;
}
public String getContent() {
return content;
}
public boolean myMessage() {
return myMessage;
}
}
MessageAdapter:
package com.example.ezminute;
public class MessageAdapter extends ArrayAdapter<ChatBubble> {
private Activity activity;
private List<ChatBubble> messages;
public MessageAdapter(Activity context, int resource, List<ChatBubble> objects) {
super(context, resource, objects);
this.activity = context;
this.messages = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
int layoutResource = 0; // determined by view type
ChatBubble ChatBubble = getItem(position);
int viewType = getItemViewType(position);
if (ChatBubble.myMessage()) {
layoutResource = R.layout.left_chat_bubble;
} else {
layoutResource = R.layout.right_chat_bubble;
}
if (convertView != null) {
holder = (ViewHolder) convertView.getTag();
} else {
convertView = inflater.inflate(layoutResource, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
//set message content
holder.msg.setText(ChatBubble.getContent());
return convertView;
}
#Override
public int getViewTypeCount() {
// return the total number of view types. this value should never change
// at runtime. Value 2 is returned because of left and right views.
return 2;
}
#Override
public int getItemViewType(int position) {
// return a value between 0 and (getViewTypeCount - 1)
return position % 2;
}
private class ViewHolder {
private TextView msg;
public ViewHolder(View v) {
msg = (TextView) v.findViewById(R.id.txt_msg);
}
}
}

Loading image from URL to ListView

I am trying to make a list view. I did it successfully without the photos loading from url without using a custom array adapter. However how can I implement loading images from url without using a custom array adapter?
I am trying to use the working codes from this thread but it is giving an error for holder.
Error Part
icon = new ImageDownloaderTask(holder.imageView).execute(doctorPhoto);
DoctorsActivity.java
public class DoctorsActivity extends AppCompatActivity {
private JSONArray arrayAdapter;
private static final String URL_FOR_BALANCE = "http://192.168.1.28/api2/doctors.php";
String cancel_req_tag = "login";
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
Bitmap icon = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctors);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.toolbar_doctors);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#003764")));
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
final String pid = sharedPreferences.getString(Config.UID_SHARED_PREF, null);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_BALANCE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
JSONArray contacts = jObj.getJSONArray("user");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String doctorTitle = c.getString("title");
String doctorName = c.getString("first_name");
String doctorSurname = c.getString("last_name");
String doctorPhoto = c.getString("photo"); //image URL
String doctorMobile = c.getString("mobile");
String doctorFullName = doctorTitle+" "+doctorName+" "+doctorSurname;
icon = new ImageDownloaderTask(holder.imageView).execute(doctorPhoto);
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("photo", icon);
contact.put("doctor", doctorFullName);
contact.put("mobile", doctorMobile);
// adding contact to contact list
contactList.add(contact);
}
ListAdapter adapter = new SimpleAdapter(
DoctorsActivity.this, contactList,
R.layout.activity_doctors_list_item, new String[]{"photo", "doctor",
"mobile"}, new int[]{R.id.photo,
R.id.doctor, R.id.mobile});
lv.setAdapter(adapter);
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to login url
Map<String, String> params = new HashMap<String, String>();
params.put("uid", pid);
params.put("lang", Locale.getDefault().getDisplayLanguage());
return params;
}
};
// Adding request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq,cancel_req_tag);
}
class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownloaderTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(String... params) {
return downloadBitmap(params[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
Drawable placeholder = null;
imageView.setImageDrawable(placeholder);
}
}
}
}
private Bitmap downloadBitmap(String url) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();
final int responseCode = urlConnection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
urlConnection.disconnect();
Log.w("ImageDownloader", "Errore durante il download da " + url);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
}
}
Why not use a 3rd party lib like https://github.com/bumptech/glide?
Relevant code:
// ...
new Glide
.with(convertView.getContext())
.load(url)
.centerCrop()
.placeholder(R.drawable.noimage)
.crossFade()
.into(bmImage);
holder.tvName.setText(doctorList.get(position).getName());
holder.tvMobile.setText(doctorList.get(position).getMobile());
// ...
For everyone who wants to have listView with images this my corrected working Custom Adapter:
public class DoctorAdapter extends ArrayAdapter<Doctors>{
ArrayList<Doctors> doctorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public DoctorAdapter(Context context, int resource, ArrayList<Doctors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
doctorList = objects;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.photo);
holder.tvName = (TextView) v.findViewById(R.id.doctor);
holder.tvMobile = (TextView) v.findViewById(R.id.mobile);
holder.callButton = (Button) v.findViewById(R.id.btnCall);
holder.callButton.setTag(holder);
holder.callButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewHolder viewHolder = (ViewHolder) view.getTag();
String message= viewHolder.tvMobile.getText().toString();
Toast.makeText(view.getContext(), message, Toast.LENGTH_SHORT).show();
}
});
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.noimage);
new DownloadImageTask(holder.imageview).execute(doctorList.get(position).getImage());
holder.tvName.setText(doctorList.get(position).getName());
holder.tvMobile.setText(doctorList.get(position).getMobile());
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView tvName;
public TextView tvMobile;
public Button callButton;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}

How to refresh adapter and deselect all items each time when user clicks on multispinner?

I want to refresh the getview() of baseadapter each time when user click on multispinner. Also wants to deselect all the selected checkbox.
Anybody please help.
Blockquote
Below is my multispinner java class
public class MultiSpinnerSearch extends Spinner implements OnCancelListener {
private static final String TAG = MultiSpinnerSearch.class.getSimpleName();
private List<KeyPairBoolData> items;
private String defaultText = "";
private String spinnerTitle = "";
private SpinnerListener listener;
private int limit = 0;
private int selected = 0;
private LimitExceedListener limitListener;
MyAdapter adapter;
public static AlertDialog.Builder builder;
public static AlertDialog ad;
public MultiSpinnerSearch(Context context) {
super(context);
}
public MultiSpinnerSearch(Context arg0, AttributeSet arg1) {
super(arg0, arg1);
TypedArray a = arg0.obtainStyledAttributes(arg1, R.styleable.MultiSpinnerSearch);
limit = a.getIndexCount();
for (int i = 0; i < limit; ++i) {
int attr = a.getIndex(i);
if (attr == R.styleable.MultiSpinnerSearch_hintText) {
spinnerTitle = a.getString(attr);
defaultText = spinnerTitle;
break;
}
}
Log.i(TAG, "spinnerTitle: " + spinnerTitle);
a.recycle();
}
public MultiSpinnerSearch(Context arg0, AttributeSet arg1, int arg2) {
super(arg0, arg1, arg2);
}
public void setLimit(int limit, LimitExceedListener listener) {
this.limit = limit;
this.limitListener = listener;
}
public List<KeyPairBoolData> getSelectedItems() {
List<KeyPairBoolData> selectedItems = new ArrayList<>();
for (KeyPairBoolData item : items) {
if (item.isSelected()) {
selectedItems.add(item);
}
}
return selectedItems;
}
public List<Long> getSelectedIds() {
List<Long> selectedItemsIds = new ArrayList<>();
for (KeyPairBoolData item : items) {
if (item.isSelected()) {
selectedItemsIds.add(item.getId());
}
}
return selectedItemsIds;
}
#Override
public void onCancel(DialogInterface dialog) {
// refresh text on spinner
StringBuilder spinnerBuffer = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
if (items.get(i).isSelected()) {
spinnerBuffer.append(items.get(i).getName());
spinnerBuffer.append(", ");
}
}
String spinnerText = spinnerBuffer.toString();
if (spinnerText.length() > 2)
spinnerText = defaultText;
else
spinnerText = defaultText;
ArrayAdapter<String> adapterSpinner = new ArrayAdapter<>(getContext(), R.layout.textview_for_spinner, new String[]{spinnerText});
setAdapter(adapterSpinner);
if (adapter != null)
adapter.notifyDataSetChanged();
listener.onItemsSelected(items);
}
#Override
public boolean performClick() {
builder = new AlertDialog.Builder(new ContextThemeWrapper(getContext(), R.style.Material_App_Dialog));
builder.setTitle(spinnerTitle);
final LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view = inflater.inflate(R.layout.alert_dialog_listview_search, null);
builder.setView(view);
final ListView listView = (ListView) view.findViewById(R.id.alertSearchListView);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setFastScrollEnabled(false);
adapter = new MyAdapter(getContext(), items);
listView.setAdapter(adapter);
final TextView emptyText = (TextView) view.findViewById(R.id.empty);
listView.setEmptyView(emptyText);
final EditText editText = (EditText) view.findViewById(R.id.alertSearchEditText);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
builder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.i(TAG, " ITEMS : " + items.size());
dialog.cancel();
}
});
builder.setOnCancelListener(this);
ad = builder.show();
return true;
}
public void setItems(List<KeyPairBoolData> items, int position, SpinnerListener listener) {
this.items = items;
this.listener = listener;
StringBuilder spinnerBuffer = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
if (items.get(i).isSelected()) {
spinnerBuffer.append(items.get(i).getName());
spinnerBuffer.append(", ");
}
}
if (spinnerBuffer.length() > 2)
defaultText = spinnerBuffer.toString().substring(0, spinnerBuffer.toString().length() - 2);
ArrayAdapter<String> adapterSpinner = new ArrayAdapter<>(getContext(), R.layout.textview_for_spinner, new String[]{defaultText});
setAdapter(adapterSpinner);
if (position != -1) {
items.get(position).setSelected(true);
//listener.onItemsSelected(items);
onCancel(null);
}
}
public interface LimitExceedListener {
void onLimitListener(KeyPairBoolData data);
}
//Adapter Class
public class MyAdapter extends BaseAdapter implements Filterable {
List<KeyPairBoolData> arrayList;
List<KeyPairBoolData> mOriginalValues; // Original Values
LayoutInflater inflater;
public MyAdapter(Context context, List<KeyPairBoolData> arrayList) {
this.arrayList = arrayList;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
TextView textView;
CheckBox checkBox;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Log.i(TAG, "getView() enter");
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.item_listview_multiple, parent, false);
holder.textView = (TextView) convertView.findViewById(R.id.alertTextView);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.alertCheckbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final int backgroundColor = (position % 2 == 0) ? R.color.list_background : R.color.list_background;
convertView.setBackgroundColor(ContextCompat.getColor(getContext(), backgroundColor));
if (position==0)
{
holder.textView.setTextColor(Color.BLACK);
}
if (position==3)
{
holder.textView.setTextColor(Color.GREEN);
convertView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.list_selected));
}
final KeyPairBoolData data = arrayList.get(position);
holder.textView.setText(data.getName());
holder.textView.setTypeface(null, Typeface.NORMAL);
holder.checkBox.setChecked(data.isSelected());
convertView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (data.isSelected()) { // unselect
selected--;
} else if (selected == limit) { // select with limit
if (limitListener != null)
limitListener.onLimitListener(data);
return;
} else { // selected
selected++;
}
final ViewHolder temp = (ViewHolder) v.getTag();
temp.checkBox.setChecked(!temp.checkBox.isChecked());
data.setSelected(!data.isSelected());
Log.i(TAG, "On Click Selected Item : " + data.getName() + " : " + data.isSelected());
}
});
holder.checkBox.setTag(holder);
return convertView;
}
#SuppressLint("DefaultLocale")
#Override
public Filter getFilter() {
return new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
arrayList = (List<KeyPairBoolData>) results.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
List<KeyPairBoolData> FilteredArrList = new ArrayList<>();
if (mOriginalValues == null) {
mOriginalValues = new ArrayList<>(arrayList); // saves the original data in mOriginalValues
}
/********
*
* If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values
* else does the Filtering and returns FilteredArrList(Filtered)
*
********/
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = mOriginalValues.size();
results.values = mOriginalValues;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mOriginalValues.size(); i++) {
Log.i(TAG, "Filter : " + mOriginalValues.get(i).getName() + " -> " + mOriginalValues.get(i).isSelected());
String data = mOriginalValues.get(i).getName();
if (data.toLowerCase().contains(constraint.toString())) {
FilteredArrList.add(mOriginalValues.get(i));
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
}
}
}
And from my main activity
MultiSpinnerSearch searchSpinner = (MultiSpinnerSearch) findViewById(R.id.searchMultiSpinner);
searchSpinner.setItems(listArray, -1, new SpinnerListener() {
#Override
public void onItemsSelected(List<KeyPairBoolData> items) {
for (int i = 0; i < items.size(); i++) {
if (items.get(i).isSelected()) {
Log.i("TAG", i + " : " + items.get(i).getName() + " : " + items.get(i).isSelected());
FlashMessage(i + " : " + items.get(i).getName() + " : " + items.get(i).isSelected());
if (GroupName.equals(""))
{
GroupName=GroupName+items.get(i).getName();
Group_stuid=Group_stuid+student_idlist[i+1];
}
else
{
GroupName=GroupName+","+items.get(i).getName();
Group_stuid=Group_stuid+"#"+student_idlist[i+1];
}
}
}
FlashMessage("grp name : "+GroupName);
FlashMessage("grp id : "+Group_stuid);
Audiofilename=appfunct.checkfile(eventType,acdses_sct,class_sct,category_sct,subject_sct,test_sct,Group_stuid,GroupName);
outfolder=appfunct.outfldr();
Group_stuid=Group_stuid.replaceAll("/","-");
File create_stuid=new File(outfolder.toString()+"/"+Group_stuid);
if(!create_stuid.exists()) {
create_stuid.mkdirs();
}
FlashMessage(""+GroupFoldername);
Group_listFiles=appfunct.showlistfiles(GroupFoldername);
if (Group_listFiles != null)
{
final CustomGroupFolder_ListDispaly adapter1 = new CustomGroupFolder_ListDispaly(Group_recording.this,R.layout.group_item_listview,Group_listFiles);
group_listview.setAdapter(adapter1);
}
GroupName="";
Group_stuid="";
selected_students=appfunct.getSelectedNamesGroup(GroupFoldername);
}
});
FlashMessage("out : grp id "+Group_stuid);
searchSpinner.setLimit(2, new MultiSpinnerSearch.LimitExceedListener() {
#Override
public void onLimitListener(KeyPairBoolData data) {
Toast.makeText(getApplicationContext(),
"Limit exceed ", Toast.LENGTH_LONG).show();
}
});
apply this to your adapter adapter.notifyDataSetChanged();

How to update TableView Row using javaFx

I'm trying to make some downloads and show the progress inside my table:
to do that I'm using the following classes:
public class DownloadDataTable {
private SimpleDoubleProperty progress;
private SimpleStringProperty type;
private SimpleStringProperty status;
public DownloadDataTable(double progress, String type, String status) {
this.progress = new SimpleDoubleProperty(progress);
this.type = new SimpleStringProperty(type);
this.status = new SimpleStringProperty(status);
}
public double getProgress() {
return progress.get();
}
public void setProgress(double progress) {
this.progress.set(progress);
}
public String getType() {
String retorno;
if (type==null){
retorno="";
}else{
retorno=type.get();
}
return retorno;
}
public void setType (String type) {
this.type.set(type);
}
public String getStatus(){
String retorno;
if (status==null){
retorno="";
} else{
retorno=status.get();
}
return retorno;
}
public void setStatus(String status){
this.status.set(status);
}
}
and to create the TitledPane, tableview and column tables I'm doing this:
public void addDownloadToTitledPane(DownloadContent downloadContent) {
MetaDados metaDado = downloadContent.getMetaDado();
String title = metaDado.getName();
if (title.length() > 60) {
title = title.substring(0, 57) + "...";
}
TableView downloadTable = new TableView();
TableColumn<DownloadDataTable, Double> progress = new TableColumn<>("progress");
progress.setCellFactory(new Callback<TableColumn<DownloadDataTable, Double>, TableCell<DownloadDataTable, Double>>() {
#Override
public TableCell<DownloadDataTable, Double> call(TableColumn<DownloadDataTable, Double> p) {
final ProgressBar progressBar = new ProgressBar(-1);
final TableCell cell = new TableCell<DownloadDataTable, Double>() {
#Override
protected void updateItem(Double t, boolean bln) {
super.updateItem(t, bln);
if (bln) {
setText(null);
setGraphic(null);
} else {
progressBar.setProgress(t);
progressBar.prefWidthProperty().bind(this.widthProperty());
setGraphic(progressBar);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
}
};
cell.setAlignment(Pos.CENTER);
return cell;
}
});
progress.setCellValueFactory(new PropertyValueFactory<DownloadDataTable, Double>("progress"));
progress.setText("Progresso");
TableColumn<DownloadDataTable, String> type = new TableColumn<>("type");
type.setCellFactory(new Callback<TableColumn<DownloadDataTable, String>, TableCell<DownloadDataTable, String>>() {
#Override
public TableCell<DownloadDataTable, String> call(TableColumn<DownloadDataTable, String> p) {
TableCell cell = new TableCell<DownloadDataTable, String>() {
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setText(empty ? null : getString());
setGraphic(null);
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
};
cell.setAlignment(Pos.CENTER);
return cell;
}
});
type.setCellValueFactory(new PropertyValueFactory<DownloadDataTable, String>("type"));
type.setText("Tipo");
TableColumn<DownloadDataTable, String> status = new TableColumn<>("status");
status.setCellFactory(new Callback<TableColumn<DownloadDataTable, String>, TableCell<DownloadDataTable, String>>() {
#Override
public TableCell<DownloadDataTable, String> call(TableColumn<DownloadDataTable, String> p) {
TableCell cell = new TableCell<DownloadDataTable, String>() {
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setText(empty ? null : getString());
setGraphic(null);
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
};
cell.setAlignment(Pos.CENTER);
return cell;
}
});
status.setCellValueFactory(new PropertyValueFactory<DownloadDataTable, String>("status"));
status.setText("Status");
downloadTable.getColumns().addAll(progress, type, status);
List<PendingComponents> pendingComponents = downloadContent.getPendingComponents();
ObservableList<DownloadDataTable> data = FXCollections.observableArrayList();
for (PendingComponents pendingComponent : pendingComponents) {
String typeComponent;
if (pendingComponent.getType().equalsIgnoreCase(Constants.HTML)) {
typeComponent = "Conteúdo Principal";
} else {
typeComponent = "Pacote de Imagens";
}
data.add(new DownloadDataTable(-1, typeComponent, "Preparando download"));
}
downloadTable.setItems(data);
downloadTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
TitledPane downloadPane = new TitledPane(title, downloadTable);
downloadPane.setId(metaDado.getOfflineUuid());
vBoxDownload.getChildren().add(downloadPane);
}
Until here everything seems to works fine, but when I try to recover my table and update the data, my table is not updated. I've debbuged and everything seems to work, even the data value is changed, but my table still without update. See my code:
private void publishProgress(final String msg) {
Platform.runLater(new Runnable() {
#Override
public void run() {
TitledPane titledPane = (TitledPane) controller.vBoxDownload.lookup("#"+metaDado.getOfflineUuid());
TableView table = (TableView) titledPane.getContent();
DownloadDataTable data = (DownloadDataTable) table.getItems().get(0);
data.setProgress(100);
data.setStatus(msg);
}
});
}
If I try to remove and add my row it doesn't work, but if I just add another row with the new values, I got a old row with the same value and a new row with new values. I can't figure out what am I doing wrong, someone can help me??
You shouldn't need to add/remove the row to get the table to update when the progress value changes.
The problem is that you're not making the progress property accessible to the TableView. This causes the progress.setCellValueFactory(...) call to wrap your getProgress() value in a new ObservableObjectWrapper. This allows the value to display in the TableView, but it won't notify the table when the value is changed.
Add the following to your DownloadDataTable class, and your table will update when the value changes:
public SimpleDoubleProperty progressProperty() {
return this.progress;
}
public SimpleStringProperty typeProperty() {
return this.type;
}
public SimpleStringProperty statusProperty() {
return this.status;
}

ExpandableListView extended using BaseExpandableListAdapter but reading from Sqlite DB example

Senior Geeks.
I'd like to request a simple but fully working example of how to implement an ExpandableListView while extending from BaseExpandableListAdapter Yet Reading data from an Sqlite Database.
I have researched and experimented on the question (see here), but with minimal success where i was able to display some data in the header, albeit it was same values repeating for all group headers. Also child items don't show.
The reason for extending with BaseExpandableListAdapter is to have a custom layout for the group header. The reason for SQLite access is naturally because thats where my data is stored.
All examples trawled on the net so far use either SimpleCursorTreeAdapter or CursorTreeAdapter as the extender in DB based applications or simply BaseExpandableListAdapter when data used is in ArrayLists.
Below is the Experimentation thus far. (with this code,only the group header is populated with the same figures over and over. Childitems dont appear)
public class ExpandableListViewAdapterCustom extends BaseExpandableListAdapter {
protected Activity currentActivity;
public ExpandableListViewAdapterCustom(Activity callingActivity){
this.currentActivity = callingActivity;
}
private Cursor mGroupsCursorLocal ;
private Cursor mChildCursor;
private Context ctx;
private int groupItem;
private int childItem;
private String[] fieldsToUseFromGroupCursor;
private int[] screenTextsToMapGroupDataTo;
private String[] fieldsToUseFromChildCursor;
private int[] screenTextsToMapChildDataTo;
public ArrayList<String> tempChild;
public LayoutInflater minflater;
public Activity activity;
public int intGroupTotal;
public void setCurrentActivity(Activity activity) {
this.activity = activity;
}
public void setCtx(Context ctx) {
this.ctx = ctx;
}
public void setGroupItem(int groupItem) {
this.groupItem = groupItem;
}
public void setChildItem(int childItem) {
this.childItem = childItem;
}
public Activity getCurrentActivity() {
return currentActivity;
}
public Cursor getmGroupsCursorLocal() {
return mGroupsCursorLocal;
}
public Context getCtx() {
return currentActivity.getBaseContext();
}
public void setmGroupsCursorLocal(Cursor mGroupsCursor) {
this.mGroupsCursorLocal = mGroupsCursor;
}
public ExpandableListViewAdapterCustom(Cursor mGroupsCursor,
Activity activity,
int groupItem,
int childItem,
String[] fieldsToUseFromGroupCursor,
int[] screenTextsToMapGroupDataTo,
String[] fieldsToUseFromChildCursor,
int[] screenTextsToMapChildDataTo) {
DatabaseRoutines db = new DatabaseRoutines(activity);
setmGroupsCursorLocal(mGroupsCursor);
mGroupsCursorLocal = db.fetchGroup();
activity.startManagingCursor (mGroupsCursor);
mGroupsCursorLocal.moveToFirst();
mChildCursor=db.fetchChildren(mGroupsCursorLocal.getColumnIndex("Year"));
mChildCursor.moveToFirst();
activity.startManagingCursor(mChildCursor);
setCtx(activity);
setCurrentActivity(activity);
}
public void setInflater(LayoutInflater mInflater, Activity act) {
this.minflater = mInflater;
activity = act;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return null;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
#Override
public View getChildView(int groupPosition,
int childPosition,boolean
isLastChild,
View convertView,
ViewGroup parent) {
View v = convertView;
if (v == null)
{
LayoutInflater inflater =
(LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.exp_listview_childrow, parent, false);
}
TextView txtMonth = (TextView) v.findViewById(R.id.txtMonth);
TextView txtMonthAmountSent = (TextView)
v.findViewById(R.id.txtMonthAmountSentValue);
TextView txtMonthReceived = (TextView)
v.findViewById(R.id.txtMonthAmountReceivedValue);
txtMonth.setText(mChildCursor.getString(mChildCursor.getColumnIndex("Month")));
txtMonthAmountSent.setText
(mChildCursor.getString(mChildCursor.getColumnIndex("TotalSent")));
txtMonthReceived.setText
(mChildCursor.getString(mChildCursor.getColumnIndex("TotalReceived")));
return v;
}
#Override
public int getChildrenCount(int groupPosition) {
return (mChildCursor.getCount());
}
#Override
public Object getGroup(int groupPosition) {
return null;
}
#Override
public int getGroupCount() {
return mGroupsCursorLocal.getCount();
}
#Override
public void onGroupCollapsed(int groupPosition) {
super.onGroupCollapsed(groupPosition);
}
#Override
public void onGroupExpanded(int groupPosition) {
super.onGroupExpanded(groupPosition);
}
#Override
public long getGroupId(int groupPosition) {
return 0;
}
#Override
public View getGroupView(
int groupPosition,
boolean isExpanded,
View convertView,
ViewGroup parent)
{
View v = convertView;
if (v == null) {
LayoutInflater inflater =
(LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.exp_listview_groupheader, parent, false);
}
TextView txtYear = (TextView) v.findViewById(R.id.txtYearValue);
TextView txtAmountSent = (TextView) v.findViewById(R.id.txtAmountSentValue);
TextView txtAmountRecieved = (TextView)
v.findViewById(R.id.txtAmountReceivedValue);
txtYear.setText(mGroupsCursorLocal.getString(
mGroupsCursorLocal.getColumnIndex("Year")));
txtAmountSent.setText(
mGroupsCursorLocal.getString(mGroupsCursorLocal.getColumnIndex("TotalSent")));
txtAmountRecieved.setText(
GroupsCursorLocal.getString(mGroupsCursorLocal.getColumnIndex("TotalReceived")));
return v;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
}
The Database code is like this
public Cursor fetchGroup() {
SQLiteDatabase db = this.getReadableDatabase(); //if memory leaks check here
String query = "SELECT DISTINCT MIN(ID) AS id,
Year, SUM(SentAmount) AS TotalSent, SUM(ReceivedAmount) AS TotalReceived
FROM MyTbl GROUP BY Year ORDER BY Year DESC ";
return db.rawQuery(query, null);}
public Cursor fetchChildren(int Yr) {
SQLiteDatabase db = this.getReadableDatabase(); //if memory leaks check here
String query = "SELECT MIN(ID) AS id,
Year, Month, SUM(SentAmount) AS TotalSent,
SUM(ReceivedAmount) AS TotalReceived
FROM MyTbl Where Year= "+ Yr +" GROUP BY Year,
Month ORDER BY Year DESC, Month DESC";
return db.rawQuery(query, null);
}
The Code is called from main activity using the following
ExpandableListView elv = (ExpandableListView)
findViewById(R.id.expandableListView);
ExpandableListAdapter mAdapter = new
ExpandableListViewAdapterCustom(mGroupsCursor,
MyActivity.this,
R.layout.exp_listview_groupheader,// Your row layout for a group
R.layout.exp_listview_childrow, // Your row layout for a child
new String[] { "Year",
"TotalSent",
"TotalReceived" },// Field(s) to use from group cursor
new int[] {R.id.txtYearValue,
R.id.txtAmountSentValue,
R.id.txtAmountReceivedValue },// Widget ids to put group data
into new String[] { "Year","Month",
"TotalSent",
"TotalReceived" }, // Field(s) to use from child cursors new
int[] {R.id.txtMonthValue,
R.id.txtMonthAmountSentValue,
R.id.txtMonthAmountReceivedValue});// Widget ids to put child d
data into
elv.setClickable(true);
elv.setAdapter(mAdapter); // set the
After almost two weeks and no answer, i decided to simply use an ExpandableListView example using ArrayLists and modified it such that the ArrayLists were populated by data from the DB. Its not what i wanted but it works. I was actually suprised that nowhwere on the web is there an example of using ExpandableListview extended form BaseAdapter but reading from SQlite using say cursorTreeAdapter or SimpleCursorAdapter.
Below is how i did it in case it helps someone in future. the code shown is the bit that populates the ArrayList from DB
public ArrayList<ExpandListGroup> SetStandardGroups() {
ArrayList<ExpandListGroup> list = new ArrayList<ExpandListGroup>();
ArrayList<ExpandListChild> list2 = new ArrayList<ExpandListChild>();
int intMonthNum;
ExpandListGroup grp;
ExpandListChild chld;
//initialize db code here
DatabaseRoutines db = new DatabaseRoutines(this);
//create the Groups retreival cursor;
Cursor mGroupsCursor = db.fetchGroup();
//---the database call is done using this code which is in my
//---custom db class which implements the sqlhelper methods etc
//------start of db code snippet-------------------------------
//---public Cursor fetchGroup() {
//---SQLiteDatabase db = this.getReadableDatabase();
//--- String query = "SELECT DISTINCT MIN(ID) AS id, Year,
//--- SUM(SentAmount) AS TotalSent,
//--- SUM(ReceivedAmount) AS TotalReceived
//--- FROM Tbl GROUP BY Year ORDER BY Year DESC ";
//--- return db.rawQuery(query, null);}
//------end of db code snippet-------------------------------
mGroupsCursor.moveToFirst();
//method is depreciated from api14 but i'm targeting Gingerbread (api10) so i need to use it.
startManagingCursor(mGroupsCursor);
int intYear;
int intHeaderCounter = 0;
int intChildCounter = 0;
int intChildTotalCount = 0;
int intHeaderTotalGroupCount = mGroupsCursor.getCount();
//set the starting Year for the loop, if there is data;
if (intHeaderTotalGroupCount > 0) {
//get the first year
//intYear = mGroupsCursor.getInt(mGroupsCursor.getColumnIndex("Year"));
for (intHeaderCounter = 0; intHeaderCounter < intHeaderTotalGroupCount; intHeaderCounter++) {
grp = new ExpandListGroup();
intYear = mGroupsCursor.getInt(mGroupsCursor.getColumnIndex("Year"));
grp.setYear(intYear);
grp.setYearAmountReceived(mGroupsCursor.getDouble(mGroupsCursor.getColumnIndex("TotalReceived")));
grp.setYearAmountSent(mGroupsCursor.getDouble(mGroupsCursor.getColumnIndex("TotalSent")));
grp.setTag(mGroupsCursor.getString(mGroupsCursor.getColumnIndex("id")));
//Prepare counters for inner loop for child items of each
Cursor mChildCursor = db.fetchChildren(intYear);
mChildCursor.moveToFirst();
intChildTotalCount = mChildCursor.getCount();
//populate child items
for (intChildCounter = 0; intChildCounter < intChildTotalCount; intChildCounter++) {
chld = new ExpandListChild();
intMonthNum = mChildCursor.getInt(mChildCursor.getColumnIndex("Month"));
chld.setMonthNumber(intMonthNum);
chld.setTotalReceivedMonth(mChildCursor.getInt(mChildCursor.getColumnIndex("TotalReceived")));
chld.setTotalSentMonth(mChildCursor.getInt(mChildCursor.getColumnIndex("TotalSent")));
chld.setTag(mGroupsCursor.getString(mGroupsCursor.getColumnIndex("id")).toString());
list2.add(chld);
//grp.setItems(list2);
//move to next child record;
mChildCursor.moveToNext();
}
grp.setItems(list2);
list.add(grp);
list2 = new ArrayList<ExpandListChild>();
//move to next parent record;
mGroupsCursor.moveToNext();
}
} else {
log.d( "yourdebugtag_here", "Sorry, No Transactions Found.");
}
//db.close();
return list;
}

Resources