I have a listview in which in each row I have a checkbox along with details o persons. Now on clicking checkboxes, I want to store the id of those persons in arrayList which I am able to store but the arrayList id in adapter. I want to access the arrayList in activity because I want to take a button in activity on clicking which I want to send ids of all the selected persons to another activity. How do I do that.
My code is below:
SendWorkList.java
public class SendWorkList extends AppCompatActivity {
List<SendWorkRow> send_work_array_list;
ListView send_work_list;
JSONArray send_work_jsonArray1,send_work_result_jsonArray2;
JSONObject send_work_jsonObject1,send_work_result_jsonArray2_i;
String[] send_work_id,send_work_name,send_work_bankaccount,send_work_ifsc,send_work_contacts,send_work_department,send_work_cardnumber,send_work_cardexpiry,send_work_cardcvv;
String send_work_status,send_work_result;
ViewGroup send_work_headerView;
Set<Integer> send_work_count;
Intent intent;
Set<String> indexes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_work);
send_work_list=findViewById( R.id.send_work_list);
send_work_array_list=new ArrayList<SendWorkRow>();
send_work_count= new HashSet<>();
}
#Override
protected void onResume() {
super.onResume();
cardDetailsList();
/* send_work_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(SendWorkList.this, "assasa", Toast.LENGTH_SHORT).show();
}
});*/
}
private void cardDetailsList()
{
RequestQueue rq = Volley.newRequestQueue(SendWorkList.this);
StringRequest stringRequest = new StringRequest( Request.Method.GET,
"http://grepthorsoftware.in/tst/bank_account/showingdata.php",
new Response.Listener<String>() {
public void onResponse(String response) {
try {
send_work_jsonArray1=new JSONArray(response);
send_work_jsonObject1 = send_work_jsonArray1.getJSONObject(0);
send_work_status= send_work_jsonObject1.getString("status");
if(send_work_status.equals("1")) {
send_work_result = send_work_jsonObject1.getString("result");
send_work_result_jsonArray2 = new JSONArray(send_work_result);
send_work_id = new String[send_work_result_jsonArray2.length()];
send_work_name = new String[send_work_result_jsonArray2.length()];
send_work_bankaccount = new String[send_work_result_jsonArray2.length()];
send_work_ifsc = new String[send_work_result_jsonArray2.length()];
send_work_contacts = new String[send_work_result_jsonArray2.length()];
send_work_department =new String[send_work_result_jsonArray2.length()];
send_work_cardnumber = new String[send_work_result_jsonArray2.length()];
send_work_cardexpiry = new String[send_work_result_jsonArray2.length()];
send_work_cardcvv= new String[send_work_result_jsonArray2.length()];
if ( send_work_name.length > 0 || send_work_id.length > 0 || send_work_bankaccount.length > 0 || send_work_ifsc.length > 0 || send_work_contacts.length > 0)
{
send_work_id = null;
send_work_name = null;
send_work_bankaccount = null;
send_work_ifsc = null;
send_work_contacts = null;
send_work_department= null;
send_work_cardnumber= null;
send_work_cardexpiry= null;
send_work_cardcvv= null;
send_work_id = new String[send_work_result_jsonArray2.length()];
send_work_name = new String[send_work_result_jsonArray2.length()];
send_work_bankaccount = new String[send_work_result_jsonArray2.length()];
send_work_ifsc = new String[send_work_result_jsonArray2.length()];
send_work_contacts = new String[send_work_result_jsonArray2.length()];
send_work_department =new String[send_work_result_jsonArray2.length()];
send_work_cardnumber = new String[send_work_result_jsonArray2.length()];
send_work_cardexpiry = new String[send_work_result_jsonArray2.length()];
send_work_cardcvv= new String[send_work_result_jsonArray2.length()];
}
for(int i=0;i<send_work_result_jsonArray2.length();i++)
{
send_work_result_jsonArray2_i=send_work_result_jsonArray2.getJSONObject(i);
send_work_id[i] = send_work_result_jsonArray2_i.getString("id");
send_work_name[i] = send_work_result_jsonArray2_i.getString("Name");
send_work_bankaccount[i] = send_work_result_jsonArray2_i.getString("Bankaccount");
send_work_ifsc[i] = send_work_result_jsonArray2_i.getString("IFSC");
send_work_contacts[i] = send_work_result_jsonArray2_i.getString("Contact");
send_work_department[i] = send_work_result_jsonArray2_i.getString("Department");
send_work_cardnumber[i] = send_work_result_jsonArray2_i.getString("Cardnumber");
send_work_cardexpiry[i] = send_work_result_jsonArray2_i.getString("Cardexpiry");
send_work_cardcvv[i] = send_work_result_jsonArray2_i.getString("Cardcvv");
}
if ( send_work_array_list.size() > 0) {
send_work_array_list.clear();
}
for (int i = 0; i < send_work_id.length && i< send_work_name.length && i < send_work_bankaccount.length && i < send_work_ifsc.length && i < send_work_contacts.length && i < send_work_department.length && i< send_work_cardnumber.length && i< send_work_cardexpiry.length && i< send_work_cardcvv.length; i++) {
send_work_array_list.add(new SendWorkRow( send_work_id[i], send_work_name[i], send_work_bankaccount[i], send_work_ifsc[i], send_work_contacts[i], send_work_department[i], send_work_cardnumber[i], send_work_cardexpiry[i],send_work_cardcvv[i]));
}
if ( send_work_headerView != null) {
send_work_list.removeHeaderView( send_work_headerView);
}
send_work_headerView = (ViewGroup) getLayoutInflater().inflate(R.layout.send_work_list_view_header, send_work_list, false);
send_work_list.addHeaderView( send_work_headerView);
send_work_list.setAdapter(new SendWorkAdapter(SendWorkList.this, send_work_array_list));
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
// TODO Auto-generated method stub
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
rq.add(stringRequest);
}
}
SendWorkAdapter.java
public class SendWorkAdapter extends BaseAdapter {
Context context;
List<SendWorkRow> send_work_array_list;
Set<String> indexes;
public SendWorkAdapter(Context context, List<SendWorkRow> send_work_array_list)
{
this.context=context;
this.send_work_array_list=send_work_array_list;
indexes = new HashSet<String>();
}
#Override
public int getCount() {
return send_work_array_list.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
LayoutInflater inflater= (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View view=inflater.inflate( R.layout.send_work_list_view_row,viewGroup,false);
CheckBox textView1=view.findViewById( R.id.send_work_checkbox_row);
TextView textView2=view.findViewById( R.id.send_work_name_row );
TextView textView3=view.findViewById( R.id.send_work_bank_account_row );
TextView textView4=view.findViewById( R.id.send_work_ifsc_row );
TextView textView5=view.findViewById( R.id.send_work_contact_number_row );
TextView textView6=view.findViewById( R.id.send_work_department_row );
TextView textView7=view.findViewById( R.id.send_work_card_number_row );
TextView textView8=view.findViewById( R.id.send_work_expiry_date_row );
TextView textView9=view.findViewById( R.id.send_work_cvv_row );
final SendWorkRow account_details_row=send_work_array_list.get( position );
textView2.setText( account_details_row.getSendWorkCardDetailsName() );
textView3.setText( account_details_row.getSendWorkCardDetailsBankAccount() );
textView4.setText( account_details_row.getSendWorkCardDetailsIfsc());
textView5.setText( account_details_row.getSendWorkCardDetailsContacts() );
textView6.setText( account_details_row.getSendWorkCardDetailsDepartment() );
textView7.setText( account_details_row.getSendWorkCardDetailsCardNumber() );
textView8.setText( account_details_row.getSendWorkCardDetailsCardExpiry() );
textView9.setText( account_details_row.getSendWorkCardDetailsCardCvv() );
textView1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(compoundButton.isChecked()){
Toast.makeText(context, account_details_row.getSendWorkCardDetailsId(), Toast.LENGTH_SHORT).show();
indexes.add(account_details_row.getSendWorkCardDetailsId());
}
}
});
return view;
}
}
SendWorkRow.java
public class SendWorkRow {
private String send_work_id,send_work_name,send_work_bankaccount,send_work_ifsc,send_work_contacts,send_work_department,send_work_cardnumber,send_work_cardexpiry,send_work_cardcvv;
public SendWorkRow(String send_work_id, String send_work_name, String send_work_bankaccount, String send_work_ifsc, String send_work_contacts,String send_work_department,String send_work_cardnumber,String send_work_cardexpiry,String send_work_cardcvv) {
this.send_work_id = send_work_id;
this.send_work_name = send_work_name;
this.send_work_bankaccount = send_work_bankaccount;
this.send_work_ifsc = send_work_ifsc;
this.send_work_contacts = send_work_contacts;
this.send_work_department = send_work_department;
this.send_work_cardnumber = send_work_cardnumber;
this.send_work_cardexpiry = send_work_cardexpiry;
this.send_work_cardcvv = send_work_cardcvv;
}
//Getters
public String getSendWorkCardDetailsId() {
return send_work_id;
}
public String getSendWorkCardDetailsName() {
return send_work_name;
}
public String getSendWorkCardDetailsBankAccount() {
return send_work_bankaccount;
}
public String getSendWorkCardDetailsIfsc() {
return send_work_ifsc;
}
public String getSendWorkCardDetailsContacts() {
return send_work_contacts;
}
public String getSendWorkCardDetailsDepartment() {
return send_work_department;
}
public String getSendWorkCardDetailsCardNumber() {
return send_work_cardnumber;
}
public String getSendWorkCardDetailsCardExpiry() {
return send_work_cardexpiry;
}
public String getSendWorkCardDetailsCardCvv() {
return send_work_cardcvv;
}
}
Create one method in adapter like
public class SendWorkAdapter extends BaseAdapter {
public List<SendWorkRow> getAllWorkRows() {
return send_work_array_list;
}
}
and access this method using adapter instance in activity.
Another way is you can write a method in Adapter where you will find all selected ids in a List and return. So whenever you will require list of selected ids, call this method from Activity and do your task. like
public class SendWorkAdapter extends BaseAdapter {
public List<SendWorkRow> getAllSelectedWorkRows() {
// write your logic to find selected rows
return result;
}
}
Related
I am getting the data from server using JSON and when i try to search in the listview it just refreshes the whole list and does not narrate it, but when i debug i can see the result on getfilter is right right and it drugsFiltered = (ArrayList<drugs_json_data>) results.values; does have the filtered data inside it. just the listview.setadaptor is being done inside onPostExecute of the asynctask.
here is my adapter code:
public class drugs_adaptor_listView extends ArrayAdapter<drugs_json_data> implements Filterable {
ArrayList<drugs_json_data> drugs;
ArrayList<drugs_json_data> drugsFiltered;
Context context;
int resource;
public drugs_adaptor_listView(Context context, int resource, ArrayList<drugs_json_data> drugs) {
super(context, resource, drugs);
this.drugs = drugs;
this.drugsFiltered = drugs;
this.context = context;
this.resource = resource;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View r = convertView;
ViewHolder viewHolder;
if (r == null) {
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
r = layoutInflater.inflate(R.layout.row_layout_drugs, null, true);
viewHolder = new ViewHolder(r);
r.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) r.getTag();
}
drugs_json_data drugs_json_data = getItem(position);
viewHolder.txtDrugId.setText(drugs_json_data.getDrugId());
viewHolder.txtDrugName.setText(drugs_json_data.getDrugName());
viewHolder.txtDrugCategory.setText(drugs_json_data.getDrugCategory());
Picasso builder = new Picasso.Builder(context).build();
builder.load(drugs_json_data.getDrugImage()).memoryPolicy(MemoryPolicy.NO_STORE).placeholder(R.drawable.ic_launcher_foreground).into(viewHolder.imageView);
return r;
}
#NonNull
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
drugsFiltered = (ArrayList<drugs_json_data>) results.values; // has the filtered values
if (results.count>0) {
notifyDataSetChanged(); // notifies the data with new filtered values
}else {
notifyDataSetInvalidated();
}
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
ArrayList<drugs_json_data> FilteredArrList = new ArrayList<>();
if (drugs == null) {
drugs = new ArrayList<>(drugsFiltered); // saves the original data in mOriginalValues
}
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = drugs.size();
results.values = drugs;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < drugs.size(); i++) {
String data = drugs.get(i).getDrugName();
if (data.startsWith(constraint.toString())) {
FilteredArrList.add(new drugs_json_data(drugs.get(i).getDrugId(), drugs.get(i).getDrugName(), drugs.get(i).getDrugCategory(), drugs.get(i).getDrugImage()));
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
class ViewHolder {
TextView txtDrugId, txtDrugName, txtDrugCategory;
ImageView imageView;
ViewHolder(View v) {
txtDrugId = v.findViewById(R.id.txtDrugId);
txtDrugName = v.findViewById(R.id.txtDrugName);
txtDrugCategory = v.findViewById(R.id.txtDrugCat);
imageView = v.findViewById(R.id.ImageViewDrug);
}
}
}
here is the data model:
public class drugs_json_data {
private String drugImage;
private String drugName;
private String drugCategory;
private String drugId;
public drugs_json_data(String drugImage, String drugName, String drugCategory, String drugId) {
this.drugImage = drugImage;
this.drugName = drugName;
this.drugCategory = drugCategory;
this.drugId = drugId;
}
public String getDrugImage() {
return this.drugImage;
}
public void setDrugImage(String drugImage) {
this.drugImage = drugImage;
}
public String getDrugName() {
return this.drugName;
}
public void setDrugName(String drugName) {
this.drugName = drugName;
}
public String getDrugCategory() {
return this.drugCategory;
}
public void setDrugCategory(String drugCategory) {
this.drugCategory = drugCategory;
}
public String getDrugId() {
return this.drugId;
}
public void setDrugId(String drugId) {
this.drugId = drugId;
}
}
and here is the main activity code:
public class clerk_drugs extends AppCompatActivity {
ListView listView;
Button createDrug;
String drug_id, json_drug;
TextView noMed;
EditText searchTxt;
JSONObject jsonObject;
JSONArray jsonArray;
ArrayList<drugs_json_data> arrayList;
drugs_adaptor_listView adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clerk_drugs);
createDrug = findViewById(R.id.create_drug);
arrayList = new ArrayList<>();
listView = findViewById(R.id.list_drugs);
noMed = findViewById(R.id.no_med);
searchTxt = findViewById(R.id.listSearch);
searchTxt.setSingleLine(true);
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
new ReadJSON().execute("http://(mylink)").get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
try {
jsonObject = new JSONObject(json_drug);
jsonArray = jsonObject.getJSONArray("server_response");
} catch (JSONException e) {
e.printStackTrace();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
drug_id = ((TextView) view.findViewById(R.id.txtDrugId)).getText().toString();
for (int i = 0; i<jsonArray.length(); i++){
try {
JSONObject jobj = jsonArray.getJSONObject(i);
String drugid = jobj.getString("drug_id");
if(drugid.equals(drug_id)) {
String drugname = jobj.getString("drug_name");
String drugcategory = jobj.getString("drug_category");
String drugdescription = jobj.getString("drug_description");
String drugphoto = jobj.getString("drug_photo");
drug_update_dialog drug_update_dialog = new drug_update_dialog();
Bundle args = new Bundle();
args.putString("drug-id", drug_id);
args.putString("drug-name", drugname);
args.putString("drug-category", drugcategory);
args.putString("drug-description", drugdescription);
args.putString("drug_photo",drugphoto);
drug_update_dialog.setArguments(args);
drug_update_dialog.show(getSupportFragmentManager(),"ویرایش اطلاعات دارو");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
searchTxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
searchTxt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus){
hideKeyboard(v);
}
}
});
}
public void hideKeyboard(View view) {
InputMethodManager inputMethodManager =(InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
class ReadJSON extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
try {
JSONObject jsonObject = new JSONObject(content);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
for(int i=0; i<jsonArray.length();i++){
JSONObject drugObj = jsonArray.getJSONObject(i);
arrayList.add(new drugs_json_data(
drugObj.getString("drug_photo"),
drugObj.getString("drug_name"),
drugObj.getString("drug_category"),
drugObj.getString("drug_id")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new drugs_adaptor_listView(
getApplicationContext(), R.layout.row_layout_drugs, arrayList
);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
if (adapter.getCount()==0){
noMed.setVisibility(View.VISIBLE);
}
}
}
private String readURL(String theURL) {
StringBuilder content = new StringBuilder();
try{
URL url = new URL(theURL);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line=bufferedReader.readLine())!=null){
content.append(line).append("\n");
}
bufferedReader.close();
}catch (Exception e){
e.printStackTrace();
}
json_drug = content.toString();
return content.toString();
}
#Override
public void onBackPressed() {
finish();
Intent intent = new Intent(this,patient_mainPage.class);
startActivity(intent);
}
public void createDrugDialog(View view){
openDrugDialog();
}
private void openDrugDialog() {
drug_add_dialog drug_add_dialog = new drug_add_dialog();
drug_add_dialog.show(getSupportFragmentManager(),"ثبت داروی جدید");
}
}
I would be grateful if someone could help.
UPDATED
In getView method in Adapter
Replace
drugs_json_data drugs_json_data = getItem(position);
With
drugs_json_data drugs_json_data = drugsFiltered.get(position);
I am facing one issue in android filter.
First of all I search some text and on the resulted value I am doing one event and come back to the activity. Once I come back that time my listview will refresh with all item rather then filtered item.
For example :
I am searching one contact from contact book and it will return some result. On that result I will do some functionality and then come back to contact listing screen that time my contact list reset automatically.
Below is the code of filter
public class ValueFilter extends Filter {
ContactsAdapter adapter;
private ArrayList<HashMap<String, Object>> mfilterList;
public ValueFilter(ArrayList<HashMap<String, Object>> filterList, ContactsAdapter adapter) {
this.adapter = adapter;
this.mfilterList = filterList;
}
//Invoked in a worker thread to filter the data according to the constraint.
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<HashMap<String, Object>> filterListbk = new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < mfilterList.size(); i++) {
String contactName = (String) mfilterList.get(i).get(Contacts.CONTACTKEY);
String contactNo = (String) mfilterList.get(i).get(Contacts.DURATION);
contactName = contactName.toLowerCase();
constraint = (CharSequence) constraint.toString().toLowerCase();
if (contactName.contains(constraint)) {
filterListbk.add(mfilterList.get(i));
}
if (contactNo.contains(constraint)) {
filterListbk.add(mfilterList.get(i));
}
results.count = filterListbk.size();
results.values = filterListbk;
}
} else {
results.count = mfilterList.size();
results.values = mfilterList;
}
return results;
}
//Invoked in the UI thread to publish the filtering results in the user interface.
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
// adapter.players= (ArrayList<Player>) results.values;
adapter.Books = (ArrayList<HashMap<String, Object>>) results.values;
String new_result = results.values.toString();
if(!new_result.equals(null)){
adapter.Books = (ArrayList<HashMap<String, Object>>) results.values;
adapter.notifyDataSetChanged();
Intent intent = new Intent();
intent.setAction(SipManager.ACTION_NO_RECORD_FOUND);
Bundle args = new Bundle();
args.putSerializable("result",(Serializable)adapter.Books);
args.putSerializable("flag","0");
intent.putExtra("BUNDLE",args);
/*intent.putExtra("flag","0");
intent.putExtra("result",adapter.Books);*/
// add data
ctx.sendBroadcast(intent);
}
if(new_result.equals("[]")){
Intent intent = new Intent();
intent.setAction(SipManager.ACTION_NO_RECORD_FOUND);
//intent.putExtra("flag","1");
Bundle args = new Bundle();
args.putSerializable("result",(Serializable)adapter.Books);
args.putSerializable("flag","1");
intent.putExtra("BUNDLE",args);
ctx.sendBroadcast(intent);
}
//adapter.Books.clear();
notifyDataSetChanged();
}
}
Below is the code of my fragment
public class Contacts extends Fragment implements OnBackPressListener {
IndexFastScrollRecyclerView mRecyclerView;
private List<String> mDataArray;
public static boolean isVisible = false;
ContactsAdapter adapter;
DatabaseHelper dbHelp;
public static final String CONTACTID = "contactid";
public static final String CONTACTKEY = "contactname";
public static final String CONTACTFAV = "contactfav";
public static final String CONTACTNUM = "contactno";
public static final String DURATION = "duration";
public static final String SIP = "sip";
public static final String SIP_USER = "sip_user";
public String sip_label = "";//"Aniphones";
public String not_sip_label = "";
public int flag = 0;
public Cursor cursor;
public ArrayList<HashMap<String, Object>> myBooks;
public ArrayList<HashMap<String, Object>> myBooks1;
public ArrayList<String> ContactSimpleList;
public HashMap<String, Object> hm;
public Long id;
public String getname = "";
public DatabaseHelper dbhelp;
public SharedPreferences.Editor edit;
public TextView no_contacts;
public String contact = "";
public Phonenumber.PhoneNumber number = null;
public PhoneNumberUtil phoneUtil;
public String dynamic_table = "";
FloatingActionButton fab;
String test = "", sip_user_pref = "";
Context ctx;
String service_start;
private TextWatcher mSearchTw;
private EditText etAllContSearch;
View rootView;
public String name = "", balance = "";
public static final int PREMISSION_CONTACT_REQUEST_CODE = 1;
private Background_allcontacts mBackground_allcontacts = null;
AlertDialog spotDialog = null;
private List<AlphabetItem> mAlphabetItems;
PrefManager pref;
HashMap<String, String> credential;
GlobalClass gc;
ViewPager viewPager;
boolean isCallPlaced = true;
Object selectedItem;
boolean is_called_from_filter = false;
public ArrayList<HashMap<String, Object>> filterBook;
private BroadcastReceiver mNoRecordFound = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
if (intent.getAction().equals(SipManager.ACTION_NO_RECORD_FOUND)) {
Bundle args = intent.getBundleExtra("BUNDLE");
String flag = args.getString("flag");
//String flag = intent.getExtras().getString("flag");
if(flag.equals("1")){
no_contacts.setVisibility(View.VISIBLE);
}
else {
is_called_from_filter = true;
ArrayList<HashMap<String, Object>> object = (ArrayList<HashMap<String, Object>>) args.getSerializable("result");
filterBook = object;
no_contacts.setVisibility(View.INVISIBLE);
}
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
Fabric.with(getActivity(), new Crashlytics());
getActivity().invalidateOptionsMenu();
rootView = inflater.inflate(R.layout.contact_tab, container,
false);
ctx = getContext();
pref = new PrefManager(getActivity());
mRecyclerView = (IndexFastScrollRecyclerView) rootView.findViewById(R.id.fast_scroller_recycler);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
mLayoutManager = new MyCustomLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.smoothScrollToPosition(0);
gc = GlobalClass.getInstance();
no_contacts = (TextView) rootView.findViewById(R.id.no_contacts);
spotDialog = new SpotsDialog(ctx, R.style.CustomSpotDialog);
ctx = getContext();
dbhelp = new DatabaseHelper(ctx);
initialiseData();
initialiseUI();
etAllContSearch = (EditText) rootView.findViewById(R.id.etAllContSearch);
etAllContSearch.requestFocus();
etAllContSearch.setOnTouchListener(Contacts.this);
etAllContSearch.setCompoundDrawablesWithIntrinsicBounds(R.drawable.search_icon, 0, 0, 0);
mSearchTw = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (etAllContSearch.getText().toString().trim().length() > 0) {
etAllContSearch.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.closesicon, 0);
mRecyclerView.setIndexBarVisibility(true);
} else {
etAllContSearch.setCompoundDrawablesWithIntrinsicBounds(R.drawable.search_icon, 0, 0, 0);
mRecyclerView.setIndexBarVisibility(false);
}
if (adapter != null) {
//if (!adapter.isEmpty()) {
System.out.println("Test: Result do in search " + s);
adapter.getFilter().filter(s);
mRecyclerView.setIndexBarVisibility(true);
//}
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (etAllContSearch.getText().toString().length() == 0 || etAllContSearch.getText().toString() == "") {
mRecyclerView.setIndexBarVisibility(true);
} else {
mRecyclerView.setIndexBarVisibility(false);
}
}
#Override
public void afterTextChanged(Editable s) {
if (etAllContSearch.getText().toString().length() == 0 || etAllContSearch.getText().toString() == "") {
mRecyclerView.setIndexBarVisibility(true);
} else {
mRecyclerView.setIndexBarVisibility(false);
}
}
};
myBooks = new ArrayList<HashMap<String, Object>>();
myBooks1 = new ArrayList<HashMap<String, Object>>();
ContactSimpleList = new ArrayList<String>();
service_start = PreferenceManager.getDefaultSharedPreferences(ctx).getString(Settings.PREF_SERVICE_START + "", Settings.DEFAULT_SERVICE_START);
Log.d(TAG, "contact_sync service flag" + service_start);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkPermission()) {
Log.d(TAG, "inside check permission" + service_start);
if (service_start.equals("0")) {
no_contacts.setVisibility(View.VISIBLE);
no_contacts.setText(getResources().getString(R.string.synchronize_contacts));
} else {
// hideDialog();
no_contacts.setVisibility(View.GONE);
System.out.println("Test: Result oncreate ");
if (mBackground_allcontacts == null) {
mBackground_allcontacts = new Background_allcontacts();
mBackground_allcontacts.execute();
}
}
} else {
requestPermission();
}
} else {
Log.d(TAG, "else " + service_start);
if (service_start.equals("0")) {
no_contacts.setVisibility(View.VISIBLE);
no_contacts.setText(getResources().getString(R.string.synchronize_contacts));
} else {
// hideDialog();
no_contacts.setVisibility(View.GONE);
if (mBackground_allcontacts == null) {
mBackground_allcontacts = new Background_allcontacts();
mBackground_allcontacts.execute();
}
}
}
etAllContSearch.addTextChangedListener(mSearchTw);
IntentFilter iFilter_NorecordFound = new IntentFilter(SipManager.ACTION_NO_RECORD_FOUND);
getActivity().registerReceiver(mNoRecordFound, iFilter_NorecordFound);
return rootView;
}
protected void initialiseData() {
//Recycler view data
mDataArray = DataHelper.getAlphabetData();
//Alphabet fast scroller data
mAlphabetItems = new ArrayList<>();
List<String> strAlphabets = new ArrayList<>();
for (int i = 0; i < mDataArray.size(); i++) {
String name = mDataArray.get(i);
if (name == null || name.trim().isEmpty())
continue;
String word = name.substring(0, 1);
if (!strAlphabets.contains(word)) {
strAlphabets.add(word);
mAlphabetItems.add(new AlphabetItem(i, word, false));
// mAlphabetItems.add(new AlphabetItem(i, word, false));
}
mRecyclerView.smoothScrollToPosition(i);
}
}
protected void initialiseUI() {
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.setIndexTextSize(12);
mRecyclerView.setIndexBarColor("#FFFFFF");
mRecyclerView.setIndexBarCornerRadius(0);
mRecyclerView.setIndexBarTransparentValue((float) 0.4);
mRecyclerView.setIndexbarMargin(0);
mRecyclerView.setIndexbarWidth(30);
mRecyclerView.setPreviewPadding(0);
mRecyclerView.setIndexBarTextColor("#2d4278");
mRecyclerView.setIndexBarVisibility(true);
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_CONTACTS);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_CONTACTS) && ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_CONTACTS)) {
Toast.makeText(getActivity(), "Until you grant the permission, we canot display the contacts.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS}, Contacts.PREMISSION_CONTACT_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case Contacts.PREMISSION_CONTACT_REQUEST_CODE:
if (grantResults.length > 0) {
// Contacts permission
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (service_start.equals("0")) {
Toast.makeText(getActivity(), getResources().getString(R.string.synchronize_contacts), Toast.LENGTH_SHORT).show();
} else {
new Background_allcontacts().execute();
}
} else {
Toast.makeText(getActivity(), "Until you grant the permission, we canot display the contacts.", Toast.LENGTH_LONG).show();
}
}
break;
}
}
public void nodata() {
// TODO Auto-generated method stub
no_contacts.setText(getString(R.string.no_sip_contacts));
no_contacts.setVisibility(View.VISIBLE);
mRecyclerView.setVisibility(View.GONE);
}
#Override
public void onActivityCreated(#Nullable Bundle outState) {
super.onActivityCreated(outState);
if (adapter != null) {
adapter.saveStates(outState);
}
}
#Override
public void onViewStateRestored(#Nullable Bundle inState) {
super.onViewStateRestored(inState);
if (adapter != null) {
adapter.restoreStates(inState);
}
}
#Override
public void onResume() {
super.onResume();
isCallPlaced = true;
pref.set_is_ongoing_call_flag(false);
mRecyclerView.setVisibility(View.VISIBLE);
getActivity().invalidateOptionsMenu();
System.out.println("Test: Result onresume ");
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
if (isVisibleToUser && this.isVisible()) {
viewPager = (ViewPager) getActivity().findViewById(R.id.viewpager);
if (viewPager.getCurrentItem() == 1) {
gc.hideKeypad(getActivity());
spotDialog.hide();
if (adapter != null) {
adapter.getFilter().filter(etAllContSearch.getText().toString());
mRecyclerView.setIndexBarVisibility(true);
}
}
}
super.setUserVisibleHint(isVisibleToUser);
}
#Override
public boolean onBackPressed() {
return new BackPressImpl(this).onBackPressed();
}
public void getdata() {
if (mBackground_allcontacts == null) {
mBackground_allcontacts = new Background_allcontacts();
mBackground_allcontacts.execute();
}
}
public void getdata(String from, String value) {
if (mBackground_allcontacts == null) {
mBackground_allcontacts = new Background_allcontacts(from, value);
mBackground_allcontacts.execute();
}
}
//Himadri
//Unregister all receiver when view destroy
#Override
public void onDestroyView() {
try {
//Here is the code for stopping some service
} catch (Exception e) {
e.printStackTrace();
}
super.onDestroyView();
}
public class Background_allcontacts extends AsyncTask<Void, Integer, Void> {
String from;
String value;
public Background_allcontacts() {
}
public Background_allcontacts(String from, String value) {
// TODO Auto-generated constructor stub
this.from = from;
this.value = value;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
// showDialog();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
String dynamic_table = PreferenceManager.getDefaultSharedPreferences(ctx).getString(Settings.PREF_DYNAMIC_TABLE + "", Settings.DEFAULT_DYNAMIC_TABLE);
if (dynamic_table != null) {
if (!dynamic_table.equals(Settings.DEFAULT_DYNAMIC_TABLE)) {
cursor = dbhelp.fetchcalllog("select contact_id,contact_name,contact_num, fav,contactImage from '" + dynamic_table + "' order by UPPER(contact_name)");
}
}
return null;
}
// #SuppressLint("NewApi")
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
try {
ContactSimpleList = new ArrayList<String>();
if (cursor != null) {
if (cursor.getCount() == 0) {
nodata();
} else if (cursor.getCount() > 0) {
no_contacts.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
etAllContSearch.setVisibility(View.VISIBLE);
test = PreferenceManager.getDefaultSharedPreferences(getActivity()).getString(Settings.PREF_SIPARRAY + "", Settings.DEFAULT_SIPARRAY);
sip_user_pref = PreferenceManager.getDefaultSharedPreferences(getActivity()).getString(Settings.PREF_SIPUSERARRAY + "", Settings.DEFAULT_SIPARRAY);
String[] separated = null, sipUser = null;
if (test != null && test.length() != 0) {
if (test.charAt(test.length() - 1) == ',') {
test = test.substring(0, test.length() - 1);
} else if (sip_user_pref.charAt(sip_user_pref.length() - 1) == ',') {
sip_user_pref = sip_user_pref.substring(0, sip_user_pref.length() - 1);
}
// Log.v("sip contacts",test);
if (test.contains(",")) {
separated = test.split(",");
sipUser = sip_user_pref.split(",");
}
}
myBooks.clear();
// cursor.moveToFirst();
while (cursor.moveToNext()) {
String id = "", name = "", phoneNumber = "", phoneFav = "", contactImg = "";
try {
id = cursor.getString(0);
name = cursor.getString(1);
phoneNumber = cursor.getString(2);
phoneFav = cursor.getString(3);
contactImg = cursor.getString(4);
} catch (Exception e) {
e.printStackTrace();
}
phoneNumber = phoneNumber.replaceAll("\\D", "");
if (test.contains(",")) {
for (int j = 0; j < separated.length; j++) {
if (Arrays.asList(separated).contains(phoneNumber)) {
if (separated[j].equals(phoneNumber)) {
hm = new HashMap<String, Object>();
hm.put(CONTACTID, id);
hm.put(CONTACTKEY, name);
hm.put(DURATION, phoneNumber);
hm.put(CONTACTFAV, phoneFav);
hm.put("contactImage", contactImg);
hm.put(SIP, sip_label);
hm.put(SIP_USER, sipUser[j]);
myBooks.add(hm);
myBooks1.add(hm);
ContactSimpleList.add(phoneNumber);
}
} else {
hm = new HashMap<String, Object>();
hm.put(CONTACTID, id);
hm.put(CONTACTKEY, name);
hm.put(DURATION, phoneNumber);
hm.put(CONTACTFAV, phoneFav);
hm.put("contactImage", contactImg);
hm.put(SIP, not_sip_label);
hm.put(SIP_USER, "");
myBooks.add(hm);
myBooks1.add(hm);
ContactSimpleList.add(phoneNumber);
}
}
} else {
if (Arrays.asList(test).contains(phoneNumber)) {
hm = new HashMap<String, Object>();
hm.put(CONTACTID, id);
hm.put(CONTACTKEY, name);
hm.put(DURATION, phoneNumber);
hm.put(CONTACTFAV, phoneFav);
hm.put("contactImage", contactImg);
hm.put(SIP, sip_label);
hm.put(SIP_USER, sip_user_pref);
myBooks.add(hm);
myBooks1.add(hm);
ContactSimpleList.add(phoneNumber);
} else {
hm = new HashMap<String, Object>();
hm.put(CONTACTID, id);
hm.put(CONTACTKEY, name);
hm.put(DURATION, phoneNumber);
hm.put(CONTACTFAV, phoneFav);
hm.put("contactImage", contactImg);
hm.put(SIP, not_sip_label);
hm.put(SIP_USER, "");
myBooks.add(hm);
myBooks1.add(hm);
ContactSimpleList.add(phoneNumber);
}
}
}
}
Set<HashMap<String, Object>> unique = new LinkedHashSet<HashMap<String, Object>>(myBooks);
myBooks = new ArrayList<HashMap<String, Object>>(unique);
Set<String> unique1 = new LinkedHashSet<String>(ContactSimpleList);
ContactSimpleList = new ArrayList<String>(unique1);
gc.setContactsList(ctx, myBooks);
gc.setContactListSimpleNum(ctx, ContactSimpleList);
adapter = new ContactsAdapter(myBooks, getActivity(), "ALL_CONTACT", mDataArray, false);
mRecyclerView.setAdapter(adapter);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
mBackground_allcontacts = null;
}
super.onPostExecute(result);
}
}
}
How to do the Filter concept from Below design? I here by attached two screen designs.
DashBoard Fragment -> Having Listview with Base adapter.
The above ListView code is given Below
DashBoardRefactor
public class DashBoardRefactor extends Fragment {
public static ProgressDialog progress;
public static List<DashListModel> dashRowList1 = new ArrayList<DashListModel>();
public static View footerView;
// #Bind(R.id.dashListView)
public static ListView dashListView;
int preCount = 2, scroll_Inc = 10, lastCount;
boolean flag = true;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dashboard_fragment, container, false);
ButterKnife.bind(this, v);
setHasOptionsMenu(true);
progress = new ProgressDialog(getActivity());
dashListView = (ListView) v.findViewById(R.id.dashListView);
footerView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dashboard_list_footer, null, false);
dashListView.addFooterView(footerView);
footerView.setVisibility(View.GONE);
dashRowList1.clear();
dashboardViewTask();
dashListView.setOnScrollListener(new EndlessScrollListener(getActivity(), dashListView, footerView));
return v;
}
public void dashboardViewTask() {
progress.setMessage("Loading...");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
progress.show();
// footerView.setVisibility(View.VISIBLE);
Map<String, String> params = new HashMap<String, String>();
Log.e("candidate_id", "candidate_id---->" + SessionStores.getBullHornId(getActivity()));
params.put("candidate_id", SessionStores.getBullHornId(getActivity()));
params.put("employmentPreference", SessionStores.getEmploymentPreference(getActivity()));
params.put("page", "1");
new DashBoardTask(getActivity(), params, dashListView, footerView);
}
#Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
if (menu != null) {
menu.removeItem(R.id.menu_notify);
}
inflater.inflate(R.menu.menu_options, menu);
MenuItem item = menu.findItem(R.id.menu_filter);
item.setVisible(true);
getActivity().invalidateOptionsMenu();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.his__menu_accept:
Toast.makeText(getActivity(), "clicked dashboard menu accept", Toast.LENGTH_LONG).show();
return true;
case R.id.menu_filter:
// click evnt for filter
Toast.makeText(getActivity(), "clicked dashboard filter", Toast.LENGTH_LONG).show();
Intent filter_intent = new Intent(getActivity(), DashBoardFilterScreen.class);
startActivity(filter_intent);
getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onPause() {
super.onPause();
// dashboardViewTask();
}
}
DashBoardTask:
public class DashBoardTask {
public static String candidateIdNo;
public static Integer isBookmarked;
public ListAdapter dashListAdapter;
ListView dashListView;
View footerView;
String fromdate_formated = "";
String todate_formated = "";
private Context context;
private JSONObject jObject = null;
private String result, authorizationKey;
private Map<String, String> params;
public DashBoardTask(Context context, Map<String, String> params, ListView dashListView, View footerView) {
this.context = context;
Log.e("context ", "DashBoardTask: " + context);
this.dashListView = dashListView;
Dashboard.dashRowList.clear();
this.params = params;
this.footerView = footerView;
ResponseTask();
}
private void ResponseTask() {
authorizationKey = Constants.ACCESS_TOKEN;
new ServerResponse(ApiClass.getApiUrl(Constants.DASHBOARD_VIEW)).getJSONObjectfromURL(ServerResponse.RequestType.POST, params, authorizationKey, context, "", new VolleyResponseListener() {
#Override
public void onError(String message) {
if (DashBoardRefactor.progress.isShowing()) {
DashBoardRefactor.progress.dismiss();
}
}
#Override
public void onResponse(String response) {
String dateEnd = "", startDate = "";
result = response.toString();
try {
jObject = new JSONObject(result);
if (jObject != null) {
Integer totalJobList = jObject.getInt("page_count");
Integer total = jObject.getInt("total");
Integer count = jObject.getInt("count");
Integer start = jObject.getInt("start");
if (footerView.isShown() && count == 0) {
footerView.setVisibility(View.GONE);
}
Integer Status = jObject.getInt("status");
if (Status == 1) {
SessionStores.savetotalJobList(totalJobList, context);
JSONArray dataObject = jObject.getJSONArray("data");
Dashboard.dashRowList.clear();
for (int i = 0; i < dataObject.length(); i++) {
Log.e("length", "lenght----->" + dataObject.length());
JSONObject jobDetail = dataObject.getJSONObject(i);
Log.e("jobDetail", "jobDetail----->" + jobDetail);
Integer goalsName = jobDetail.getInt("id");
String compnyTitle = jobDetail.getString("title");
String description = jobDetail.getString("description");
Integer salary = jobDetail.getInt("salary");
String dateAdded = jobDetail.getString("dateAdded");
if (jobDetail.getString("startDate") != null && !jobDetail.getString("startDate").isEmpty() && !jobDetail.getString("startDate").equals("null")) {
startDate = jobDetail.getString("startDate");
} else {
Log.e("Task Null", "Task Null----startDate->");
}
if (jobDetail.getString("dateEnd") != null && !jobDetail.getString("dateEnd").isEmpty() && !jobDetail.getString("dateEnd").equals("null")) {
dateEnd = jobDetail.getString("dateEnd");
} else {
Log.e("Task Null", "Task Null----->");
}
isBookmarked = jobDetail.getInt("isBookmarked");
Integer startSalary = jobDetail.getInt("customFloat1");
Integer endSalary = jobDetail.getInt("customFloat2");
JSONObject cmpanyName = jobDetail.getJSONObject("clientCorporation");
String compnyNamede = cmpanyName.getString("name");
String city = jobDetail.getString("customText1");
JSONObject candidateId = jobDetail.getJSONObject("clientContact");
candidateIdNo = candidateId.getString("id");
DashListModel dashListItem = new DashListModel();
dashListItem.setDashCompanyName(compnyNamede);
dashListItem.setDashJobDescription(description);
dashListItem.setDashJobPosition(compnyTitle);
dashListItem.setDashJobCity(city);
// dashListItem.setDashJobState(state);
dashListItem.setDashSalary(startSalary.toString());
dashListItem.setDashJobAvailableDate(dateAdded);
dashListItem.setDashId(goalsName.toString());
dashListItem.setDashIsBookMarked(isBookmarked.toString());
dashListItem.setDashEndSalary(endSalary.toString());
dashListItem.setToDate(dateEnd);
////////////////////////////////////
String fromDate = null, toDate = null, postedDate = null;
if (startDate.length() > 11) {
Log.e("11", "11---->");
fromDate = Utils.convertFromUnixDateAdded(startDate);
} else if (startDate.length() == 10) {
Log.e("10", "10----->");
fromDate = Utils.convertFromUnix(startDate);
}
if (dateEnd.length() > 11) {
Log.e("11", "11---->");
toDate = Utils.convertFromUnixDateAdded(dateEnd);
} else if (dateEnd.length() == 10) {
Log.e("10", "10----->");
toDate = Utils.convertFromUnix(dateEnd);
}
if (dateAdded.length() > 11) {
Log.e("11", "11---->");
postedDate = Utils.convertFromUnixDateAdded(dateAdded);
} else if (dateAdded.length() == 10) {
Log.e("10", "10----->");
postedDate = Utils.convertFromUnix(dateAdded);
}
try {
if (!fromDate.isEmpty() || !fromDate.equalsIgnoreCase("null")) {
String[] fromDateSplit = fromDate.split("/");
String fromMonth = fromDateSplit[0];
String fromDat = fromDateSplit[1];
String fromYear = fromDateSplit[2];
String fromMonthName = new DateFormatSymbols().getMonths()[Integer.parseInt(fromMonth) - 1];
fromdate_formated = fromMonthName.substring(0, 3) + " " + fromDat + getDayOfMonthSuffix(Integer.parseInt(fromDat));
Log.e("fromdate", "fromdate---->" + fromDate);
Log.e("toDate", "toDate---->" + toDate);
Log.e("fromMonth", "fromMonth---->" + fromMonth);
Log.e("fromDat", "fromDat---->" + fromDat);
Log.e("fromYear", "fromYear---->" + fromYear);
}
if (!toDate.isEmpty() || !toDate.equalsIgnoreCase("null")) {
String[] toDateSplit = toDate.split("/");
String toMonth = toDateSplit[0];
String toDat = toDateSplit[1];
String toYear = toDateSplit[2];
String toMonthName = new DateFormatSymbols().getMonths()[Integer.parseInt(toMonth) - 1];
todate_formated = toMonthName.substring(0, 3) + " " + toDat + getDayOfMonthSuffix(Integer.parseInt(toDat)) + " " + toYear;
Log.e("________________", "-------------------->");
Log.e("toMonth", "toMonth---->" + toMonth);
Log.e("toDat", "toDat---->" + toDat);
Log.e("toYear", "toYear---->" + toYear);
Log.e("________________", "-------------------->");
Log.e("toMonthName", "toMonthName---->" + toMonthName);
}
} catch (Exception e) {
e.printStackTrace();
}
dashListItem.setPostedDate(postedDate);
dashListItem.setFromDate(fromdate_formated);
dashListItem.setEndDate(todate_formated);
/////////////////////////////////////////
// Dashboard.dashRowList.add(dashListItem);
DashBoardRefactor.dashRowList1.add(dashListItem);
}
// get listview current position - used to maintain scroll position
int currentPosition = dashListView.getFirstVisiblePosition();
dashListAdapter = new DashListAdapter(context, DashBoardRefactor.dashRowList1, dashListView);
dashListView.setAdapter(dashListAdapter);
((BaseAdapter) dashListAdapter).notifyDataSetChanged();
if (currentPosition != 0) {
// Setting new scroll position
dashListView.setSelectionFromTop(currentPosition + 1, 0);
}
} else if (Status==0 && count==0 && start==0){
String Message = jObject.getString("message");
Utils.ShowAlert(context, Message);
}
if (footerView.isShown()) {
footerView.setVisibility(View.GONE);
}
//progress.dismiss();
if (DashBoardRefactor.progress.isShowing()) {
try {
DashBoardRefactor.progress.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
}
DashListModel:
public class DashListModel {
private String dashCompanyName;
private String dashJobPosition;
private String dashJobPostedDate;
private String dashJobDescription;
private String dashSalary;
private String dashJobCity;
private String dashJobState;
private String dashJobAvailableDate;
private String dashId, dashIsBookmarked;
private String dashEndSalary;
private String toDate;
private String postedDate, fromdate, enddate;
public String getDashCompanyName() {
return dashCompanyName;
}
public void setDashCompanyName(String dashCompanyName) {
this.dashCompanyName = dashCompanyName;
}
public String getDashJobPosition() {
return dashJobPosition;
}
public void setDashJobPosition(String dashJobPosition) {
this.dashJobPosition = dashJobPosition;
}
public String getDashJobDescription() {
return dashJobDescription;
}
public void setDashJobDescription(String dashJobDescription) {
this.dashJobDescription = dashJobDescription;
}
public String getDashJobPostedDate() {
return dashJobPostedDate;
}
public void setDashJobPostedDate(String dashJobPostedDate) {
this.dashJobPostedDate = dashJobPostedDate;
}
public String getDashSalary() {
return dashSalary;
}
public void setDashSalary(String dashSalary) {
this.dashSalary = dashSalary;
}
public String getDashJobCity() {
return dashJobCity;
}
public void setDashJobCity(String dashJobCity) {
this.dashJobCity = dashJobCity;
}
/* public String getDashJobState() {
return dashJobState;
}
public void setDashJobState(String dashJobState) {
this.dashJobState = dashJobState;
}*/
public String getDashJobAvailableDate() {
return dashJobAvailableDate;
}
public void setDashJobAvailableDate(String dashJobAvailableDate) {
this.dashJobAvailableDate = dashJobAvailableDate;
}
public String getDashId() {
return dashId;
}
public void setDashId(String dashId) {
this.dashId = dashId;
}
public String getDashIsBookmarked() {
return dashIsBookmarked;
}
public void setDashIsBookMarked(String dashIsBookmarked) {
this.dashIsBookmarked = dashIsBookmarked;
}
public String getDashEndSalary() {
return dashEndSalary;
}
public void setDashEndSalary(String dashEndSalary) {
this.dashEndSalary = dashEndSalary;
}
public String getToDate() {
return toDate;
}
public void setToDate(String toDate) {
this.toDate = toDate;
}
public String getPostedDate() {
return postedDate;
}
public void setPostedDate(String postedDate) {
this.postedDate = postedDate;
}
public String getFromDate() {
return fromdate;
}
public void setFromDate(String fromdate) {
this.fromdate = fromdate;
}
public String getEndDate() {
return enddate;
}
public void setEndDate(String enddate) {
this.enddate = enddate;
}
DashListAdapter:
package com.peoplecaddie.adapter;
public class DashListAdapter extends BaseAdapter {
public static ListView dashListView;
Context c;
private LayoutInflater inflater;
private List<DashListModel> dashRowList;
public DashListAdapter(Context c, List<DashListModel> dashRowList, ListView dashListView) {
this.c = c;
this.dashListView = dashListView;
this.dashRowList = dashRowList;
}
#Override
public int getCount() {
return this.dashRowList.size();
}
#Override
public Object getItem(int position) {
return dashRowList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder dashHolder;
if (inflater == null)
inflater = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.dashboard_jobdetails_list, null);
final DashListModel dashModel = dashRowList.get(position);
dashHolder = new ViewHolder(convertView);
dashHolder.dash_company_name.setText(dashModel.getDashCompanyName());
dashHolder.dash_position_name.setText(dashModel.getDashJobPosition());
dashHolder.dash_posted_date.setText(dashModel.getPostedDate());
dashHolder.dash_job_description.setText(Utils.stripHtml(dashModel.getDashJobDescription()));
dashHolder.dash_salary.setText(dashModel.getDashSalary() + " - " + dashModel.getDashEndSalary());
dashHolder.dash_available_date.setText(dashModel.getFromDate() + " - " + dashModel.getEndDate());
dashHolder.book_jobCity.setText(dashModel.getDashJobCity());
if (dashModel.getDashIsBookmarked().equalsIgnoreCase("1")) {
dashHolder.bookmark_img.setImageResource(R.drawable.bookmark);
} else if (dashModel.getDashIsBookmarked().equalsIgnoreCase("0")) {
dashHolder.bookmark_img.setImageResource(R.drawable.blue_tag_img);
}
dashHolder.bookmark_img.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (dashModel.getDashIsBookmarked().equalsIgnoreCase("0")) {
dashModel.setDashIsBookMarked("1");
Map<String, String> params = new HashMap<String, String>();
params.put("candidate_id", SessionStores.getBullHornId(c));
params.put("joborder_id", dashModel.getDashId());
BackGroundTasks bookmark_add_bg_tasks = new BackGroundTasks(c, new JSONObject(params), Constants.BOOKMARK_ADD_TAG);
bookmark_add_bg_tasks.ResponseTask(new BackGroundTasks.VolleyCallbackOnEdit() {
#Override
public void onSuccess(String result) {
String resp_resultsd = result;
Log.e("insidecallback", " bookmark_add_bg_tasks----->" + resp_resultsd);
// finish();
dashHolder.bookmark_img.setImageResource(R.drawable.bookmark);
notifyDataSetChanged();
}
});
} else if (dashModel.getDashIsBookmarked().equalsIgnoreCase("1")) {
dashModel.setDashIsBookMarked("0");
Log.e("imgchange", " imgchange");
Map<String, String> params = new HashMap<String, String>();
params.put("candidate_id", SessionStores.getBullHornId(c));
params.put("joborder_id", dashModel.getDashId());
BackGroundTasks bookmark_delete_bg_tasks = new BackGroundTasks(c, new JSONObject(params), Constants.BOOKMARK_DELETE_TAG);
bookmark_delete_bg_tasks.ResponseTask(new BackGroundTasks.VolleyCallbackOnEdit() {
#Override
public void onSuccess(String result) {
String resp_resultsd = result;
Log.e("insidecallback", " bookmark_delete_bg_tasks----->" + resp_resultsd);
// finish();
dashHolder.bookmark_img.setImageResource(R.drawable.blue_tag_img);
notifyDataSetChanged();
}
});
}
}
});
return convertView;
}
static class ViewHolder {
#Bind(R.id.book_company_name)
TextView dash_company_name;
private RelativeLayout.LayoutParams viewLayParams;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
Clarification:
How do to Filter while click the Filter Button On DashBoard Fragment. Please Suggest the way. I here by attached My Filter design also.
Dashboard Fragment--> Filter Button-> Filter screen-> the Filtered results should view on DashBoard Fragment.
Once click the apply Button Based on the input from Filter screen it filters the list view the result comes from back end team. I have to display that result on Dashboard Fragment.
Kindly please clarify this Filter concept.
In this code I have a custom adapter, and after I add new data into ArrayList my adapter.notifyDataSetChanged(); doesn't work.
public class ReceiveListFragment extends ListFragment implements AbsListView.OnScrollListener {
public ArrayList<ReceivedItemStructure> items;
private int prevVisibleItem;
private boolean isFirstTime;
private DatabaseHandler db;
private String config_username;
private String config_password;
private ReceivedAdapter adapter;
private Cursor cursor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
db = new DatabaseHandler(G.context);
config_username = Configuration.getInstance()
.getString(getActivity(),
Configuration.SharedPrefsTypes.USERNAME);
config_password = Configuration.getInstance()
.getString(getActivity(),
Configuration.SharedPrefsTypes.PASSWORD);
items = new ArrayList<ReceivedItemStructure>();
getRequestFromServer(0, 10);
adapter = new ReceivedAdapter(G.context, items);
setListAdapter(adapter);
Timer smsThread = new Timer();
GetSMSThread getSMSThread = new GetSMSThread();
smsThread.scheduleAtFixedRate(getSMSThread, 1, 10000); //(timertask,delay,period)
return super.onCreateView(inflater, container, savedInstanceState);
}
private String getRequestFromServer(long lastID, int count) {
String received = "";
try {
received = new JsonService(config_username, config_password, lastID, count, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(received);
String mUserID = config_username;
for (int i = 0; i < data_array.length(); i++) {
JSONObject json_obj = data_array.getJSONObject(i);
String mLastID = json_obj.getString("id_recived_sms");
String mSmsBody = json_obj.getString("sms_body");
String mSmsNumber = json_obj.getString("sms_number");
String mSenderName = json_obj.getString("mobile_number");
String mContactName = json_obj.getString("contact_name");
String mDate = json_obj.getString("recived_date");
ReceivedItemStructure item = new ReceivedItemStructure(
mLastID,
mUserID,
mSmsBody,
mSmsNumber,
mSenderName,
mContactName,
mDate
);
items.add(item);
//Log.e(" ", "" + mLastID);
}
/** Creating array adapter to set data in listview */
} catch (Exception e) {
e.printStackTrace();
}
return received;
}
public long getLastID() {
return Long.parseLong(items.get(items.size() - 1).getmLastID());
}
private void addDataToList(String LastID, String SmsBody, String SmsNumber, String SenderName, String ContactName, String Date) {
String mLastID = LastID;
String mUserID = config_username;
String mSmsBody = SmsBody;
String mSmsNumber = SmsNumber;
String mSenderName = SenderName;
String mContactName = ContactName;
String mDate = Date;
ReceivedItemStructure item = new ReceivedItemStructure(
mLastID,
mUserID,
mSmsBody,
mSmsNumber,
mSenderName,
mContactName,
mDate
);
items.add(item);
adapter.update(items);
adapter.notifyDataSetChanged();
}
public class GetSMSThread extends TimerTask {
private Long lastID;
private SQLiteDatabase dbHelper;
private List<ReceiveListFragment> rows;
#Override
public void run() {
lastID = getLastID();
if (Configuration.getInstance().checkInternetConnection(G.context)) {
try {
Thread threadTask = new Thread() {
#Override
public void run() {
G.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
int countSMS = 0;
String smsReceivedSender = "";
String receive_lastID = "";
String r = new JsonService(config_username, config_password, 0, 1, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(r);
ArrayList<String> items_array = new ArrayList<String>();
JSONObject json_obj = data_array.getJSONObject(0);
receive_lastID = json_obj.getString("id_recived_sms");
smsReceivedSender = json_obj.getString("mobile_number");
for (ReceivedItemStructure rf : items) {
items_array.add(rf.getmLastID());
}
if (items_array.indexOf(receive_lastID) == -1) {
countSMS++;
addDataToList(
json_obj.getString("id_recived_sms"),
json_obj.getString("sms_body"),
json_obj.getString("sms_number"),
json_obj.getString("mobile_number"),
json_obj.getString("contact_name"),
json_obj.getString("recived_date")
);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
threadTask.start();
} catch (Exception e) {
e.printStackTrace();
} // END TRY
}
}
}
}
My custom Adapter code is this:
public class ReceivedAdapter extends ArrayAdapter<ReceivedItemStructure> {
private ArrayList<ReceivedItemStructure> list;
public ReceivedAdapter(Context c, ArrayList<ReceivedItemStructure> items) {
super(c,0,items);
list = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ReceiveItemView itemView = (ReceiveItemView)convertView;
if (null == itemView)
itemView = ReceiveItemView.inflate(parent);
itemView.setItem(getItem(position));
return itemView;
}
public void update(ArrayList<ReceivedItemStructure> items) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
addAll(items);
} else {
for (ReceivedItemStructure item : items) {
add(item);
}
}
}
}
setListAdapter(adapter); works correctly and I don't have any problem, but after I add new data into items notifyDataSetChanged it doesn't work.
My manifest content:
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21"/>
it is the super class that is handling the dataset, since you are not overriding getCount and getItem,
public void update(ArrayList<ReceivedItemStructure> items) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
addAll(items);
} else {
for (ReceivedItemStructure item : items) {
add(item)
}
}
}
addAll was introduced with Honeycomb, so you probably want to check the current supported sdk where you are app is running
You are modifying your original items collection. But you should to modify adapter's data. Use ArrayAdapter.add method to add new items.
I am expirience wierd situation because my list view updates only once.
The idia is following, i want to download posts from web, which are located on page 3 and page 5 and show both of them on listview. However, List view shows posts only from page 3. MEanwhile, log shows that all poast are downloded and stored in addList.
So the problem - objects from second itteration are not shown in listview. Help me please to fix this issue.
public class MyAddActivateActivity extends ErrorActivity implements
AddActivateInterface {
// All static variables
// XML node keys
View footer;
public static final String KEY_ID = "not_id";
public static final String KEY_TITLE = "not_title";
Context context;
public static final String KEY_PHOTO = "not_photo";
public final static String KEY_PRICE = "not_price";
public final static String KEY_DATE = "not_date";
public final static String KEY_DATE_TILL = "not_date_till";
private int not_source = 3;
JSONObject test = null;
ListView list;
MyAddActivateAdapter adapter;
ArrayList<HashMap<String, String>> addList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.aadd_my_add_list_to_activate);
footer = getLayoutInflater().inflate(R.layout.loading_view, null);
addList = new ArrayList<HashMap<String, String>>();
ImageView back_button = (ImageView) findViewById(R.id.imageView3);
back_button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),
ChooserActivity.class);
startActivity(i);
finish();
}
});
Intent intent = this.getIntent();
// if (intent != null) {
// not_source = intent.getExtras().getInt("not_source");
// }
GAdds g = new GAdds();
g.execute(1, not_source);
list = (ListView) findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter = new MyAddActivateAdapter(this, addList);
list.addFooterView(footer);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String add_id = ((TextView) view
.findViewById(R.id.tv_my_add_id)).getText().toString();
add_id = add_id.substring(4);
Log.d("ADD_ID", add_id);
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(),
AddToCheckActivity.class);
// sending data to new activity
UILApplication.advert.setId(add_id);
startActivity(i);
finish();
}
});
}
private void emptyAlertSender() {
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Ничего не найдено");
alertDialog.setMessage("У вас нет неактивных объявлений.");
alertDialog.setButton("на главную",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(),
ChooserActivity.class);
startActivity(intent);
finish();
}
});
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.show();
}
class GAdds extends AsyncTask<Integer, Void, JSONObject> {
#Override
protected JSONObject doInBackground(Integer... params) {
// addList.clear();
Log.d("backgraund", "backgraund");
UserFunctions u = new UserFunctions();
return u.getAdds(params[0] + "", params[1] + "");
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
Log.d("postexecute", "postexecute");
footer.setVisibility(View.GONE);
JSONArray tArr = null;
if (result != null) {
try {
tArr = result.getJSONArray("notices");
for (int i = 0; i < tArr.length(); i++) {
JSONObject a = null;
HashMap<String, String> map = new HashMap<String, String>();
a = (JSONObject) tArr.get(i);
if (a.getInt("not_status") == 0) {
int premium = a.getInt("not_premium");
int up = a.getInt("not_up");
if (premium == 1 && up == 1) {
map.put("status", R.drawable.vip + "");
} else if (premium == 1) {
map.put("status", R.drawable.prem + "");
} else if (premium != 1 && up == 1) {
map.put("status", R.drawable.up + "");
} else {
map.put("status", 0 + "");
}
map.put(KEY_ID, "ID: " + a.getString(KEY_ID));
map.put(KEY_TITLE, a.getString(KEY_TITLE));
map.put(KEY_PRICE,
"Цена: " + a.getString(KEY_PRICE) + " грн.");
map.put(KEY_PHOTO, a.getString(KEY_PHOTO));
map.put(KEY_DATE,
"Создано: " + a.getString(KEY_DATE));
map.put(KEY_DATE_TILL,
"Действительно до: "
+ a.getString(KEY_DATE_TILL));
map.put("check", "false");
Log.d("MyAddList", "map was populated");
}
if (map.size() > 0)
{
addList.add(map);
Log.d("MyAddList", "addlist was populated");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
if (UILApplication.login != 2) {
UILApplication.login = 3;
}
onCreateDialog(LOST_CONNECTION).show();
}
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});
if (not_source == 3) {
not_source = 5;
GAdds task = new GAdds();
task.execute(1, 5);
}
if (not_source == 5) {
Log.d("ID", m.get(KEY_ID));
if (addList.size() == 0) {
emptyAlertSender();
}
}
}
}
#SuppressWarnings("unchecked")
public void addAct(View v) {
AddActivate aAct = new AddActivate(this);
aAct.execute(addList);
}
#Override
public void onAddActivate(JSONObject result) {
if (result != null) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
}
adapter
public class MyAddActivateAdapter extends BaseAdapter {
private List<Row> rows;
private ArrayList<HashMap<String, String>> data;
private Activity activity;
public MyAddActivateAdapter(Activity activity,
ArrayList<HashMap<String, String>> data) {
Log.d("mediaadapter", "listcreation: " + data.size());
rows = new ArrayList<Row>();// member variable
this.data = data;
this.activity = activity;
}
#Override
public int getViewTypeCount() {
return RowType.values().length;
}
#Override
public void notifyDataSetChanged() {
rows.clear();
for (HashMap<String, String> addvert : data) {
rows.add(new MyAddActivateRow((LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE), addvert));
Log.d("MyActivateAdapter", "update " + data.size());
}
}
#Override
public int getItemViewType(int position) {
return rows.get(position).getViewType();
}
public int getCount() {
return rows.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
return rows.get(position).getView(convertView);
}
}
I think the problem is you aren't calling the super class of notifyDataSetChanged(), maybe try
#Override
public void notifyDataSetChanged() {
rows.clear();
for (HashMap<String, String> addvert : data) {
rows.add(new MyAddActivateRow((LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE), addvert));
Log.d("MyActivateAdapter", "update " + data.size());
}
super.notifyDataSetChanged();
}