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);
}
}
}
Related
I am developing the chatbot app. I am using the RecycleView to render the chat of user and bot. I have to show the user listview or text response depend upon his query. All is working until my RecyclerView get's scroll. Whenever my RecyclerView gets scroll it changes the item position. I search a lot and applied every solution but not able to solve my issue.
here is my activity.java
public class HomeActivity extends AppCompatActivity implements AIListener,
View.OnClickListener {
private RecyclerView recyclerView;
private ChatAdapter mAdapter;
LinearLayoutManager layoutManager;
private ArrayList<Message> messageArrayList;
private EditText inputMessage;
private RelativeLayout btnSend;
Boolean flagFab = true;
PaytmPGService service = null;
Map<String, String> paytmparam = new HashMap<>();
PrefManager prefManager;
private AIService aiService;
AIDataService aiDataService;
AIRequest aiRequest;
Gson gson;
String food_dish = " ";
double price = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
inputMessage = findViewById(R.id.editText_ibm);
btnSend = findViewById(R.id.addBtnibm);
recyclerView = findViewById(R.id.recycler_view_ibm);
messageArrayList = new ArrayList<>();
mAdapter = new ChatAdapter(this,messageArrayList);
prefManager = new PrefManager(this);
GsonBuilder gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
layoutManager = new LinearLayoutManager(this);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
int msgCount = mAdapter.getItemCount();
int lastVisiblePosition = layoutManager.findLastCompletelyVisibleItemPosition();
if (lastVisiblePosition == -1 ||
(positionStart >= (msgCount - 1) &&
lastVisiblePosition == (positionStart - 1))) {
recyclerView.scrollToPosition(positionStart);
}
}
});
recyclerView.setAdapter(mAdapter);
this.inputMessage.setText("");
final AIConfiguration configuration = new AIConfiguration("cabc4b7b9c20409aa7ffb1b3d5fe1243",
AIConfiguration.SupportedLanguages.English,
AIConfiguration.RecognitionEngine.System);
aiService = AIService.getService(this, configuration);
aiService.setListener(this);
aiDataService = new AIDataService(configuration);
aiRequest = new AIRequest();
btnSend.setOnClickListener(this);
inputMessage.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) {
ImageView fab_img = findViewById(R.id.fab_img_ibm);
Bitmap img = BitmapFactory.decodeResource(getResources(), R.drawable.ic_send_white_24dp);
Bitmap img1 = BitmapFactory.decodeResource(getResources(), R.drawable.ic_mic_white_24dp);
if (s.toString().trim().length() != 0 && flagFab) {
ImageViewAnimatedChange(HomeActivity.this, fab_img, img);
flagFab = false;
} else if (s.toString().trim().length() == 0) {
ImageViewAnimatedChange(HomeActivity.this, fab_img, img1);
flagFab = true;
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void ImageViewAnimatedChange(Context c, final ImageView v, final Bitmap new_image) {
final Animation anim_out = AnimationUtils.loadAnimation(c, R.anim.zoom_out);
final Animation anim_in = AnimationUtils.loadAnimation(c, R.anim.zoom_in);
anim_out.setAnimationListener(new Animation.AnimationListener()
{
#Override public void onAnimationStart(Animation animation) {}
#Override public void onAnimationRepeat(Animation animation) {}
#Override public void onAnimationEnd(Animation animation)
{
v.setImageBitmap(new_image);
anim_in.setAnimationListener(new Animation.AnimationListener() {
#Override public void onAnimationStart(Animation animation) {}
#Override public void onAnimationRepeat(Animation animation) {}
#Override public void onAnimationEnd(Animation animation) {}
});
v.startAnimation(anim_in);
}
});
v.startAnimation(anim_out);
}
#Override
public void onClick(View v) {
final String inputmessage = this.inputMessage.getText().toString().trim();
if(!inputmessage.equals("")){
new AsyncTask<String, Void, AIResponse>(){
private AIError aiError;
#Override
protected AIResponse doInBackground(final String... params) {
final AIRequest request = new AIRequest();
String query = params[0];
if (!TextUtils.isEmpty(query))
request.setQuery(query);
try {
return aiDataService.request(request);
} catch (final AIServiceException e) {
aiError = new AIError(e);
return null;
}
}
#Override
protected void onPostExecute(final AIResponse response) {
if (response != null) {
onResult(response);
} else {
onError(aiError);
}
}
}.execute(inputmessage);
}else {
aiService.startListening();
}
inputMessage.setText("");
}
#Override
public void onResult(AIResponse response) {
int itemNumber = 0;
Log.d("dialogeflow response",response.toString());
try {
JSONObject AIResponse = new JSONObject(gson.toJson(response));
Log.d("json response",AIResponse.toString());
final JSONObject result = AIResponse.getJSONObject("result");
JSONArray contexts = result.getJSONArray("contexts");
final JSONObject fulfillment = result.getJSONObject("fulfillment");
if(contexts.length()>0) {
for(int i = 0;i<contexts.length();i++) {
JSONObject context_items = contexts.getJSONObject(i);
JSONObject paramters = context_items.getJSONObject("parameters");
if (paramters.has("Cuisine")) {
prefManager.setCuisinetype(paramters.getString("Cuisine"));
} else if (paramters.has("Restaurants_name")) {
prefManager.setRestaurant_name(paramters.getString("Restaurants_name"));
}
if (paramters.has("number") && !paramters.getString("number").equals("") && paramters.has("Food_Dishes") && !paramters.getString("Food_Dishes").equals("")) {
itemNumber = Integer.parseInt(paramters.getString("number"));
if (itemNumber <= 2 && price !=0) {
price = 300 + (int) (Math.random() * ((1400 - 300) + 1));
} else {
price = 600 + (int) (Math.random() * ((2200 - 600) + 1));
}
food_dish = paramters.getString("Food_Dishes");
}
}
}
final double finalPrice = price;
final int finalItemNumber = itemNumber;
if(!result.getString("resolvedQuery").matches("payment is done successfully")) {
Message usermsg = new Message();
usermsg.setMessage(result.getString("resolvedQuery"));
usermsg.setId("1");
messageArrayList.add(usermsg);
mAdapter.notifyDataSetChanged();
if (fulfillment.has("speech")) {
Log.d("response of speech", fulfillment.getString("speech"));
if (!fulfillment.getString("speech").equals("") && fulfillment.getString("speech") != null) {
final String speech = fulfillment.getString("speech");
if (fulfillment.getString("speech").matches("Redirecting you to the Pay-Tm site")) {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
outMessage.setMessage(speech);
outMessage.setId("2");
messageArrayList.add(outMessage);
mAdapter.notifyDataSetChanged();
getpaytm_params((int) price);
}
}, 2000);
} else {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
if (speech.contains("Your total bill is ₹")) {
Log.d("price", String.valueOf(price));
outMessage.setMessage("Please Confirm your order:- \n" +finalItemNumber +" "+food_dish+" from "+prefManager.getRestaurant_name()+" at Flat No: 20,Galaxy Apartment,Airport Authority Colony,Andheri,Mumbai,Maharashtra 400 047 \n Your total bill is ₹"+price+". \n Do you want to pay by Wallet or by PayTm");
}else{
outMessage.setMessage(speech);
}
outMessage.setId("2");
messageArrayList.add(outMessage);
Log.d("messgae",outMessage.getMessage());
mAdapter.notifyDataSetChanged();
}
}, 2000);
}
} else {
final JSONArray msg = fulfillment.getJSONArray("messages");
for (int i = 0; i < msg.length(); i++) {
if (i == 0) {
Message outMessage = new Message();
JSONObject speechobj = msg.getJSONObject(i);
JSONArray speech = speechobj.getJSONArray("speech");
Log.d("response of speech", speech.getString(0));
outMessage.setMessage(speech.getString(0));
outMessage.setId("2");
messageArrayList.add(outMessage);
} else {
final int itemposition = i;
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
try {
JSONObject speechobj = msg.getJSONObject(itemposition);
JSONArray speech = speechobj.getJSONArray("speech");
Log.d("response of speech", speech.getString(0));
outMessage.setMessage(speech.getString(0));
outMessage.setId("2");
messageArrayList.add(outMessage);
mAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, 5000);
}
}
}
}
}else{
if (!fulfillment.getString("speech").equals("") && fulfillment.getString("speech") != null) {
final String speech = fulfillment.getString("speech");
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
outMessage.setMessage(speech);
outMessage.setId("2");
messageArrayList.add(outMessage);
mAdapter.notifyDataSetChanged();
}
},2000);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(AIError error) {
}
#Override
public void onAudioLevel(float level) {
}
#Override
public void onListeningStarted() {
btnSend.setBackground(getDrawable(R.drawable.recording_bg));
}
#Override
public void onListeningCanceled() {
btnSend.setBackground(getDrawable(R.drawable.stedy_recording));
}
#Override
public void onListeningFinished() {
btnSend.setBackground(getDrawable(R.drawable.stedy_recording));
}
}`
my ChatAdapter.java class
public class ChatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private int BOT = 100;
private int BOT_Restaurant_ListView = 101;
private int USER = 102;
private Activity activity;
private PrefManager prefManager;
private int itemposition = -1;
private int menu_itemposition = -1;
private List<Restaurant_List_Model> restaurant_list;
private ArrayList<Message> messageArrayList;
private RestaurantListViewAdapter restaurantListViewAdapter;
private TextToSpeech tts ;
public ChatAdapter(Activity activity, ArrayList<Message> messageArrayList) {
this.activity = activity;
this.messageArrayList = messageArrayList;
tts = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR){
tts.setLanguage(Locale.ENGLISH);
}
}
});
prefManager = new PrefManager(activity.getApplicationContext());
setHasStableIds(true);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemview;
if(viewType == BOT){
itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.bot_msg_view,parent,false);
}else if(viewType == BOT_Restaurant_ListView){
itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.bot_msg_restaurant_listview,parent,false);
}else {
itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_msg_view,parent,false);
}
return new ViewHolder(itemview);
}
#Override
public int getItemViewType(int position) {
Message message = messageArrayList.get(position);
if(message.getId()!=null && message.getId().equals("2")){
if(message.getMessage().contains("restaurants") || message.getMessage().contains("restaurant")) {
return BOT_Restaurant_ListView;
}else {
return BOT;
}
}else{
return USER;
}
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position) {
int pic_int = 1;
String filename = null;
final Message message = messageArrayList.get(position);
message.setMessage(message.getMessage());
if (holder.getItemViewType() == BOT_Restaurant_ListView) {
Log.d("inside bot listview msg", String.valueOf(BOT_Restaurant_ListView ));
Log.d("adapter position", String.valueOf(holder.getAdapterPosition()));
if(itemposition<holder.getAdapterPosition()){
itemposition = holder.getAdapterPosition();
Log.d("itemposition",String.valueOf(itemposition));
String jsonFileContent;
Log.d("cuisine value", prefManager.getCuisinetype());
if (message.getMessage().contains("restaurants")) {
if(!prefManager.getCuisinetype().equals("") && prefManager.getCuisinetype() != null){
Log.d("restauratn has drawn", "greate");
try {
restaurant_list = new ArrayList<>();
restaurantListViewAdapter = new RestaurantListViewAdapter(activity, restaurant_list);
((ViewHolder) holder).retaurant_listView.setVisibility(View.VISIBLE);
((ViewHolder) holder).retaurant_listView.setAdapter(restaurantListViewAdapter);
Log.d("cuisine value", prefManager.getCuisinetype());
if(message.getMessage().contains("Here are restaurants near you")){
String [] restaurant_Array ={
"indian","french","mexican","italian"
};
int randomNumber = (int) Math.floor(Math.random()*restaurant_Array.length);
filename = restaurant_Array[randomNumber];
Log.d("filename",filename);
jsonFileContent = readFile(activity.getResources().getIdentifier(filename, "raw", activity.getPackageName()));
}else {
filename = prefManager.getCuisinetype().toLowerCase() + "_restaurants";
Log.d("filename", filename);
jsonFileContent = readFile(activity.getResources().getIdentifier(filename, "raw", activity.getPackageName()));
}
JSONObject restaurantfile = new JSONObject(jsonFileContent);
JSONArray jsonArray = restaurantfile.getJSONArray("restaurants");
for (int i = 0; i < jsonArray.length(); i++) {
ImageRoundCorner imageRoundCorner = new ImageRoundCorner();
JSONObject restaurantList = jsonArray.getJSONObject(i);
Restaurant_List_Model restaurant_list_obj = new Restaurant_List_Model();
restaurant_list_obj.setName(restaurantList.getString("name"));
restaurant_list_obj.setLocation(restaurantList.getString("location"));
restaurant_list_obj.setImage_of_item(imageRoundCorner.getRoundedCornerBitmap(BitmapFactory.decodeResource(activity.getResources(), activity.getResources().getIdentifier("restaurant_" + pic_int, "drawable", activity.getPackageName()))));
pic_int++;
restaurant_list_obj.setRating(restaurantList.getLong("rating"));
restaurant_list.add(restaurant_list_obj);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
} else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
prefManager.setCuisinetype("");
pic_int = 1;
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
restaurantListViewAdapter.notifyDataSetChanged();
}
}else if(message.getMessage().contains("Here are some famous food items from "+prefManager.getRestaurant_name()+" restaurant")){
try {
Log.d("menu has draw","greate");
restaurant_list = new ArrayList<>();
restaurantListViewAdapter = new RestaurantListViewAdapter(activity, restaurant_list);
((ViewHolder) holder).retaurant_listView.setAdapter(restaurantListViewAdapter);
((ViewHolder) holder).retaurant_listView.setVisibility(View.VISIBLE);
Log.d("restaurant name value", prefManager.getRestaurant_name());
jsonFileContent = readFile(R.raw.restaurant_menu);
JSONObject menu_cuisine = new JSONObject(jsonFileContent);
ImageRoundCorner imageRoundCorner = new ImageRoundCorner();
if (menu_cuisine.has(prefManager.getRestaurant_name())) {
JSONObject restaurant_menu = menu_cuisine.getJSONObject("Dominos");
Log.d("Chili's American menu", restaurant_menu.toString());
JSONArray menu = restaurant_menu.getJSONArray("menu");
for (int j = 0; j < menu.length(); j++) {
JSONObject menu_obj = menu.getJSONObject(j);
Restaurant_List_Model restaurant_list_obj = new Restaurant_List_Model();
restaurant_list_obj.setName(menu_obj.getString("name"));
restaurant_list_obj.setLocation(menu_obj.getString("cuisine_type"));
restaurant_list_obj.setImage_of_item(imageRoundCorner.getRoundedCornerBitmap(BitmapFactory.decodeResource(activity.getResources(), activity.getResources().getIdentifier("menu_" + pic_int, "drawable", activity.getPackageName()))));
//restaurant_list_obj.setImage_of_item(imageRoundCorner.getRoundedCornerBitmap(BitmapFactory.decodeResource(activity.getResources(), activity.getResources().getIdentifier("menu_" + pic_int, "drawable", activity.getPackageName()))));
pic_int++;
restaurant_list_obj.setRating(menu_obj.getLong("rating"));
restaurant_list.add(restaurant_list_obj);
}
restaurantListViewAdapter.notifyDataSetChanged();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
} else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
pic_int = 1;
prefManager.setRestaurant_name("");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Log.d("user_message",message.getMessage());
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
}else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
pic_int = 1;
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
((ViewHolder) holder).retaurant_listView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
v.onTouchEvent(event);
return true;
}
});
}
} if(holder.getItemViewType()==BOT) {
Log.d("adapter position", String.valueOf(holder.getAdapterPosition()));
Log.d("inside bot msg", String.valueOf(BOT));
((ViewHolder) holder).bot_msg.setText(message.getMessage());
if(itemposition<holder.getAdapterPosition()) {
itemposition = holder.getAdapterPosition();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
} else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
}
}if(holder.getItemViewType() == USER) {
((ViewHolder) holder).user_message.setText(message.getMessage());
}
}
#Override
public void onViewRecycled(#NonNull RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
if(holder.isRecyclable()){
Log.d("inside onViewRecycled","great");
// itemposition = holder.getAdapterPosition();
}
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public int getItemCount() {
return messageArrayList.size();
}
private String readFile(int id) throws IOException
{
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(activity.getResources().openRawResource(id)));
String content = "";
String line;
while ((line = reader.readLine()) != null)
{
content = content + line;
}
return content;
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView user_message,bot_msg;
private ListView retaurant_listView;
ViewHolder(View itemView) {
super(itemView);
bot_msg = itemView.findViewById(R.id.bot_message);
user_message = itemView.findViewById(R.id.message);
retaurant_listView = itemView.findViewById(R.id.restaurant_items_list_ibm);
}
}
}
Please help me out with this issue.
In gif, you can see the lower list is swap with the upper list and then return back
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;
}
}
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.
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();
}
I am trying to sort the collection in custom arrayadapter and making a call to update the view . However, the view does not gets updated.
There are two values over which I want to sort (date and amount) and have a custom comparators for them.
I can see that the data itself has changed (i.e if a list item has gone outside of view after sorting and when it gets the view, the data it show is the correct data that should exist after sorting).
The second question is about the filter. The way the filter is implemented right now, it does not update the views either.
Here is code
public class SearchActivity extends BListActivity {
private Bundle sessionInfo;
private TransactionDetailsHandler transactionDetailsHandler = new TransactionDetailsHandler();
private static boolean ascDate = false;
private static boolean ascAmount = false;
private ArrayList<TransactionDetails> transactionDetails;
private ArrayList<TransactionDetails> filterResults;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sessionInfo = getIntent().getExtras();
final String sessionId = sessionInfo.getString("sessionId");
final String transactionResponse = sessionInfo
.getString(C.TRN_DETAIL_KEY);
try {
Xml.parse(transactionResponse, transactionDetailsHandler);
} catch (Exception ex) {
ex.printStackTrace();
}
final ArrayAdapter<TransactionDetails> adapter = getArrayAdapter();
findViewById(R.id.amount_btn).setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
if (ascDate) {
adapter.sort(new TransactionDetailAmountComparatorAsc());
ascDate = false;
} else {
adapter.sort(new TransactionDetailAmountComparatorDesc());
ascDate = true;
}
adapter.notifyDataSetChanged();
}
});
findViewById(R.id.date_btn).setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
if (ascAmount) {
adapter.sort(new TransactionDetailDateComparatorAsc());
ascAmount = false;
} else {
adapter.sort(new TransactionDetailDateComparatorDesc());
ascAmount = true;
}
adapter.notifyDataSetChanged();
}
});
findViewById(R.id.search_btn).setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
findViewById(R.id.buttonLL).setVisibility(View.GONE);
findViewById(R.id.searchLL).setVisibility(View.VISIBLE);
}
});
findViewById(R.id.cancel_btn).setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
findViewById(R.id.searchLL).setVisibility(View.GONE);
findViewById(R.id.buttonLL).setVisibility(View.VISIBLE);
}
});
TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
System.out.println("XXXX Constraint = " + s);
adapter.getFilter().filter(s);
}
};
EditText et = (EditText) findViewById(R.id.edit_box);
et.addTextChangedListener(filterTextWatcher);
}
protected ArrayAdapter<TransactionDetails> getArrayAdapter() {
transactionDetails = transactionDetailsHandler
.getTransactionDetailsList();
filterResults = transactionDetails;
return new SearchListAdapter(this,
(List<TransactionDetails>) transactionDetails);
}
protected class SearchListAdapter extends ArrayAdapter<TransactionDetails> {
private int rId;
private List<TransactionDetails> data;
private Filter filter;
public SearchListAdapter(Context context, List<TransactionDetails> data) {
super(context, R.layout.search_list_item, data);
this.rId = R.layout.search_list_item;
this.data = data;
}
#Override
public View getView(int position, View cv, ViewGroup parent) {
cv = getLayoutInflater().inflate(rId, parent, false);
TransactionDetails item = data.get(position);
((TextView) cv.findViewById(R.id.t_id)).setText(item.getTrnId());
((TextView) cv.findViewById(R.id.date)).setText(item
.getTrnDatetime());
((TextView) cv.findViewById(R.id.amount)).setText(item
.getTrnAmount());
((TextView) cv.findViewById(R.id.card_num))
.setText("XXXX XXXX XXXX " + item.getTrnMaskedCard());
try {
if (item.getTrnCardType() != null
&& item.getTrnCardType().trim().length() > 0)
((ImageView) cv.findViewById(R.id.card_img))
.setImageResource(Integer.parseInt(item
.getTrnCardType()));
} catch (Exception ex) {
ex.printStackTrace();
}
((TextView) cv.findViewById(R.id.result)).setText(item
.getTrnStatus());
return cv;
}
#Override
public Filter getFilter() {
if (filter == null)
filter = new TransactionDetailFilter();
return filter;
}
private class TransactionDetailFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
System.out.println("XXXX Started filtering with Constraint = "
+ constraint);
FilterResults results = new FilterResults();
String prefix = constraint.toString().toLowerCase();
if (prefix == null || prefix.length() == 0) {
ArrayList<TransactionDetails> list = new ArrayList<TransactionDetails>(
transactionDetails);
results.values = list;
results.count = list.size();
} else {
final ArrayList<TransactionDetails> list = new ArrayList<TransactionDetails>(
transactionDetails);
final ArrayList<TransactionDetails> nlist = new ArrayList<TransactionDetails>();
int count = list.size();
System.out
.println("XXXX List to be search size = " + count);
for (int i = 0; i < count; i++) {
final TransactionDetails details = list.get(i);
System.out.println("XXXX List to be searched = "
+ details.toString());
if (details.getTrnId().startsWith(prefix)
|| details.getTrnDatetime().startsWith(prefix)
|| details.getTrnAmount().startsWith(prefix)
|| details.getTrnMaskedCard()
.startsWith(prefix)
|| details.getTrnStatus().startsWith(prefix)) {
System.out.println("XXXX Adding result "
+ details.toString());
nlist.add(details);
}
}
results.values = nlist;
results.count = nlist.size();
}
System.out.println("XXXX Ended filtering with Constraint = "
+ constraint + " . Result size = " + results.count);
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
System.out.println("XXXX Preparing to publish results. Result size = "+ results.count);
ArrayList<TransactionDetails> fitems = (ArrayList<TransactionDetails>) results.values;
clear();
int count = fitems.size();
for (int i = 0; i < count; i++) {
TransactionDetails details = (TransactionDetails) fitems
.get(i);
add(details);
}
notifyDataSetChanged();
System.out.println("XXXX Finished publishing results.");
}
}
#Override
public void add(TransactionDetails item) {
System.out.println("XXXX Adding items to be published." + item.toString());
filterResults.add(item);
}
}
// -------------------------------------------------------------------------------------------------------------------------------------------------
class TransactionDetailAmountComparatorAsc implements
Comparator<TransactionDetails> {
public int compare(TransactionDetails detail1,
TransactionDetails detail2) {
float f = Float.parseFloat(detail1.getTrnAmount())
- Float.parseFloat(detail2.getTrnAmount());
if (f > 0)
return 1;
if (f < 1)
return -1;
return 0;
}
}
class TransactionDetailAmountComparatorDesc implements
Comparator<TransactionDetails> {
public int compare(TransactionDetails detail1,
TransactionDetails detail2) {
float f = Float.parseFloat(detail1.getTrnAmount())
- Float.parseFloat(detail2.getTrnAmount());
if (f > 0)
return -1;
if (f < 1)
return 1;
return 0;
}
}
class TransactionDetailDateComparatorAsc implements
Comparator<TransactionDetails> {
public int compare(TransactionDetails detail1,
TransactionDetails detail2) {
detail1.getTrnDatetime();
detail2.getTrnDatetime();
String pattern = "MM/dd/yy HH:mm";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
Date date1 = format.parse(detail1.getTrnDatetime());
Date date2 = format.parse(detail2.getTrnDatetime());
return date1.compareTo(date2);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
class TransactionDetailDateComparatorDesc implements
Comparator<TransactionDetails> {
public int compare(TransactionDetails detail1,
TransactionDetails detail2) {
detail1.getTrnDatetime();
detail2.getTrnDatetime();
String pattern = "MM/dd/yy HH:mm";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
Date date1 = format.parse(detail1.getTrnDatetime());
Date date2 = format.parse(detail2.getTrnDatetime());
return -(date1.compareTo(date2));
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
position -= ((ListView) parent).getHeaderViewsCount();
TransactionDetails details = (TransactionDetails) parent.getAdapter()
.getItem(position);
Bundle b = new Bundle(sessionInfo);
b.putSerializable(C.TRN_DETAIL_KEY, details);
Util.openView(SearchActivity.this, TransDetailActivity.class, b);
}
#Override
protected int getContentView() {
return R.layout.search_layout;
}
#Override
protected int getStringArrayID() {
return 0;
}
#Override
protected Class<?>[] getDestinations() {
return null;
}
#Override
protected int getTitleId() {
return R.string.search;
}
}