Get cardview data to another activity with swipe - java

I want to get data of card on right swipe and on left i want to remove it from list but not to delete it from firebase how can i achieve it ? Here is my code
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
if(direction==ItemTouchHelper.RIGHT)
{
Toast.makeText(home.this, uplodinfo2.getBreed() +"/"+ uplodinfo2.getPrice()+"Right Swipe", Toast.LENGTH_SHORT).show();
}
if(direction==ItemTouchHelper.LEFT)
{
}
}
};
protected void onStart()
{ super.onStart();
FirebaseRecyclerAdapter<PetData,PetAdapter> firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<PetData, PetAdapter>(PetData.class,R.layout.swipelayout,PetAdapter.class,query) {
#Override
protected void populateViewHolder(PetAdapter categoryviewHoder, final PetData uplodinfo, int i) {
uplodinfo2=uplodinfo;
categoryviewHoder.setDetail(getApplicationContext(),"Price: " + uplodinfo.getPrice() + "$","Breed Name: "+uplodinfo.getBreed(),uplodinfo.getImageUrl());
msg= uplodinfo.getName();
// txtcat.setText(Category);
categoryviewHoder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(home.this,rightview.class);
startActivity(i);
}
});
}
};
recyclerHome.setAdapter(firebaseRecyclerAdapter);
}

Related

Pass username to another activity with RewardedAd

