I'm facing an issue with my viewpager2 adapter. The adapter contains a share button which starts an new activity with a create chooser Intent. The problem is if swipe down or press the android back button the current item layout is flattened or sometime it changes the current item to the next one.
However if go through the sharing process completely the app works fine.
ViewPager2.JAVA*
public class StreamPostDetailAdapter extends RecyclerView.Adapter<StreamPostDetailAdapter.TestPagerViewHolder> {
public Context mContext;
public List<Post> mPost;
private FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
String mUid ;
public IpagerAdapter mListener;
private CommentAdapter commentAdapter;
private List<Comment> commentList;
public StreamPostDetailAdapter(Context mContext, List<Post> mPost, IpagerAdapter mListener) {
this.mListener = mListener;
this.mContext = mContext;
this.mPost = mPost;
mUid = firebaseUser.getUid();
}
#NonNull
#Override
public TestPagerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_post_swipe_item, parent, false);
return new TestPagerViewHolder(view,mListener);
}
#Override
public void onBindViewHolder(#NonNull TestPagerViewHolder holder, int position) {
Post post = mPost.get(holder.getBindingAdapterPosition());
String post_publisher = post.getPublisher();
String post_id = post.getPostid() ;
String post_image = post.getPostimage() ;
String post_timeStamp = post.getTimestamp();
String tag_list = post.getTagList();
String postTitle = post.getDescription();
boolean personal = post.getPersonal_tattoo();
commentList = new ArrayList<>();
commentAdapter = new CommentAdapter(mContext,commentList);
GlideApp.with(mContext).load(post_image)
.placeholder(R.mipmap.loading_img_placeholder)
.into(holder.image_post);
holder.title.setText(post.getDescription());
if (post.getTagList().equals("")) {
holder.tagList.setVisibility(View.GONE);
} else {
holder.tagList.setVisibility(View.VISIBLE);
holder.tagList.setText(post.getTagList());
}
holder.comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.bsCommentsController(post_id, holder.commentRv);
BottomSheetBehavior.from(holder.bsComments).setState(BottomSheetBehavior.STATE_EXPANDED);
}
});
holder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.like.getTag().equals("like")) {
FirebaseDatabase.getInstance().getReference().child("Likes")
.child(post_id)
.child(mUid).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Likes")
.child(post_id)
.child(mUid).removeValue();
}
}
});
holder.image_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", Context.MODE_PRIVATE).edit();
editor.putString("id", post_publisher);
editor.apply();
Intent intent = new Intent(mContext,HomeActivity.class);
intent.putExtra("origin","ViewPager");
mContext.startActivity(intent);
((StreamPostDetailActivity)mContext).finish();
}
});
holder.save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mContext instanceof SavedPostActivity) {
mListener.removePost(post_id,post_image,position);
}
if (holder.save.getTag().equals("save")) {
FirebaseDatabase.getInstance().getReference().child("Saved").child(firebaseUser.getUid())
.child(post_id).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Saved").child(firebaseUser.getUid())
.child(post_id).removeValue();
}
}
});
holder.share_post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BitmapDrawable drawable = (BitmapDrawable)holder.image_post.getDrawable();
Bitmap bitmap = drawable.getBitmap();
String path = MediaStore.Images.Media.insertImage(mContext.getContentResolver(), bitmap, UUID.randomUUID().toString() + ".jpeg", "drawing");
Uri uri = Uri.parse(path);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM,uri);
intent.putExtra(Intent.EXTRA_TEXT, "Playstore Link : put app link in store ");
mContext.startActivity(Intent.createChooser(intent,"Share2"));
}
});
if (mContext instanceof SearchTattooDetailsActivity) {
holder.btn_post_options.setVisibility(View.GONE);
}else {
holder.btn_post_options.setVisibility(View.VISIBLE);
holder.btn_post_options.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showMoreOptions(holder.btn_post_options, post_publisher, mUid, post_id, post_image, position, postTitle
, tag_list, personal);
}
});
}
// Add a new comment
holder.sendComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!holder.comment_bar_edt.getText().toString().equals("")){
mListener.addComment(post_id, holder.comment_bar_edt.getText().toString());
holder.comment_bar_edt.setText("");
holder.comment_bar_edt.clearFocus();
}
}
});
holder.commentRv.setHasFixedSize(true);
holder.commentRv.setAdapter(commentAdapter);
}
#Override
public int getItemCount() {
return mPost.size();
}
private void showMoreOptions(ImageButton btn_post_options, String post_publisher, String mUid, String post_id, String post_image,int posItem, String postTitle, String tagList, boolean personal) {
PopupMenu popupMenu = new PopupMenu(mContext,btn_post_options, Gravity.END);
if (!post_publisher.equals(mUid)) {
popupMenu.getMenu().add(Menu.NONE,0,0,"Report post");
}
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
if (id == 0){
Toast.makeText(mContext, "CreateReportPost/UserNewCategoryRequestEmail", Toast.LENGTH_SHORT).show();
} else if (id == 1) {
//not working
Intent intentEdit = new Intent(mContext, EditPostActivity.class);
intentEdit.putExtra("title",postTitle);
intentEdit.putExtra("imageUrl", post_image);
intentEdit.putExtra("tagList", tagList );
intentEdit.putExtra("personal", personal );
intentEdit.putExtra("postId", post_id);
intentEdit.putExtra("posEditedPost", posItem);
((Activity)mContext).finish();
mContext.startActivity(intentEdit);
}
return false;
}
});
popupMenu.show();
}
//View Holder Class
public static class TestPagerViewHolder extends RecyclerView.ViewHolder {
public ImageView image_profile, image_post, like, comment, save,share_post;
public TextView username, likes, comments, title, time,tagList;
public ImageButton btn_post_options;
public IpagerAdapter mListener;
//Comments Bottom sheet
EditText comment_bar_edt;
public RecyclerView commentRv ;
ImageView sendComment,userImgComment;
public ConstraintLayout bsComments;
public LinearLayoutManager layoutManager;
public TestPagerViewHolder(#NonNull View itemView, IpagerAdapter mListener) {
super(itemView);
this.mListener = mListener;
image_post = itemView.findViewById(R.id.post_image);
image_profile = itemView.findViewById(R.id.image_profile);
like = itemView.findViewById(R.id.like_ic);
share_post= itemView.findViewById(R.id.share_post);
comment = itemView.findViewById(R.id.comment_ic);
save = itemView.findViewById(R.id.save);
username = itemView.findViewById(R.id.username);
likes = itemView.findViewById(R.id.likes);
comments = itemView.findViewById(R.id.comments);
tagList = itemView.findViewById(R.id.tagList);
title = itemView.findViewById(R.id.title);
time = itemView.findViewById(R.id.time);
btn_post_options = itemView.findViewById(R.id.post_options);
bsComments= itemView.findViewById(R.id.bsComments);
comment_bar_edt = itemView.findViewById(R.id.comment_bar_edt);
sendComment = itemView.findViewById(R.id.sendComment);
commentRv = itemView.findViewById(R.id.comments_rv);
BottomSheetBehavior.from(bsComments).setState(BottomSheetBehavior.STATE_HIDDEN);
}
}
public interface IpagerAdapter {
void removePost(String post_id, String post_image, int position);
void bsCommentsController(String post_id, RecyclerView commentRecyclerView);
void addComment(String post_id,String comment_txt);
}
public void removeItem(int position) {
if (position > -1 && position < mPost.size()) {
mPost.remove(position);
notifyDataSetChanged();
notifyItemRemoved(position);
}
}
}
#Francis,
Since It has been a while, I just remember that I've made changes in how I handled the BottomSheet which was containing the Comments RecyclerView. I extracted it from the StreamPostDetailAdapter (ViewPager2) and moved it to the corresponding activity. Therefore I have only one BottomSheet for all viewpager2 items. Then recyclerView data (comments fetch from firebase) is updated using interface listener methods to populate each items.
You will find the code of the ViewPager2 below:
public class StreamPostDetailAdapter extends RecyclerView.Adapter<StreamPostDetailAdapter.TestPagerViewHolder> {
public Context mContext;
public List<Post> mPost;
private FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
String mUid ;
public IpagerAdapter mListener;
private CommentAdapter commentAdapter;
private List<Comment> commentList;
public StreamPostDetailAdapter(Context mContext, List<Post> mPost, IpagerAdapter mListener) {
this.mListener = mListener;
this.mContext = mContext;
this.mPost = mPost;
mUid = firebaseUser.getUid();
}
#NonNull
#Override
public TestPagerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_post_swipe_item, parent, false);
return new TestPagerViewHolder(view,mListener);
}
#Override
public void onBindViewHolder(#NonNull TestPagerViewHolder holder, int position) {
Post post = mPost.get(holder.getBindingAdapterPosition());
String post_publisher = post.getPublisher();
String post_id = post.getPostid() ;
String post_image = post.getPostimage() ;
String post_timeStamp = post.getTimestamp();
String tag_list = post.getTagList();
String postTitle = post.getDescription();
boolean personal = post.getPersonal_tattoo();
GlideApp.with(mContext).load(post_image)
.placeholder(R.mipmap.loading_img_placeholder)
.into(holder.image_post);
holder.title.setText(post.getDescription());
if (post.getTagList().equals("")) {
holder.tagList.setVisibility(View.GONE);
} else {
holder.tagList.setVisibility(View.VISIBLE);
holder.tagList.setText(post.getTagList());
}
publisherInfo(holder.image_profile, holder.username, post_publisher);
asLiked(post_id, holder.like);
nLikes(holder.likes, post_id);
//getComments(post_id, holder.comments);
isSaved(post_id, holder.save);
getTimeAgo(holder.time, post_timeStamp);
holder.comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.openBsComment();
}
});
holder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.like.getTag().equals("like")) {
FirebaseDatabase.getInstance().getReference().child("Likes")
.child(post_id)
.child(mUid).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Likes")
.child(post_id)
.child(mUid).removeValue();
}
}
});
holder.image_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", Context.MODE_PRIVATE).edit();
editor.putString("id", post_publisher);
editor.apply();
Intent intent = new Intent(mContext,HomeActivity.class);
intent.putExtra("origin","ViewPager");
mContext.startActivity(intent);
((StreamPostDetailActivity)mContext).finish();
}
});
holder.save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mContext instanceof SavedPostActivity) {
mListener.removePost(post_id,post_image,position);
}
if (holder.save.getTag().equals("save")) {
FirebaseDatabase.getInstance().getReference().child("Saved").child(firebaseUser.getUid())
.child(post_id).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Saved").child(firebaseUser.getUid())
.child(post_id).removeValue();
}
}
});
holder.share_post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BitmapDrawable drawable = (BitmapDrawable)holder.image_post.getDrawable();
Bitmap bitmap = drawable.getBitmap();
mListener.sharePost(bitmap);
}
});
if (mContext instanceof TaggedTattooDetailsActivity) {
holder.btn_post_options.setVisibility(View.GONE);
}else {
holder.btn_post_options.setVisibility(View.VISIBLE);
holder.btn_post_options.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showMoreOptions(holder.btn_post_options, post_publisher, mUid, post_id, post_image, position, postTitle
, tag_list, personal);
}
});
}
// Add a new comment
}
#Override
public int getItemCount() {
return mPost.size();
}
private void showMoreOptions(ImageButton btn_post_options, String post_publisher, String mUid, String post_id, String post_image,int posItem, String postTitle, String tagList, boolean personal) {
PopupMenu popupMenu = new PopupMenu(mContext,btn_post_options, Gravity.END);
if (!post_publisher.equals(mUid)) {
popupMenu.getMenu().add(Menu.NONE,0,0,"Report post");
}
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
if (id == 0){
Toast.makeText(mContext, "CreateReportPost/UserNewCategoryRequestEmail", Toast.LENGTH_SHORT).show();
} else if (id == 1) {
//not working
Intent intentEdit = new Intent(mContext, EditPostActivity.class);
intentEdit.putExtra("title",postTitle);
intentEdit.putExtra("imageUrl", post_image);
intentEdit.putExtra("tagList", tagList );
intentEdit.putExtra("personal", personal );
intentEdit.putExtra("postId", post_id);
intentEdit.putExtra("posEditedPost", posItem);
((Activity)mContext).finish();
mContext.startActivity(intentEdit);
}
return false;
}
});
popupMenu.show();
}
//View Holder Class
public static class TestPagerViewHolder extends RecyclerView.ViewHolder {
public ImageView image_profile, image_post, like, comment, save,share_post;
public TextView username, likes, comments, title, time,tagList;
public ImageButton btn_post_options;
public IpagerAdapter mListener;
//Comments Bottom sheet
public LinearLayoutManager layoutManager;
public TestPagerViewHolder(#NonNull View itemView, IpagerAdapter mListener) {
super(itemView);
this.mListener = mListener;
image_post = itemView.findViewById(R.id.post_image);
image_profile = itemView.findViewById(R.id.image_profile);
like = itemView.findViewById(R.id.like_ic);
share_post= itemView.findViewById(R.id.share_post);
comment = itemView.findViewById(R.id.comment_ic);
save = itemView.findViewById(R.id.save);
username = itemView.findViewById(R.id.username);
likes = itemView.findViewById(R.id.likes);
comments = itemView.findViewById(R.id.comments);
tagList = itemView.findViewById(R.id.tagList);
title = itemView.findViewById(R.id.title);
time = itemView.findViewById(R.id.time);
btn_post_options = itemView.findViewById(R.id.post_options);
}
}
public interface IpagerAdapter {
void removePost(String post_id, String post_image, int position);
void openBsComment();
void sharePost(Bitmap postImage);
}
private void getComments(String postid, TextView comments) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Comments").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.getChildrenCount() != 0) {
comments.setText(" " + snapshot.getChildrenCount());
} else {
comments.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void getTimeAgo(TextView time, String stamp_post) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");;
Log.i(TAG, "timestamp value in format date: "+ stamp_post);
try {
long timeStamp = sdf.parse(stamp_post).getTime();
long now = System.currentTimeMillis();
CharSequence ago = DateUtils.getRelativeTimeSpanString(timeStamp, now, DateUtils.MINUTE_IN_MILLIS);
Log.i(TAG, "timestamp milli value is: " + timeStamp);
time.setText(ago);
} catch (ParseException e) {
e.printStackTrace();
}
}
private void asLiked(String postid, final ImageView imageView) {
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Likes").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.child(firebaseUser.getUid()).exists()) {
imageView.setImageResource(R.drawable.liked);
imageView.setTag("liked");
} else {
imageView.setImageResource(R.drawable.ic_like);
imageView.setTag("like");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void nLikes(final TextView likes, String postid) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Likes").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
likes.setText(" "+ snapshot.getChildrenCount());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void isSaved(String postid, final ImageView imageView) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Saved").child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.child(postid).exists()) {
imageView.setImageResource(R.drawable.ic_bookmark_colored);
imageView.setTag("saved");
} else {
imageView.setImageResource(R.drawable.ic_save_post);
imageView.setTag("save");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void publisherInfo(ImageView image_profile, TextView username, String userid) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("App_users")
.child(userid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
Glide.with(mContext.getApplicationContext()).load(user.getimageUrl()).into(image_profile);
username.setText(user.getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
public void removeItem(int position) {
if (position > -1 && position < mPost.size()) {
mPost.remove(position);
notifyDataSetChanged();
notifyItemRemoved(position);
}
}
}
I am trying to experiment and learn BuilderPattern,reading from json file at the same time. My goal is to create object using the data I get from the json file. This is how the json file looks like:
[{
"firstName": "Git",
"lastName": "Hub",
"website": "howtodoinjava.com"
},
{
"firstName": "Brian",
"lastName": "Schultz"
}
]
Class1: Employee Class
public class Employee {
private String firstName; // required
private String lastName; // required
private String website; // optional
//Only has setters
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setWebsite(String website) {
this.website = website;
}
//no public constructor. So the only way to get a Employee object is through the EmployeeBuilder class.
private Employee(EmployeeBuilder builder) {
this.firstName = firstName;
this.lastName = lastName;
this.website = website;
}
public static class EmployeeBuilder {
private String firstName; // required
private String lastName; // required
private String website; // optional
public EmployeeBuilder() throws IOException {
}
public EmployeeBuilder requiredFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public EmployeeBuilder requiredLastName(String lastName) {
this.lastName = lastName;
return this;
}
public EmployeeBuilder optionalWebsite(String website) {
this.website = website;
return this;
}
//Return the finally constructed User object
public Employee build() {
Employee emp = new Employee(this);
return emp;
}
}
}
Class2: User Class
public class User {
String firstName;
String lastName;
String website;
//Using Getters to get values from Json
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getWebsite() {
return website;
}
}
3 Main class
public class Main {
public static void main(String[] args) throws IOException {
ObjectMapper object = new ObjectMapper();
User[] user = object.readValue(new File("C:\\MyTemp\\jackson.json"), User[].class);
//Employee employee= new Employee.EmployeeBuilder().requiredFirstName(person.getFirstName()).requiredLastName(person.getLastName()).optionalWebsite(person.getWebsite()).build();
List<User> emp1 = object.readValue("C:\\MyTemp\\jackson.json", new TypeReference<List<User>>() {});
emp1.stream().forEach(x -> System.out.println(x));
/*for (User person : user) {
Employee employee= new Employee.EmployeeBuilder().requiredFirstName(person.getFirstName()).build();
System.out.println(employee);
} */
}
}
Problem: When I run this code all I get are the 1st names. Git and Brian. I am not getting the last names or website.
Can someone please suggest what am I missing? Thanks in advance for your time.
Json response with api URLhttp://192.168.0.19:2000/api/userprofile?phone=0722931069&Password=1111
{
"Username":"abel",
"ProfileId":"746737",
"Password":"1111",
"SaccaUssdId":"3728282",
"PaybillNo":"74883",
"Phonenumber":"0722931069",
"CustomerType":"d",
"RegistrationDate":"2005-12-09T00:00:00",
"TimeStamp":"2005-12-09T00:00:00",
"PreferredModeOfComm":"phonecall",
"APIURL":"hhh",
"APIUsername":"kplDL",
"APIPassword":"JKSDjic"
}
Here is my POJO class, PLease help sort out this issue
public class Fetchnumber {
private String Username;
private String ProfileId;
private String Password;
private String SaccaUssdId;
private String PaybillNo;
private String Phonenumber;
private String CustomerType;
private String RegistrationDate;
private String TimeStamp;
private String PreferredModeOfComm;
private String APIURL;
private String APIUsername;
private String APIPassword;
public Fetchnumber(String username, String profileId, String password, String saccaUssdId, String paybillNo, String phonenumber, String customerType, String registrationDate, String timeStamp, String preferredModeOfComm, String APIURL, String APIUsername, String APIPassword) {
this.Username = username;
this.ProfileId = profileId;
this.Password = password;
this.SaccaUssdId = saccaUssdId;
this.PaybillNo = paybillNo;
this.Phonenumber = phonenumber;
this.CustomerType = customerType;
this.RegistrationDate = registrationDate;
this.TimeStamp = timeStamp;
this.PreferredModeOfComm = preferredModeOfComm;
this.APIURL = APIURL;
this.APIUsername = APIUsername;
this.APIPassword = APIPassword;
}
public String getUsername() {
return Username;
}
public String getProfileId() {
return ProfileId;
}
public String getPassword() {
return Password;
}
public String getSaccaUssdId() {
return SaccaUssdId;
}
public String getPaybillNo() {
return PaybillNo;
}
public String getPhonenumber() {
return Phonenumber;
}
public String getCustomerType() {
return CustomerType;
}
public String getRegistrationDate() {
return RegistrationDate;
}
public String getTimeStamp() {
return TimeStamp;
}
public String getPreferredModeOfComm() {
return PreferredModeOfComm;
}
public String getAPIURL() {
return APIURL;
}
public String getAPIUsername() {
return APIUsername;
}
public String getAPIPassword() {
return APIPassword;
}
}
`Please help me, I am using retrofit2 library and Pinview and mobile number to authenticate users but as soon as I finish keying in pin, the app listens to pin key in.
Here is how I have declared base url and method that takes two parameters to be queried
String BASE_URL="http://192.168.0.19:2000/";
#GET("api/userprofile")
Call<Fetchnumber> getNumbers(#Query("phone" ) String phone, #Query("Password") String Password);
Here is the error I get in Logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String e.uzer.msacco.Fetchnumber.getPassword()' on a null object reference
at e.uzer.msacco.UserLogin$1$1.onDataEntered(UserLogin.java:49)
at com.goodiebag.pinview.Pinview.onTextChanged(Pinview.java:406)
at android.widget.TextView.sendOnTextChanged(TextView.java:8320)
at android.widget.TextView.handleTextChanged(TextView.java:8385)
at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:10531)
Here is The retrofit library that shows how i have passed two parameters to the method getnumbers
Retrofit retrofit = new Retrofit.Builder().baseUrl(Api.BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
Api api = retrofit.create(Api.class);
Call<Fetchnumber> call = api.getNumbers(phonenumbersubmission.phone_number.getText().toString(),pinview.getValue().toString().trim());
call.enqueue(new Callback<Fetchnumber>() {
Here is how i have handled Onresponse
public void onResponse(Call<Fetchnumber> call, final Response<Fetchnumber> response) {
pinview.setPinViewEventListener(new Pinview.PinViewEventListener() {
#Override
public void onDataEntered(Pinview pinview, boolean b) {
if ((response.body().getPassword().equals(pinview.getValue().toString())&&( response.body().getPhonenumber().toString().equals(phonenumbersubmission.phone_number.toString())))) {
Toast.makeText(UserLogin.this, "Login successful", Toast.LENGTH_LONG).show();
Intent intent = new Intent(UserLogin.this, enrollment.class);
startActivity(intent);
} else {
Toast.makeText(UserLogin.this, "Wrong PIN", Toast.LENGTH_LONG).show();
Where getPassword and getPhonenumber() are from POJO class.
Any help will be much appreciated,
Thank you in andvance.
Add #SerializedName annotation to all the fields in your pojo class with respective key names from your json response. it should be like
public class Example {
#SerializedName("Username")
#Expose
private String username;
#SerializedName("ProfileId")
#Expose
private String profileId;
#SerializedName("Password")
#Expose
private String password;
#SerializedName("SaccaUssdId")
#Expose
private String saccaUssdId;
#SerializedName("PaybillNo")
#Expose
private String paybillNo;
#SerializedName("Phonenumber")
#Expose
private String phonenumber;
#SerializedName("CustomerType")
#Expose
private String customerType;
#SerializedName("RegistrationDate")
#Expose
private String registrationDate;
#SerializedName("TimeStamp")
#Expose
private String timeStamp;
#SerializedName("PreferredModeOfComm")
#Expose
private String preferredModeOfComm;
#SerializedName("APIURL")
#Expose
private String aPIURL;
#SerializedName("APIUsername")
#Expose
private String aPIUsername;
#SerializedName("APIPassword")
#Expose
private String aPIPassword;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getProfileId() {
return profileId;
}
public void setProfileId(String profileId) {
this.profileId = profileId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSaccaUssdId() {
return saccaUssdId;
}
public void setSaccaUssdId(String saccaUssdId) {
this.saccaUssdId = saccaUssdId;
}
public String getPaybillNo() {
return paybillNo;
}
public void setPaybillNo(String paybillNo) {
this.paybillNo = paybillNo;
}
public String getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
}
public String getCustomerType() {
return customerType;
}
public void setCustomerType(String customerType) {
this.customerType = customerType;
}
public String getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(String registrationDate) {
this.registrationDate = registrationDate;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getPreferredModeOfComm() {
return preferredModeOfComm;
}
public void setPreferredModeOfComm(String preferredModeOfComm) {
this.preferredModeOfComm = preferredModeOfComm;
}
public String getAPIURL() {
return aPIURL;
}
public void setAPIURL(String aPIURL) {
this.aPIURL = aPIURL;
}
public String getAPIUsername() {
return aPIUsername;
}
public void setAPIUsername(String aPIUsername) {
this.aPIUsername = aPIUsername;
}
public String getAPIPassword() {
return aPIPassword;
}
public void setAPIPassword(String aPIPassword) {
this.aPIPassword = aPIPassword;
}
}
Perhaps someone here can give me a tip where the error could be situated (JSF 2.2, Glassfish 4.0):
I have two entities with a manytomany relation (see example)
When I deploy my project in glassfish all tables (also the linking table) are generated correctly (create-tables enabled in persistence.xml): TAGUSERWISH, TAGUSERWISH_WISH (linking table), WISH
When I execute a persist (see example) entity "wish" and "tagUserWish" is persisted correctly, but nothing is written into the linking table when I look directly into the mysql table. But when I read "wish" out with JPA, the List<TagUserWish> is filled
As soon as a new session starts (redeploy) List<TagUserWish> is also empty when read out with JPA
Owner entity:
#Entity
public class Wish implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String subject;
private String abstractT;
#OneToOne
private User user;
#ManyToMany(mappedBy = "wishes", cascade = {CascadeType.ALL} )
private List<TagUserWish> tags = new LinkedList<>();
public void addTag(TagUserWish tag){
tags.add(tag);
}
public void setTags(List<TagUserWish> tags) {
this.tags = tags;
}
public void removeTag(TagUserWish tag){
tags.remove(tag);
}
public List<TagUserWish> getTags(){
return tags;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getAbstractT() {
return abstractT;
}
public void setAbstractT(String abstractT) {
this.abstractT = abstractT;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Wish)) {
return false;
}
Wish other = (Wish) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "eu.citato.main.model.Wish[ id=" + id + " ]";
}
}
Entity 2:
#Entity
public class TagUserWish implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public TagUserWish() {
}
public TagUserWish(String name) {
this.name = name;
}
#ManyToMany
private List<Wish> wishes = new LinkedList<>();
public void addWish(Wish wish){
wishes.add(wish);
}
public void setWishes(List<Wish> wishes) {
this.wishes = wishes;
}
public void removeWish(Wish tag){
wishes.remove(tag);
}
public List<Wish> getWishes(){
return wishes;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof TagUserWish)) {
return false;
}
TagUserWish other = (TagUserWish) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "eu.citato.main.model.Tag[ id=" + id + ", name="+name+" ]";
}
}
How I persist it:
#javax.inject.Named
#SessionScoped
public class WishPM implements Serializable {
#EJB
private WishService wls;
public void commitEditWish(){
List<TagUserWish> selTags = new ArrayList<>();
selTags.add(new TagUserWish("Tag1"));
selTags.add(new TagUserWish("Tag2"));
currentWish = new Wish();
currentWish.setSubject("wishSubject");
currentWish.setAbstractT("wishAbstract");
currentWish.setTags(selTags);
wls.createWish(currentWish);
}
}
And the wish Service:
#Stateless
public class WishService implements Serializable{
#PersistenceContext(unitName = "WishlistPU")
private EntityManager em;
public void createWish(Wish entity){
em.persist(entity);
}
}
Relationships are persisted based to the owner side of relationship. Owner of the bidirectional relationship is one that is value of mappedBy in inverse side. In following case owner of the relationship is wishes field in TagUserWish entity
#ManyToMany(mappedBy = "wishes", cascade = {CascadeType.ALL} )
private List<TagUserWish> tags = new LinkedList<>();
Because instance of TagUserWish do have empty wishes collection, relationship is not persisted. Problem can be solved by adding related Wish to the instance of TagUserWish, for example as follows:
...
TagUserWish tuw1 = new TagUserWish("Tag1")
TagUserWish tuw2 = new TagUserWish("Tag2")
selTags.add(tuw1);
selTags.add(tuw2);
currentWish = new Wish();
tuw1.addWish(currentWish); //setting to owner side of relationship
tuw2.addWish(currentWish); //setting to owner side of relationship
...
I am getting JSON String data like
{"username":"KU","password":"KU"}.
How to convert this string to JAXBElement object.
Please give me answer.
You can use Jackson to unmarshal JSON easily. See the code below for your username and password case above. It outputs the following to the console console showing it has created an instance of the class from the JSON string.
{"username":"KU","password":"KU"} -> Username [KU], Password [KU].
import org.codehaus.jackson.map.ObjectMapper;
public class JaxbTest {
public static void main(String[] args) throws Throwable {
String json = "{\"username\":\"KU\",\"password\":\"KU\"}";
ObjectMapper mapper = new ObjectMapper();
JavaObject javaObject = mapper.readValue(json, JavaObject.class);
System.out.println(json + " -> " + javaObject.toString());
}
private static class JavaObject {
private String username;
private String password;
public JavaObject() { }
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "Username [" + this.username + "], Password [" + this.password + "]";
}
}
}