I want to get selected data from firebase. Actually I used listview for getting values. On selected item I need more info from data. But unfortunately am not be able to get selected data.
That's relevant code.
New_Deal_List.java
lvDealList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
NewDeal_Database newDeal_database = dealList.get(i);
Intent intent = new Intent(getApplicationContext(), Deal_Detail_one.class);
mEditor.putString(getString(R.string.COOKER_ID), newDeal_database.getuId());
mEditor.commit();
passingtoDealDaysCheckValues(newDeal_database.getDealId());
startActivity(intent);
}
});
}
Passing deal id to this function.
dealDaysRefrence.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dealSnapshot : dataSnapshot.getChildren())
{
NewDeal_Database newDeal_database = dealSnapshot.child(DealId).getValue(NewDeal_Database.class);
try{
Toast.makeText(New_Deal_List.this,dealSnapshot.child(DealId).getValue(NewDeal_Database.class).toString(),Toast.LENGTH_SHORT).show();
if(newDeal_database.getMonday()== true ){
Toast.makeText(getApplicationContext(),DEAL_DAYS_MONDAY,Toast.LENGTH_SHORT).show();
DEAL_DAYS_MONDAY = "Available";
}else{
Toast.makeText(getApplicationContext(),DEAL_DAYS_MONDAY,Toast.LENGTH_SHORT).show();
DEAL_DAYS_MONDAY = "Not-Available";
}
if(dealSnapshot.child(DealId).getValue(NewDeal_Database.class).getTuesday() == true){
DEAL_DAYS_TUESDAY = "Available";
Toast.makeText(getApplicationContext(),DEAL_DAYS_TUESDAY,Toast.LENGTH_SHORT).show();
}else{
DEAL_DAYS_TUESDAY = "Not-Available";
Toast.makeText(getApplicationContext(),DEAL_DAYS_TUESDAY,Toast.LENGTH_SHORT).show();
}
if(dealSnapshot.child(DealId).getValue(NewDeal_Database.class).getWednesday() == true){
DEAL_DAYS_WEDNESDAY = "Available";
}else{
DEAL_DAYS_WEDNESDAY = "Not-Available";
}
if(dealSnapshot.child(DealId).getValue(NewDeal_Database.class).getThursday() == true){
DEAL_DAYS_THURSDAY = "Available";
}else{
DEAL_DAYS_THURSDAY = "Not-Available";
}
if(dealSnapshot.child(DealId).getValue(NewDeal_Database.class).getFriday() == true){
DEAL_DAYS_FRIDAY = "Available";
}else{
DEAL_DAYS_FRIDAY = "Not-Available";
}
}catch (Exception e){
e.printStackTrace();
}finally {
mEditor.putString(getString(R.string.DEAL_DAYS_MONDAY), DEAL_DAYS_MONDAY);
mEditor.commit();
mEditor.putString(getString(R.string.DEAL_DAYS_TUESDAY), DEAL_DAYS_TUESDAY);
mEditor.commit();
mEditor.putString(getString(R.string.DEAL_DAYS_WEDNESDAY), DEAL_DAYS_WEDNESDAY);
mEditor.commit();
mEditor.putString(getString(R.string.DEAL_DAYS_THURSDAY), DEAL_DAYS_THURSDAY);
mEditor.commit();
mEditor.putString(getString(R.string.DEAL_DAYS_FRIDAY), DEAL_DAYS_THURSDAY);
mEditor.commit();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
In above code, if and else condition not getting desired values.
Also android studio give me suggetion. Check suggetion snapshot
This is NewDeal_Database.java class, where i set the values.
public NewDeal_Database(Boolean Monday, Boolean Tuesday, Boolean Wednesday, Boolean Thursday, Boolean Friday){
this.Monday = Monday;
this.Tuesday = Tuesday;
this.Wednesday = Wednesday;
this.Thursday = Thursday;
this.Friday = Friday;
public Boolean getMonday() {
return Monday;
}
public Boolean getTuesday() {
return Tuesday;
}
public Boolean getWednesday() {
return Wednesday;
}
public Boolean getThursday() {
return Thursday;
}
public Boolean getFriday() {
return Friday;
}
I am inserting data from into firebase in New_Deal_Time.java
using this codeNew_Deal_Time.java
dealDaysRefrence.child(id).child(DealId).setValue(dealdays);
firebase snapshot
suggsetion snapshot
First, your NewDeal_Database.java class should look like this:
public class NewDeal_Database {
public NewDeal_Database(Boolean monday, Boolean tuesday, Boolean wednesday, Boolean thursday, Boolean friday){
this.monday = monday;
this.tuesday = tuesday;
this.wednesday = wednesday;
this.thursday = thursday;
this.friday = friday;
public NewDeal_Database {} //Needed for Firebase
public Boolean getMonday() {
return monday;
}
public Boolean getTuesday() {
return tuesday;
}
public Boolean getWednesday() {
return wednesday;
}
public Boolean getThursday() {
return thursday;
}
public Boolean getFriday() {
return friday;
}
}
To get that data, please use the following code:
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String eightToten = ds.child("eightToten").getValue(Boolean.class);
String nineToeleven = ds.child("nineToeleven").getValue(Boolean.class);
String sixToeight = ds.child("sixToeight").getValue(Boolean.class);
String twelveTotwo = ds.child("twelveTotwo").getValue(Boolean.class);
Log.d("TAG", eightToten + " / " + nineToeleven + " / " + sixToeight + " / " + twelveTotwo);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
dealDaysRefrence.child(id).addListenerForSingleValueEvent(eventListener);
Related
When I run the codes, it does not show any error. I have no problem to login as guardian but when I try to login as elderly it couldn't and I don't know what's the problem. What I want is when a user input the username and password, it will validate from database and direct the user according to different user type.
Segment codes of Login.java:
private Boolean validateUsername() {
String val = username.getEditText().getText().toString();
if (val.isEmpty()) {
username.setError("Field cannot be empty");
return false;
} else {
username.setError(null);
username.setErrorEnabled(false);
return true;
}
}
private Boolean validatePassword() {
String val = password.getEditText().getText().toString();
if (val.isEmpty()) {
password.setError("Field cannot be empty");
return false;
} else {
password.setError(null);
password.setErrorEnabled(false);
return true;
}
}
public void loginUser(View view) {
//validate login info
if (!validateUsername() || !validatePassword()) {
return;
} else {
isUser();
}
}
private void isUser() {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("user").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String input1 = username.getEditText().getText().toString();
String input2 = password.getEditText().getText().toString();
if (dataSnapshot.child(input1).exists()) {
if (dataSnapshot.child(input1).child("password").getValue(String.class).equals(input2)) {
if (active.isChecked()) {
if (dataSnapshot.child(input1).child("radioGuardian").getValue(String.class).equals("Guardian")) {
preferences.setDataLogin(Login.this, true);
preferences.setDataAs(Login.this, "Guardian");
startActivity(new Intent(Login.this, dashboardGuardian.class));
} else if (dataSnapshot.child(input1).child("radioElderly").getValue(String.class).equals("Elderly")) {
preferences.setDataLogin(Login.this, true);
preferences.setDataAs(Login.this, "Elderly");
startActivity(new Intent(Login.this, dashboardUser.class));
}
} else {
if (dataSnapshot.child(input1).child("radioGuardian").getValue(String.class).equals("Guardian")) {
preferences.setDataLogin(Login.this, false);
startActivity(new Intent(Login.this, dashboardGuardian.class));
} else if (dataSnapshot.child(input1).child("radioElderly").getValue(String.class).equals("Elderly")) {
preferences.setDataLogin(Login.this, false);
startActivity(new Intent(Login.this, dashboardUser.class));
}
}
} else {
password.setError("Wrong Password");
password.requestFocus();
}
} else {
username.setError("No such User exist");
username.requestFocus();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
protected void onStart() {
super.onStart();
if (preferences.getDataLogin(this)) {
if (preferences.getDataAs(this).equals("Guardian")) {
startActivity(new Intent(this, dashboardGuardian.class));
finish();
} else {
startActivity(new Intent(this, dashboardUser.class));
finish();
}
}
}
}
Codes of Register.java:
public class Register extends AppCompatActivity {
//Variables
TextInputLayout regUsername, regEmail, regPhoneNo, regPassword;
RadioGroup radioGroup;
RadioButton selectedElderly, selectedGuardian;
Button regBtn, regToLoginBtn;
UserHelperClass helperClass;
int i = 0;
FirebaseDatabase rootNode;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//Hooks to all xml elements in activity_register.xml
regUsername = findViewById(R.id.reg_username);
regEmail = findViewById(R.id.reg_email);
regPhoneNo = findViewById(R.id.reg_phoneNo);
regPassword = findViewById(R.id.reg_password);
regBtn = findViewById(R.id.reg_btn);
regToLoginBtn = findViewById(R.id.reg_login_btn);
radioGroup = findViewById(R.id.radio_type);
selectedGuardian = findViewById(R.id.radioGuardian);
selectedElderly = findViewById(R.id.radioElderly);
helperClass = new UserHelperClass();
regBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validateUsername() && validateEmail() && validatePhoneNo() && validateUserType() && validatePassword() == true) {
Intent intent = new Intent(Register.this, Login.class);
startActivity(intent);
} else {
validateUsername();
validateEmail();
validatePhoneNo();
validateUserType();
validatePassword();
}
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("user");
//Get all the values
String m1 = selectedElderly.getText().toString();
String m2 = selectedGuardian.getText().toString();
String username = regUsername.getEditText().getText().toString();
String password = regPassword.getEditText().getText().toString();
helperClass.setUsername(regUsername.getEditText().getText().toString());
helperClass.setEmail(regEmail.getEditText().getText().toString());
helperClass.setPhoneNo(regPhoneNo.getEditText().getText().toString());
helperClass.setPassword(regPassword.getEditText().getText().toString());
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
} else {
helperClass.setRadioGuardian(m2);
}
reference.child(username).setValue(helperClass);
}
});
regToLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Register.this, Login.class);
startActivity(intent);
}
});
}
private Boolean validateUsername() {
String val = regUsername.getEditText().getText().toString();
String noWhiteSpace = "\\A\\w{4,20}\\z";
if (val.isEmpty()) {
regUsername.setError("Field cannot be empty");
return false;
} else if (val.length() >= 15) {
regUsername.setError("Username too long");
return false;
} else if (!val.matches(noWhiteSpace)) {
regUsername.setError("White space is not allowed");
return false;
} else {
regUsername.setError(null);
regUsername.setErrorEnabled(false);
return true;
}
}
private Boolean validateEmail() {
String val = regEmail.getEditText().getText().toString();
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (val.isEmpty()) {
regEmail.setError("Field cannot be empty");
return false;
} else if (!val.matches(emailPattern)) {
regEmail.setError("Invalid email address");
return false;
} else {
regEmail.setError(null);
return true;
}
}
private Boolean validatePhoneNo() {
String val = regPhoneNo.getEditText().getText().toString();
if (val.isEmpty()) {
regPhoneNo.setError("Field cannot be empty");
return false;
} else {
regPhoneNo.setError(null);
return true;
}
}
private Boolean validateUserType() {
if (radioGroup.getCheckedRadioButtonId() == -1) {
Toast.makeText(this, "Please select user type", Toast.LENGTH_SHORT).show();
return false;
} else {
return true;
}
}
private Boolean validatePassword() {
String val = regPassword.getEditText().getText().toString();
String passwordVal = "^" +
"(?=.*[0-9])" + //at least 1 digit
"(?=.*[a-z])" + //at least 1 lower case letter
"(?=.*[A-Z])" + //at least 1 upper case letter
"(?=.*[a-zA-Z])" + //any letter
"(?=.*[##$%^&+=])" + //at least 1 special character
"(?=\\S+$)" + //no white space
".{4,}" + //at least 4 characters
"$";
if (val.isEmpty()) {
regPassword.setError("Field cannot be empty");
return false;
} else if (!val.matches(passwordVal)) {
regPassword.setError("Password is too weak");
return false;
} else {
regPassword.setError(null);
regPassword.setErrorEnabled(false);
return true;
}
}
public void registerUser(View view) {
if (!validateUsername() | !validatePassword() | !validatePhoneNo() | !validateEmail() | validateUserType()) {
return;
}
//Get all the values
String m1 = selectedElderly.getText().toString();
String m2 = selectedGuardian.getText().toString();
helperClass.setUsername(regUsername.getEditText().getText().toString());
helperClass.setEmail(regEmail.getEditText().getText().toString());
helperClass.setPhoneNo(regPhoneNo.getEditText().getText().toString());
helperClass.setPassword(regPassword.getEditText().getText().toString());
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
} else {
helperClass.setRadioGuardian(m2);
}
reference.child(String.valueOf(i + 1)).setValue(helperClass);
}
}
Database structure
If you post your database structure that would be more helpful.
As per your code.
you have two children in input1
'radioGuardian' and 'radioElderly'
have you added both values on registration? Or it will be null. And it will produce nullPointEx.
Hence the issue is here!
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
} else {
helperClass.setRadioGuardian(m2);
}
Try to change it to:-
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
helperClass.setRadioGuardian("NA");
} else {
helperClass.setRadioGuardian(m2);
helperClass.setRadioElderly("NA");
}
I am new to android development.I have a recyclerview with Viewholder for displaying photo.I have implement like feature in my app but only problem that I am facing is when I add a like on the photo the like does not show on photo I liked instead it is showing like on another photo that is down below,when I see in firebase database it looks fine but it does not display in the right position in recycler view.
I think it is not updating position how can I solve this?
this is my adapter class
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, final int position) {
// mHolder = holder;
photo = moviesList.get(position);
// final VideoHolder viewHolder2 = (VideoHolder)holder;
int viewType = getItemViewType(holder.getAdapterPosition());
switch ( viewType ) {
case IMAGE_TYPE:
PhotoHolder photoview = (PhotoHolder) holder;
mPhotoHolder = photoview;
getCurrentUsername();
getLikesPhotoString();
final ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(getItem(position).getImage_path(),photoview.image);
photoview.mHeart.setOnLikeListener(new OnLikeListener() {
#Override
public void liked(LikeButton likeButton) {
addNewPhotolike(mPhotoHolder);
}
#Override
public void unLiked(LikeButton likeButton) {
removePhotolike(mPhotoHolder);
}
});
photoview.Star.setOnLikeListener(new OnLikeListener() {
#Override
public void liked(LikeButton likeButton) {
}
#Override
public void unLiked(LikeButton likeButton) {
}
});
break;
case VIDEO_TYPE:
final VideoHolder viewHolder2 = (VideoHolder)holder;
mVideoHolder = viewHolder2;
break;
}
}
#Override
public int getItemCount() {
return moviesList.size();
}
public Photo getItem(int position) {
return moviesList.get(position);
}
#Override
public int getItemViewType ( int position ) {
int viewType;
if (moviesList.get(position).getType_post().contains("Photo")) {
viewType = IMAGE_TYPE;
} else{
viewType = VIDEO_TYPE;
}
return viewType;
}
this is were photo like is added to firebase
private void addNewPhotolike(TestAdapter.PhotoHolder holder, final int position){
Log.d(TAG, "addNewlike: adding new like ");
String newLikeID = mReference.push().getKey();
Likes likes = new Likes();
likes.setUser_id(FirebaseAuth.getInstance().getCurrentUser().getUid());
mReference.child(mContext.getString(R.string.dbname_photos))
.child(getItem(position).getPhoto_id())
.child(mContext.getString(R.string.field_likes))
.child(newLikeID)
.setValue(likes);
mReference.child(mContext.getString(R.string.dbname_user_photos))
.child(getItem(position).getUser_id())
.child(getItem(position).getPhoto_id())
.child(mContext.getString(R.string.field_likes))
.child(newLikeID)
.setValue(likes);
holder.mHeartPhoto.setLiked(true);
HashMap<String ,String> notificationData = new HashMap<>();
notificationData.put("from",FirebaseAuth.getInstance().getCurrentUser().getUid());
notificationData.put("type","likes");
notificationData.put("photo_desc",getItem(position).getDescription());
holder.mNotification.child(getItem(position).getUser_id()).push().setValue(notificationData).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// getLikesString(mHolder);
getLikesPhotoString(mPhotoHolder,position);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// getLikesString(mHolder);
getLikesPhotoString(mPhotoHolder,position);
}
});
}
This is my code where like is retrieved from firebase and shown in text.
private void getLikesPhotoString(final TestAdapter.PhotoHolder holder, final int postion){
Log.d(TAG, "getLikesString: getting likes string");
try{
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.keepSynced(true);
Query query = reference
.child(mContext.getString(R.string.dbname_photos))
.child(getItem(postion).getPhoto_id())
.child(mContext.getString(R.string.field_likes));
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
holder.usersPhoto = new StringBuilder();
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(mContext.getString(R.string.dbname_users))
.orderByChild(mContext.getString(R.string.field_user_id))
.equalTo(singleSnapshot.getValue(Likes.class).getUser_id());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: found like: " +
singleSnapshot.getValue(User.class).getUsername());
holder.usersPhoto.append(singleSnapshot.getValue(User.class).getUsername());
holder.usersPhoto.append(",");
}
String[] splitUsers = holder.usersPhoto.toString().split(",");
if( holder.usersPhoto.toString().contains(currentUsername + ",")){
holder.likephotobycurrentUser = true;
}else{
holder.likephotobycurrentUser = false;
}
Log.d(TAG, "onDataChange: likes string: " + holder.mLIkePhotoString);
// setupwidjets();
int length = splitUsers.length;
if(length == 1){
holder.mLIkePhotoString = "Liked by " + splitUsers[0];
}
else if(length == 2){
holder.mLIkePhotoString = "Liked by " + splitUsers[0]
+ " and " + splitUsers[1];
}
else if(length == 3){
holder.mLIkePhotoString = "Liked by " + splitUsers[0]
+ ", " + splitUsers[1]
+ " and " + splitUsers[2];
}
else if(length == 4){
holder.mLIkePhotoString = "Liked by " + splitUsers[0]
+ ", " + splitUsers[1]
+ ", " + splitUsers[2]
+ " and " + splitUsers[3];
}
else if(length > 4){
holder.mLIkePhotoString = "Liked by " + splitUsers[0]
+ ", " + splitUsers[1]
+ ", " + splitUsers[2]
+ " and " + (splitUsers.length - 3) + " others";
}
Log.d(TAG, "onDataChange: likes string: " + holder.mLIkePhotoString);
//setup likes string
// setupLikePhotostring(holder, holder.mLIkePhotoString);
holder.mHeartPhoto.setLiked(true);
if (holder.likephotobycurrentUser){
holder.mHeartPhoto.setLiked(true);
}else {
holder.mHeartPhoto.setLiked(false);
}
holder.likes.setText(holder.mLIkePhotoString);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
if(!dataSnapshot.exists()){
holder.mLIkePhotoString = "";
holder.likephotobycurrentUser = false;
//setupwidjets();
// setupLikePhotostring(holder,holder.mLIkePhotoString);
if (holder.likephotobycurrentUser){
holder.mHeartPhoto.setLiked(true);
}else {
holder.mHeartPhoto.setLiked(false);
}
holder.likes.setText(holder.mLIkePhotoString);
holder.mHeartPhoto.setLiked(false);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}catch (NullPointerException e){
Log.e(TAG, "removeStar: NullPointer"+e.getMessage());
holder.mLIkePhotoString = "";
holder.likephotobycurrentUser = false;
// setupLikePhotostring(mPhotoHolder,holder.mLIkePhotoString);
if (holder.likephotobycurrentUser){
holder.mHeartPhoto.setLiked(true);
}else {
holder.mHeartPhoto.setLiked(false);
}
holder.likes.setText(holder.mLIkePhotoString);
}
}
Change this line
photo = moviesList.get(holder.getAdapterPosition());
to
photo = moviesList.get(position);
where position variable is same as we got in below function
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, final int position);
And also change holder.getAdapterPosition() to position in onBindViewHolder(...) function.
I have a model class array list with field name, code and mobile. I want to use search view for all. For example, if I write in name search view xyz and in mobile search view 9768 then it gives all the match of xyz and 9768.
searchMasterList2.add(new SearchItemMaster("111", "222", "333"));
searchMasterList2.add(new SearchItemMaster("555", "333", "444"));
searchMasterList2.add(new SearchItemMaster("222", "444", "555"));
searchMasterList2.add(new SearchItemMaster("333", "111", "222"));
searchMasterList2.add(new SearchItemMaster("444", "555", "111"));
final android.support.v7.widget.SearchView searchView1 = (android.support.v7.widget.SearchView) getView().findViewById(R.id.item_name_edtv);
searchView1.setOnSearchClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
is_click_search_item=true;
is_click_search_group=false;
}
});
searchView1.setOnQueryTextListener(this);
searchView1.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
is_click_search_item=true;
is_click_search_group=false;
}
});
final android.support.v7.widget.SearchView searchView2 = (android.support.v7.widget.SearchView) getView().findViewById(R.id.group_edtv);
searchView2.setOnSearchClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
is_click_search_item=false;
is_click_search_group=true;
}
});
searchView2.setOnQueryTextListener(this);
searchView2.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
is_click_search_item=false;
is_click_search_group=true;
}
});
#Override
public boolean onQueryTextChange(String newText) {
final List<SearchItemMaster> filteredModelList = filter(searchMasterList2, newText);
Log.v("App", newText + ", " + searchMasterList2.size() + ", " + filteredModelList.size());
adapter.animateTo(filteredModelList);
recyclerView.scrollToPosition(0);
return false;
}
private List<SearchItemMaster> filter(List<SearchItemMaster> numbers, String input_text) {
input_text = input_text.toLowerCase();
ArrayList<SearchItemMaster> filteredCompanyList = new ArrayList<>();
for (SearchItemMaster searchItemMaster : numbers) {
if (is_click_search_group) {
final String moblieNo = searchItemMaster.getMoblieNo();
if (moblieNo.contains(input_text)) {
filteredCompanyList.add(searchItemMaster);
}
}
if (is_click_search_item) {
final String code = searchItemMaster.getCode().toLowerCase();
if (code.contains(input_text)) {
filteredCompanyList.add(searchItemMaster);
}
}
}
return filteredCompanyList;
}
You can do it using loop and comparing each item values.
For Ex. if you enter Xyz in name search and 9876 in number then loop like:-
ArrayList<SearchItemMaster> resultArrayList = new ArrayList<>();
for(SearchItemMaster searchItemMasterObj : searchItemMasterList) {
if(searchItemMasterObj.getName().contains("Xyz") && searchItemMasterObj.getNumber().contains("9876")) {
resultArrayList.add(searchItemMasterObj);
}
}
and then you can use resultArrayList to show the result.
hope this will help you. :)
** i changed following code and working fine for me **
ArrayList<SearchItemMaster> searchMasterList2 = new ArrayList<>();
ArrayList<SearchItemMaster> filteredCompanyList1 = new ArrayList<>();
ArrayList<SearchItemMaster> filteredCompanyList2 = new ArrayList<>();
#Override
public boolean onQueryTextChange(String newText) {
if(is_click_search_item){
filteredCompanyList1.clear();
}
if(is_click_search_group){
filteredCompanyList2.clear();
}
final List<SearchItemMaster> filteredModelList = filter(searchMasterList2, newText);
Log.v("App", newText + ", " + searchMasterList2.size() + ", " + filteredModelList.size());
adapter.animateTo(filteredModelList);
recyclerView.scrollToPosition(0);
return false;
}
for (SearchItemMaster searchItemMaster : numbers) {
if (is_click_search_group) {
final String moblieNo = searchItemMaster.getMoblieNo().toLowerCase();;
if (moblieNo.contains(input_text)) {
filteredCompanyList2.add(searchItemMaster);
if(filteredCompanyList1.size()!=0) {
filteredCompanyList.add(searchItemMaster);
filteredCompanyList.retainAll(filteredCompanyList1);
}
else{
filteredCompanyList.add(searchItemMaster);
filteredCompanyList.retainAll(searchMasterList2);
}
}
}
if (is_click_search_item) {
final String code = searchItemMaster.getCode().toLowerCase();
if (code.contains(input_text)) {
filteredCompanyList1.add(searchItemMaster);
if(filteredCompanyList2.size()!=0){
filteredCompanyList.add(searchItemMaster);
filteredCompanyList.retainAll(filteredCompanyList2);
}
else{
filteredCompanyList.add(searchItemMaster);
filteredCompanyList.retainAll(searchMasterList2);
}
}
}
}
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'm inflating dynamic view to linear layout but it displays reversely.
try {
JSONArray jsonArray = new JSONArray(tooteet.getMeasureJson());
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
Measure measureData = new Measure();
measureData.id = jsonObject.optString("id");;
measureData.tooteetId = jsonObject.optString("tooteetId");
measureData.laneId = jsonObject.optString("laneId");
measureData.startDate = jsonObject.optString("startDate");
measureData.endDate = jsonObject.optString("endDate");
measureData.description = jsonObject.optString("text");
measureData.value = jsonObject.optDouble("value");
measureData.measureTypeId = jsonObject.optInt("measureTypeId");
measureData.description = jsonObject.optString("text");
measureData.isTimeSet =jsonObject.optBoolean("isTimeSet");
mMeasureList.add(measureData);
addMeasureView(measureData, i);
}
} catch (Exception e) {
Log.d("FeedMeasure", "Exception: "+e.toString());
}
where i'm getting log value for tooteet.getMeasureJson() is
onCreate -- tooteet.getMeasureJson(): [{"id":"3fb2af41-201d-4aca-9479-42af6cca5947","tooteetId":"3d923a95-d8d8-4478-b336-c995cc77407d","laneId":"00000000-0000-0000-0000-000000000000","value":11111,"text":"","measureTypeId":1,"isTimeSet":false},{"id":"ecab9659-7eb5-417a-8f5e-f769629957ae","tooteetId":"3d923a95-d8d8-4478-b336-c995cc77407d","laneId":"00000000-0000-0000-0000-000000000000","value":22222,"text":"","measureTypeId":1,"isTimeSet":false}]
Here I'm adding measure view using below method
private void addMeasureView(final Measure measure, int position) {
Log.d("ss","adding measure data value ________________"+measure.value+" position __________"+position);
final View parent = getLayoutInflater().inflate(R.layout.view_measure_tooteet_item, mDisplayContainer, false);
final TextView txtDescription, txtValues, txtStartDateTime, txtEndDateTime, labelTaxIncluded, labelTaxColon;
final ImageView imgEdit, imgDelete;
final LinearLayout lnrDescription, lnrStartLayout, lnrEndLayout;
final View mViewDivider;
txtDescription = (TextView) parent.findViewById(R.id.txt_description);
txtValues = (TextView) parent.findViewById(R.id.values);
txtStartDateTime = (TextView) parent.findViewById(R.id.start_date_and_time);
txtEndDateTime = (TextView) parent.findViewById(R.id.end_date_and_time);
mViewDivider = (View) parent.findViewById(R.id.view_divider);
imgEdit = (ImageView) parent.findViewById(R.id.edit);
imgDelete = (ImageView) parent.findViewById(R.id.delete);
lnrDescription = (LinearLayout) parent.findViewById(R.id.lnr_description);
lnrStartLayout = (LinearLayout) parent.findViewById(R.id.lnr_start_layout);
lnrEndLayout = (LinearLayout) parent.findViewById(R.id.lnr_end_layout);
if(tooteet.isOwner(getUserPreference())){
imgDelete.setVisibility(View.VISIBLE);
imgEdit.setVisibility(View.VISIBLE);
}else{
imgDelete.setVisibility(View.GONE);
imgEdit.setVisibility(View.GONE);
}
if(measure.getValue() > 0) {
txtValues.setVisibility(View.VISIBLE);
if (measure.getValue() % 1 == 0) {
txtValues.setText("" + (int) measure.getValue()+ " "+MeasureTypeSelector.getMeasureTypeById(FeedMeasureDetailsActivity.this, measure.getMeasureTypeId()));
} else {
txtValues.setText("" + measure.getValue()+ " "+ MeasureTypeSelector
.getMeasureTypeById(FeedMeasureDetailsActivity.this, measure.getMeasureTypeId()));
}
}else{
txtValues.setVisibility(View.GONE);
}
if(!TextUtils.isEmpty(measure.getDescription())){
lnrDescription.setVisibility(View.VISIBLE);
txtDescription.setText(measure.getDescription());
}
else{
lnrDescription.setVisibility(View.GONE);
}
if(!TextUtils.isEmpty(measure.getStartDate())) {
lnrStartLayout.setVisibility(View.VISIBLE);
txtStartDateTime.setText("" + DateConversion.getDateAndTime(measure.getStartDate(), "MMMM dd, yyyy hh:mm a"));
}
else{
lnrStartLayout.setVisibility(View.GONE);
}
if(!TextUtils.isEmpty(measure.getEndDate())) {
lnrEndLayout.setVisibility(View.VISIBLE);
txtEndDateTime.setText("" + DateConversion.getDateAndTime(measure.getEndDate(), "MMMM dd, yyyy hh:mm a"));
}else{
lnrEndLayout.setVisibility(View.GONE);
}
//
// if(position < mMeasureList.size()){
// mViewDivider.setVisibility(View.VISIBLE);
// }else{
// mViewDivider.setVisibility(View.GONE);
// }
imgDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int pos = (Integer) v.getTag();
AlertDialog.Builder builder = AlertUtils.getBuilder(FeedMeasureDetailsActivity.this);
builder.setTitle(R.string.delete);
builder.setMessage(R.string.delete_tooteet_measure_tuple);
builder.setPositiveButton(R.string.yes_caps, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!BDevice.isInternetConnected(FeedMeasureDetailsActivity.this)) {
AlertUtils.showNetworkAlert(FeedMeasureDetailsActivity.this);
return;
}
final Dialog pd = UiUtils.getSpinnerDialog(FeedMeasureDetailsActivity.this, getString(R.string.loading));
pd.show();
getDairyLineApi().deleteMeasureTooteet(mMeasureList.get(pos).getId(), tooteet.getLaneId(), new ResponseHandler() {
#Override
public void onSuccess(int statusCode, String content) {
dismiss();
AlertDialog.Builder builder = AlertUtils.getBuilder(FeedMeasureDetailsActivity.this);
builder.setMessage(R.string.deleted_successfully);
builder.setPositiveButton(R.string.ok_caps, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mDisplayContainer.removeView(parent);
mMeasureList.remove(pos);
tooteet.setMeasureJson(Measure.getMeasureDetailJSON(mMeasureList));
mTooteetManager.updateMeasureTooteet(tooteet, tooteet.getId());
}
});
builder.create().show();
}
#Override
public void onFailure(int statusCode, String content) {
dismiss();
if (!TextUtils.isEmpty(content)) {
AlertUtils.showAlert(FeedMeasureDetailsActivity.this, content);
}
}
private void dismiss() {
if (pd != null && !isFinishing()) {
pd.dismiss();
}
}
});
}
});
builder.setNegativeButton(R.string.no_caps, null);
builder.create().show();
}
});
imgEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int pos = (Integer) v.getTag();
MeasureTooteetSelector measureTooteetSelector = new MeasureTooteetSelector();
measureTooteetSelector.openMeasureDetailSelector(FeedMeasureDetailsActivity.this, mMeasureList.get(pos),
new MeasureTooteetSelector.OnMeasureDetailSelectListener() {
#Override
public void onMeasureSelect(final Measure measureData) {
if (!BDevice.isInternetConnected(FeedMeasureDetailsActivity.this)) {
AlertUtils.showNetworkAlert(FeedMeasureDetailsActivity.this);
return;
}
final Dialog pd = UiUtils.getSpinnerDialog(FeedMeasureDetailsActivity.this, getString(R.string.loading));
pd.show();
if (measureData != null) {
mMeasureList.set(pos, measureData);
}
getDairyLineApi().updateMeasureTooteet(mMeasureList.get(pos), new ResponseHandler() {
#Override
public void onSuccess(int statusCode, String content) {
dismiss();
AlertDialog.Builder builder = AlertUtils.getBuilder(FeedMeasureDetailsActivity.this);
builder.setMessage(R.string.updated_successfully);
builder.setPositiveButton(R.string.ok_caps, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (measureData != null) {
mMeasureList.set(pos, measureData);
tooteet.setMeasureJson(Measure.getMeasureDetailJSON(mMeasureList));
mTooteetManager.updateMeasureTooteet(tooteet, tooteet.getId());
mActionToSend = ACTION_MEASURE_UPDATE;
if (measureData.getValue() % 1 == 0) {
txtValues.setText("" + (int) measureData.getValue()+ " "+MeasureTypeSelector.getMeasureTypeById(FeedMeasureDetailsActivity.this, measureData.getMeasureTypeId()));
} else {
txtValues.setText("" + measureData.getValue()+ " "+ MeasureTypeSelector
.getMeasureTypeById(FeedMeasureDetailsActivity.this, measureData.getMeasureTypeId()));
}
Log.d("TAG", "measureData.getStartDate(): "+measureData.getStartDate());
if(!TextUtils.isEmpty(measureData.getStartDate()) && !measureData.getStartDate().equalsIgnoreCase("-1")) {
lnrStartLayout.setVisibility(View.VISIBLE);
txtStartDateTime.setText("" + DateConversion.getDateAndTimeWithoutGMT(measureData.getStartDate(), "MMMM dd, yyyy hh:mm a"));
}
else{
lnrStartLayout.setVisibility(View.GONE);
}
Log.d("TAG", "measureData.getEndDate(): "+measureData.getEndDate());
if(!TextUtils.isEmpty(measureData.getEndDate())&& !measureData.getStartDate().equalsIgnoreCase("-1")) {
lnrEndLayout.setVisibility(View.VISIBLE);
txtEndDateTime.setText("" + DateConversion.getDateAndTimeWithoutGMT(measureData.getEndDate(), "MMMM dd, yyyy hh:mm a"));
}else{
lnrEndLayout.setVisibility(View.GONE);
}
if(!TextUtils.isEmpty(measureData.getDescription())){
lnrDescription.setVisibility(View.VISIBLE);
txtDescription.setText(measureData.getDescription());
}
else{
lnrDescription.setVisibility(View.GONE);
}
}
}
});
builder.create().show();
}
#Override
public void onFailure(int statusCode, String content) {
dismiss();
if (!TextUtils.isEmpty(content)) {
AlertUtils.showAlert(FeedMeasureDetailsActivity.this, content);
}
}
private void dismiss() {
if (pd != null && !isFinishing()) {
pd.dismiss();
}
}
});
}
#Override
public void onCancel() {
}
});
}
});
imgEdit.setTag(position);
imgDelete.setTag(position);
addView(parent);
}
My log inside addMeasureView is below:
adding measure data value ________________11111.0 position __________0
adding measure data value ________________22222.0 position __________1
But when i'm viewing this it in layout as this order
adding measure data value ________________22222.0
adding measure data value ________________11111.0
Please suggest me any idea.
This is my model class I'm using for getValue()
import com.kwypesoft.lanes.create_tooteet.LocalTooteetCreator;
import com.kwypesoft.lanes.utils.DateConversion;
import com.kwypesoft.lanes.utils.TextUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.ArrayList;
public class Measure implements Serializable{
// "id": "398627f1-9392-4b3f-8741-903fbcbbd3be",
// "tooteetId": "ab36f69e-a0c8-4f31-aa8d-9b4038a76d57",
// "laneId": "00000000-0000-0000-0000-000000000000",
// "startDate": "2016-04-26T08:00:00",
// "endDate": "2016-04-27T10:00:00",
// "value": 125.6500000000000,
// "measureTypeId": 20
public String id;
public String tooteetId;
public String laneId;
public String startDate;
public String endDate;
public String description;
public double value;
public int measureTypeId;
public boolean isTimeSet;
public Measure() {
}
public Measure(JSONArray jsonArray) {
try {
for(int i =0; i<jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
id = jsonObject.optString("id");
tooteetId = jsonObject.optString("tooteetId");
laneId = jsonObject.optString("laneId");
startDate = jsonObject.optString("startDate");
endDate = jsonObject.optString("endDate");
description = jsonObject.optString("text");
value = jsonObject.optDouble("value");
measureTypeId = jsonObject.optInt("measureTypeId");
isTimeSet = jsonObject.optBoolean("isTimeSet");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public static String getMeasureJSON(ArrayList<LocalTooteetCreator.MeasureData> data) {
JSONArray jsonArray = new JSONArray();
for (LocalTooteetCreator.MeasureData items : data) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("value", items.value);
jsonObject.put("text", items.description);
jsonObject.put("measureTypeId", items.measureTypeId);
if(items.startDate != -1){
jsonObject.put("startDate", DateConversion.getDateWithTFromMilliSeconds(items.startTime, items.startDate));
}
if(items.endDate != -1){
jsonObject.put("endDate", DateConversion.getDateWithTFromMilliSeconds(items.endTime, items.endDate));
}
jsonObject.put("isTimeSet", items.isTimeSet);
jsonArray.put(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonArray.toString();
}
public static String getMeasureDetailJSON(ArrayList<Measure> data) {
JSONArray jsonArray = new JSONArray();
for (Measure items : data) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", items.id);
jsonObject.put("tooteetId", items.tooteetId);
jsonObject.put("laneId", items.laneId);
if(!TextUtils.isEmpty(items.startDate) && !items.getStartDate().equalsIgnoreCase("-1")){
jsonObject.put("startDate", items.startDate);
}
if(!TextUtils.isEmpty(items.endDate) && !items.getStartDate().equalsIgnoreCase("-1")){
jsonObject.put("endDate", items.endDate);
}
jsonObject.put("text", items.description);
jsonObject.put("value", items.value);
jsonObject.put("measureTypeId", items.measureTypeId);
jsonObject.put("isTimeSet", items.isTimeSet);
jsonArray.put(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonArray.toString();
}
public String getId() {
return id;
}
public String getTooteetId() {
return tooteetId;
}
public String getLaneId() {
return laneId;
}
public String getStartDate() {
return startDate;
}
public String getEndDate() {
return endDate;
}
public double getValue() {
return value;
}
public int getMeasureTypeId() {
return measureTypeId;
}
public boolean getIsTimeSet() {
return isTimeSet;
}
public String getDescription() {
return description;
}
public boolean isTimeSet() {
return isTimeSet;
}
}
Hi I have done a mistake in addview method. Before my addview method is
mDisplayContainer.addView(view, mDisplayContainer.getChildCount() - 1);
Now i changed
mDisplayContainer.addView(view);
Its Working for me. Thank u so much for your comments