The problem is that I am trying to pass the name of the user when the adReward is complete to another activity. But I'm stuck in this activity, even though the video ad is loaded. (and it works well while there are no video ad to show). Here is my code:
My java.class
public class TheDay1 extends AppCompatActivity implements RewardedVideoAdListener {
Vibrator vibrator;
private RewardedVideoAd HDay1;
int currentActivity = 0;
boolean flag;
private EditText vname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_day1);
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
MobileAds.initialize(this,
"ca-app-pub-3940256099942544/6300978111");
///ADD BAN
AdView mAdView = findViewById(R.id.banner1);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
///////////////////////////////////
//VIDEO
HDay1 = MobileAds.getRewardedVideoAdInstance(this);
HDay1.setRewardedVideoAdListener(this);
loadRewardedVideoDAY1();
vname = findViewById(R.id.name);
final ImageView nm = findViewById(R.id.ID);
nm.setVisibility(View.INVISIBLE);
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
nm.setColorFilter(filter);
final Button closeAd = findViewById(R.id.closeDay1);
closeAd.setVisibility(View.INVISIBLE);
///////////////////////////////////////////////////////////////////////////////////////////
closeAd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
vibrator.vibrate(50);
loadRewardedVideoDAY1();
if (HDay1.isLoaded()) {
HDay1.show();
setCurrent(1);
}
String name = vname.getText().toString();
getusername(name);
}
});
}
////////////////////////////////////////////////////////////////
private void Day1() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
private void getusername(String name) {
Intent intent = new Intent(this, ActivityTwo.class);
Resources resources = getResources();
String key = resources.getString(R.string.key_name);
intent.putExtra(key, name);
startActivity(intent);
}
private void loadRewardedVideoDAY1() {
if (!HDay1.isLoaded()) {
HDay1 = null;
HDay1 = MobileAds.getRewardedVideoAdInstance(this);
HDay1.setRewardedVideoAdListener(this);
///////////////TEST ID//////////////////
HDay1.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());
}
}
#Override
public void onRewardedVideoAdLoaded() {
Log.d("LOADED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoAdOpened() {
Log.d("OPENED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoStarted() {
Log.d("STARTED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoDAY1();
if (currentActivity == 1) {
Day1();
}
}
#Override
public void onRewarded(RewardItem rewardItem) {
loadRewardedVideoDAY1();
flag = true;
if (currentActivity == 1) {
Day1();
}
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
#Override
public void onRewardedVideoCompleted() {
}
#Override
protected void onPause() {
HDay1.pause(this);
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
public void setCurrent(int val){
currentActivity = val;
}
Any idea what the problem could be? Thanks in advance
Try below code. Update ProcessData with your intent logic and update oncreate with other data required in your class
public class TheDay1 extends AppCompatActivity implements RewardedVideoAdListener {
private RewardedVideoAd mRewardedVideoAd;
private Boolean bRewardVideo = false;
#Override
public void onResume() {
super.onResume();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.resume(this);
}
}
#Override
public void onPause() {
super.onPause();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.pause(this);
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.destroy(this);
}
}
#Override
public void onRewardedVideoCompleted() {
//Toast.makeText(this, "onRewardedVideoCompleted", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdLoaded() {
//Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdOpened() {
//Toast.makeText(this, "onRewardedVideoAdOpened", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoStarted() {
//Toast.makeText(this, "onRewardedVideoStarted", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdClosed() {
//Toast.makeText(this, "Reward Video Closed", Toast.LENGTH_SHORT).show();
// Load the next rewarded video ad.
if (bRewardVideo) {
ProcessData();
} else {
Toast.makeText(this, "Please View Reward Video to get Reward Points", Toast.LENGTH_LONG).show();
}
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
Toast.makeText(this, "Now you can close Ad to Process", Toast.LENGTH_LONG).show();
bRewardVideo = true;
}
#Override
public void onRewardedVideoAdLeftApplication() {
//Toast.makeText(this, "onRewardedVideoAdLeftApplication",Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
Toast.makeText(this, "Fail to Load Reward Video. Please try again!", Toast.LENGTH_SHORT).show();
}
private void loadRewardedVideoAd() {
bRewardVideo = false;
mRewardedVideoAd.loadAd(BuildConfig.REWARDVIDEOID,
new AdRequest.Builder().build());
}
private void ProcessData() {
Snackbar.make(findViewById(R.id.drawer_layout_law), "Please wait while we process the request... ", Snackbar.LENGTH_INDEFINITE).show();
//WRITE YOUR INTENT CODE HERE
Intent intent = new Intent(this, ActivityTwo.class);
Resources resources = getResources();
String key = resources.getString(R.string.key_name);
intent.putExtra(key, name);
startActivity(intent);
}
private void ShowRewardVideoDialog() {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
} else {
loadRewardedVideoAd();
Toast.makeText(mctx, "Fail to Load Reward Video : Please try again", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
}
}

Recyclerview load more lost item click when scrolling

I have a problem with Recyclerview item click. I fetch data to list() method and add via addItem() method in recyclerview custom adapter when scroll down in addOnScrollListener. I get item position with click interface on Fragment. First fetch data work perfectly but when fetch loadmore, can't retrive item positon to new data with onButtonLClick() method.
// in onBindViewHolder;
holder.lnl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
rcylviewItemNotify.onButtonLClick(position);
}catch (Throwable e){
//interface can be null
}
}
});
// addItem() method in adapter;
public void addItem(List<Image> img) {
for (Image im : img) {
arrayList.add(im);
}
notifyDataSetChanged();
}
// interface code;
public interface RcylviewItemNotify {
void onButtonLClick(int position);
}
// in Fragment code;
public void list() {
GetServices service = RetrofitInstance.getRetrofitInstance().create(GetServices.class);
Call<Images> call = service.getImages();
call.enqueue(new Callback<Images>() {
#Override
public void onResponse(Call<Images> call, Response<Images> response) {
Images body = response.body();
records = body.getImages();
adapter.addItem(records);
}
#Override
public void onFailure(Call<Images> call, Throwable t) {
Toast.makeText(getActivity(), "Network hatası onFailure", Toast.LENGTH_SHORT).show();
reflesh.setRefreshing(false);
}
});
}
#Override
public void onButtonLClick(int position) {
final String clickId = String.valueOf(records.get(position).getID());
Toast.makeText(getActivity(), "ID: " + clickId, Toast.LENGTH_SHORT).show();
}
// recycler settings;
public void loadView() {
layoutManager = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(layoutManager);
Collections.reverse(records);
adapter = new RecyclerViewAdapter(this,(ArrayList<Image>) records, getActivity());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
reflesh.setRefreshing(false);
}
I'm not sure if this is your issue but you should be using the ViewHolder to get the position. Inside of your onBindViewHolder:
#Override
public void onClick(View view){
int itemPosition = holder.getAdapterPosition();
// Then do whatever you need to with the position
}

Stop animation of Recyclerview when load more data

i'm tying to load more data each time user reached at the bottom of Recyclerview by get data of next page , using this :
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (!recyclerView.canScrollVertically(1) && isEnd) {
page++;
isEnd = false;
new fetchData().execute(page);
}
}
});
And everything works fine , but i have a problem with animation , each time i load more data Recyclerview disappears and shows.
here's my rest of code :
public class fetchData extends AsyncTask<Integer, List<Wallpaper>, List<Wallpaper>> {
Document doc = null;
ArrayList<Wallpaper> urls = new ArrayList<>();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<Wallpaper> doInBackground(Integer... integers) {
try {
doc = Jsoup.connect(URLSource+"/page/" + integers[0]).get();
} catch (IOException e) {
e.printStackTrace();
}
Elements newsHeadlines = doc.select(".thumbnail");
for (Element headline : newsHeadlines) {
String thumb = headline.select("img").attr("src");
String title = headline.select("img").attr("alt");
Wallpaper wallpaperInfo = new Wallpaper();
URL = URL.replace("/wallpapers/", "/walls/");
wallpaperInfo.setThumbnails(URL);
wallpaperInfo.setTitle(title);
urls.add(wallpaperInfo);
}
return urls;
}
#Override
protected void onPostExecute(List<Wallpaper> wallpapers) {
super.onPostExecute(wallpapers);
setAdapterForRecyclerView(wallpapers);
isEnd = true;
}
}
private void setAdapterForRecyclerView(List<Wallpaper> wallpapers) {
if (myAdapter == null) {
myAdapter = new MyAdapter(wallpapers, getActivity(), new RecyclerViewClickListener() {
#Override
public void onClick(View view, Wallpaper wallpaper) {
Intent intent = new Intent(getActivity(), FullScreen.class);
intent.putExtra("img", wallpaper.getThumbnails());
if (wallpaper.getTitle().isEmpty()) {
intent.putExtra("title", "Unknown");
} else {
intent.putExtra("title", wallpaper.getTitle());
}
startActivity(intent);
/* TODO: FULLSCREEN ACTIVITY HERE*/
}
#Override
public void onClick(View view, Category categories) {
}
});
recyclerView.setAdapter(myAdapter);
} else {
myAdapter.getItems().addAll(wallpapers);
myAdapter.notifyDataSetChanged();
}
progressbar.setVisibility(View.GONE);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (!recyclerView.canScrollVertically(1) && isEnd) {
page++;
isEnd = false;
new fetchData().execute(page);
}
}
});
}
hope you guys help me to stop this animation , i just want to load more data without any animation
i think that your problem is in the calling of setAdapterForRecyclerView as there you may create new adapter instance and set this new adapter to the recyclerview again which lead to this behavior.
i recommend to append the new list of wallpapers objects to the recyclerview list then call notifydatasetchanged

Android app Tab Switching Crash

I am currently having an error in my app. I have a recyclerview that loads posts from a firebase database and displays them. When I switch fragments and activities I do not get any errors. When I click the home button or tabs button on my phone and then click back into my app there is a crash with the error message,
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder{777f444 position=1
id=-1, oldPos=0, pLpos:0 scrap [attachedScrap] tmpDetached no parent}
android.support.v7.widget.RecyclerView{efb45c8 VFED..... .F......
0,0-1080,1497 #7f0900c2 app:id/postList},
adapter:com.sender.hp.sender.DashboardFragment$2#efd661,
layout:android.support.v7.widget.LinearLayoutManager#9760586,
context:com.sender.hp.sender.MainActivity#720f0fa
Whenever I hit the back button on my phone and my app gets closed, If I go into my tabs and hit back into my app it works fine. I don't have an onBackPressed listener.
Here is my code,
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<postsGetInfo, postsGetInfoViewHolder>(postsGetInfo.class, R.layout.posts_layout,postsGetInfoViewHolder.class,postRef) {
#Override
protected void populateViewHolder(final postsGetInfoViewHolder viewHolder, postsGetInfo model, int position) {
TextView txtUpvote = (TextView) viewHolder.myView.findViewById(R.id.txtUpvoteCount);
final String postKey = getRef(position).getKey();
viewHolder.setUsername(model.getUsername());
viewHolder.setTime(model.getTime());
viewHolder.setDate(model.getDate());
viewHolder.setDescription(model.getDescription());
viewHolder.setProfileImage(model.getProfileimage());
viewHolder.setImage(model.getImage());
viewHolder.setDisplayvotes(model.getDisplayvotes());
viewHolder.myView.findViewById(R.id.imgDownvote).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
UpdateTheDisplayVotes(postKey);
++getDownvotes;
--getDisplayVotes;
String txtDisplayVotes = Integer.toString(getDisplayVotes);
postRef.child(postKey).child("downvotes").setValue(getDownvotes);
postRef.child(postKey).child("displayvotes").setValue(txtDisplayVotes);
}
});
viewHolder.myView.findViewById(R.id.imgUpvote).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
UpdateTheDisplayVotes(postKey);
++getUpvotes;
++getDisplayVotes;
String txtDisplayVotes = Integer.toString(getDisplayVotes);
postRef.child(postKey).child("upvotes").setValue(getUpvotes);
postRef.child(postKey).child("displayvotes").setValue(txtDisplayVotes);
}
});
viewHolder.myView.findViewById(R.id.imgPost).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent editIntent = new Intent((getActivity()),postEdit.class);
editIntent.putExtra("PostKey",postKey);
startActivity(editIntent);
}
});
}
};
postList.setAdapter(firebaseRecyclerAdapter);
}
private void UpdateTheDisplayVotes(final String key) {
VoteListener = postRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if (dataSnapshot.hasChild("displayvotes")){
displayvotes = dataSnapshot.child(key).child("displayvotes").getValue().toString();
getDisplayVotes = Integer.parseInt(displayvotes);
}
if (dataSnapshot.hasChild("upvotes")){
upvotes = dataSnapshot.child(key).child("upvotes").getValue().toString();
getUpvotes = Integer.parseInt(upvotes);
}
if (dataSnapshot.hasChild("downvotes")){
downvotes = dataSnapshot.child(key).child("downvotes").getValue().toString();
getDownvotes = Integer.parseInt(downvotes);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onStart() {
super.onStart();
firebaseRecyclerAdapter.startListening();
}
#Override
public void onStop() {
super.onStop();
if (firebaseRecyclerAdapter != null){
firebaseRecyclerAdapter.cleanup();
}
}
Anyone know how to fix? Thanks for any answers!
This error occurs when the adapter or list in the adapter is cleared.
Call notifyDataSetChanged() when adapter is cleared.
#Override
public void onStop() {
super.onStop();
if (firebaseRecyclerAdapter != null){
firebaseRecyclerAdapter.cleanup();
firebaseRecyclerAdapter.notifyDataSetChanged();
}
}

Realm database is not updating

Hi friends please help me out i am making chating app with the conversion of text and images Whenever user changes the image in his profile it need to be update in the conversion as well but its not getting updated but whenever i sends a new message then the new image is updating and also i dont set the primary key
Here is below link i had tried nothing worked:
How to update the values in Table using Realm android?
Update mutiple rows in table using Realm in Android
public class Chat_history extends AppCompatActivity {
#BindView(R.id.chat_history_toolbar)
CustomToolbar chat_history_toolbar;
#BindView(R.id.sendmessgae)
CustomEditText sendmessgae;
#BindView(R.id.chat_history_list)
ListView chat_history_list;
Chat_history_Adapter chathisadapter;
RealmResults<Chat_history_pojo> chathistorylist;
Realm chatrealm;
BroadcastReceiver chatreceiver;
public static final String BroadCastAction = "com.parallelspace.parallelspace.Chat_history";
RealmChangeListener chatupdatelisterner = new RealmChangeListener() {
#Override
public void onChange(Object element) {
chathisadapter.addmessage(chathistorylist);
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_history);
ButterKnife.bind(this);
Realm.init(getApplicationContext());
setSupportActionBar(chat_history_toolbar);
assert getSupportActionBar() != null;
**chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
RealmQuery<Chat_history_pojo> getLoginData= chatrealm.where(Chat_history_pojo.class).beginGroup().equalTo("receiverid", getIntent().getStringExtra("rid")).endGroup();
RealmResults<Chat_history_pojo> registrationRealm = getLoginData.findAll();
for (Chat_history_pojo chtapojo:registrationRealm) {
chtapojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatrealm.copyToRealm(registrationRealm);
}
chatrealm.commitTransaction();**
chathistorylist = chatrealm.where(Chat_history_pojo.class).beginGroup()
.equalTo("senderid", Session.getUserID(getApplicationContext()))
.equalTo("receiverid", getIntent().getStringExtra("rid"))
.endGroup()
.or()
.beginGroup()
.equalTo("receiverid", Session.getUserID(getApplicationContext()))
.equalTo("senderid", getIntent().getStringExtra("rid"))
.endGroup()
.findAll();
chathisadapter = new Chat_history_Adapter(Chat_history.this, chathistorylist);
chat_history_list.setStackFromBottom(true);
chat_history_list.setTranscriptMode(chat_history_list.TRANSCRIPT_MODE_NORMAL);
chat_history_list.setAdapter(chathisadapter);
/*chatrealm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Constant.l("Realm Update Called");
RealmResults<Chat_history_pojo> updatehispojo = chatrealm.where(Chat_history_pojo.class).equalTo("receiverid", getIntent().getStringExtra("rid")).findAll();
for(Chat_history_pojo updatepojo:updatehispojo){
updatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatrealm.insertOrUpdate(updatepojo);
chathisadapter.notifyDataSetChanged();
}
}
});*/
sendmessgae.setDrawableClickListener(new DrawableClickListener() {
#Override
public void onClick(DrawablePosition target) {
switch (target) {
case RIGHT:
if (sendmessgae.getText().toString().isEmpty()) {
Constant.t(getApplicationContext(), "Please Enter Message");
} else {
sendmessage();
}
break;
default:
break;
}
}
});
if (getIntent().hasExtra("mtype")) {
chat_history_toolbar.toolbaricon(getApplicationContext(), getIntent().getStringExtra("rimage"));
chat_history_toolbar.toolbartext(getIntent().getStringExtra("rname"));
} else {
chat_history_toolbar.toolbaricon(getApplicationContext(), getIntent().getStringExtra("rimage"));
chat_history_toolbar.toolbartext(getIntent().getStringExtra("rname"));
}
chat_history_toolbar.Whichonclicked("back", new View.OnClickListener() {
#Override
public void onClick(View view) {
Session.removepushnotification(getApplicationContext());
Intent chathistoryintent = new Intent(getApplicationContext(), Chadim_Home.class);
chathistoryintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(chathistoryintent);
}
});
chat_history_toolbar.Whichonclicked("toolbar", new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent chathisintent = new Intent(getApplicationContext(), Detailed_friend.class);
chathisintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
chathisintent.putExtra("rname", getIntent().getStringExtra("rname"));
chathisintent.putExtra("rimage", getIntent().getStringExtra("rimage"));
chathisintent.putExtra("rid", getIntent().getStringExtra("rid"));
startActivity(chathisintent);
}
});
chat_history_toolbar.Whichonclicked("delete", new View.OnClickListener() {
#Override
public void onClick(View v) {
chatrealm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
RealmResults<Chat_history_pojo> deleteresults = realm.where(Chat_history_pojo.class).beginGroup()
.equalTo("senderid", Session.getUserID(getApplicationContext()))
.equalTo("receiverid", getIntent().getStringExtra("rid"))
.endGroup()
.or()
.beginGroup()
.equalTo("receiverid", Session.getUserID(getApplicationContext()))
.equalTo("senderid", getIntent().getStringExtra("rid"))
.endGroup()
.findAll();
deleteresults.deleteAllFromRealm();
}
});
}
});
chatreceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
chatupdatepojo.setSenderid(getIntent().getStringExtra("rid"));
chatupdatepojo.setReceiverid(Session.getUserID(getApplicationContext()));
chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatupdatepojo.setMessage(intent.getStringExtra("msg").replace("$", " "));
chatupdatepojo.setType("text");
if (intent.getStringExtra("type").equals("image")) {
chatupdatepojo.setType("image");
} else if (intent.getStringExtra("type").equals("text")) {
chatupdatepojo.setType("text");
}
chatrealm.commitTransaction();
chatrealm.close();
}
};
IntentFilter intfil = new IntentFilter(BroadCastAction);
registerReceiver(chatreceiver, intfil);
}
#Override
protected void onDestroy() {
unregisterReceiver(chatreceiver);
super.onDestroy();
}
#Override
protected void onStart() {
super.onStart();
chatrealm.addChangeListener(chatupdatelisterner);
Session.pushnotification(getApplicationContext());
}
#Override
protected void onStop() {
super.onStop();
chatrealm.removeChangeListener(chatupdatelisterner);
Session.removepushnotification(getApplicationContext());
}
#OnClick(R.id.camera)
public void camera() {
TedBottomPicker bottomSheetDialogFragment = new TedBottomPicker.Builder(Chat_history.this)
.setOnImageSelectedListener(new TedBottomPicker.OnImageSelectedListener() {
#Override
public void onImageSelected(Uri uri) {
try {
Bitmap sendimage = MediaStore.Images.Media.getBitmap(Chat_history.this.getContentResolver(), uri);
sendimages(Session.getUserID(getApplicationContext()), getIntent().getStringExtra("rid"), sendimage);
} catch (IOException e) {
Constant.l(e.toString());
}
}
})
.setPeekHeight(getResources().getDisplayMetrics().heightPixels / 2)
.create();
bottomSheetDialogFragment.show(getSupportFragmentManager());
}
private void sendimages(String sid, String rid, Bitmap sendbitmap) {
Constant.showloader(Chat_history.this);
String sendumageurl = Constant.psurl + "chatdocument&task=send&sender_id=" + sid + "&reciever_id=" + rid;
Constant.l(sendumageurl);
AndroidNetworking.post(sendumageurl).addBodyParameter("image", Constant.getStringImage(sendbitmap)).build().getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("Success")) {
Constant.l(String.valueOf(response));
chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
chatupdatepojo.setSenderid(Session.getUserID(getApplicationContext()));
chatupdatepojo.setReceiverid(getIntent().getStringExtra("rid"));
chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatupdatepojo.setMessage(response.getString("url"));
chatupdatepojo.setType("image");
chatrealm.commitTransaction();
chatrealm.close();
}
} catch (JSONException e) {
Constant.l(e.toString());
Constant.dismissloader();
}
Constant.dismissloader();
}
#Override
public void onError(ANError anError) {
Constant.l(anError.toString());
Constant.dismissloader();
}
});
}
#Override
public void onBackPressed() {
Session.removepushnotification(getApplicationContext());
Intent chathistoryintent = new Intent(getApplicationContext(), Chadim_Home.class);
chathistoryintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(chathistoryintent);
}
private void sendmessage() {
String schatsendmesg = Constant.psurl + "chat&task=send&sender_id=" + Session.getUserID(getApplicationContext()) + "&reciever_id=" + getIntent().getStringExtra("rid") + "&message=" + sendmessgae.getText().toString().replace(" ", "$");
Constant.l(schatsendmesg);
AndroidNetworking.get(schatsendmesg).setOkHttpClient(Constant.okClient()).build().getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("Success")) {
chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
chatupdatepojo.setSenderid(Session.getUserID(getApplicationContext()));
chatupdatepojo.setReceiverid(getIntent().getStringExtra("rid"));
chatupdatepojo.setMessage(sendmessgae.getText().toString());
chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatupdatepojo.setType("text");
chatrealm.commitTransaction();
chatrealm.close();
sendmessgae.setText("");
}
} catch (JSONException e) {
Constant.l(e.toString());
}
}
#Override
public void onError(ANError anError) {
Constant.l(anError.toString());
}
});
}
#Override
protected void onResume() {
super.onResume();
Session.pushnotification(getApplicationContext());
}
#Override
protected void onPause() {
super.onPause();
Session.removepushnotification(getApplicationContext());
}
}
Try this way of updation.
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
//Here i am checking the condition
RealmQuery<RegistrationRealm> getLoginData= realm.where(RegistrationRealm.class).equalTo("id",1);
//finding the first set if matches the criteria
RegistrationRealm registrationRealm = getLoginData.findFirst();
//setting the values
registrationRealm.setFirstname(firstname);
registrationRealm.setLastname(lastname);
//Updating the same object with new values
realm.copyToRealm(registrationRealm);
//commiting the current transaction
realm.commitTransaction();
If you need to update all, then get a RealmResults object and iterate through
RealmResults<RegistrationRealm> registrationRealm = getLoginData.findAll();
NOTE:
When using realm.copyToRealm() it is important to remember that only the returned object is managed by Realm, so any further changes to the original object will not be persisted.
Realm reference

Categories

Resources