How to update viewpager fregment content when viewpager swipe in MainActivity - android

I am trying to update viewpager fregment when viewpager swipe in MainActivity.
MenuActivity:-
package jbit.kanha;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import com.romainpiel.shimmer.Shimmer;
import com.romainpiel.shimmer.ShimmerTextView;
import org.json.JSONArray;
import org.json.JSONObject;
import jbit.kanha.AllAdepters.SideMenuAdapter;
import jbit.kanha.InternetConection.CheckInternetConection;
import jbit.kanha.InternetConection.ConnectionDetector;
import jbit.kanha.InternetConection.InternetDialoge;
import jbit.kanha.ProgressDialog.MyProgressDialog;
import jbit.kanha.SideMenuClasses.MyProfile;
import jbit.kanha.db.Database;
public class MenuActivity extends FragmentActivity implements View.OnClickListener{
public static ResideMenu resideMenu;
private MenuActivity mContext;
private ResideMenuItem itemHome;
private ResideMenuItem itemProfile;
private ResideMenuItem itemCalendar;
private ResideMenuItem itemSettings;
SharedPreferences loginPreferences;
private SharedPreferences pref;
ImageView profile_image;
public static TextView title_bar_right_menu,txt_total_rate;
Database database;
JSONArray categoryItem;
// private PagerSlidingTabStrip tabLayout;
private TabLayout tabLayout;
ViewPager pager;
private ConnectionDetector connectionDetector;
private MyProgressDialog dialog;
ViewPagerAdapter adapter;
OneFregment fregment;
// private int currentColor = Color.parseColor("#1D569B");
// PagerSlidingTabStrip tabStrip;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = this;
database = new Database(MenuActivity.this);
tabLayout= (TabLayout)findViewById(R.id.tabs);
pager = (ViewPager)findViewById(R.id.pager);
loginPreferences = getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
connectionDetector = new ConnectionDetector(mContext);
dialog = new MyProgressDialog(mContext);
adapter = new ViewPagerAdapter(getSupportFragmentManager());
if (connectionDetector.isConnectingToInternet()){
getCategoryName();
}else{
Toast.makeText(mContext, "No Internet Connection", Toast.LENGTH_SHORT).show();
}
title_bar_right_menu = (TextView) findViewById(R.id.title_bar_right_menu);
txt_total_rate = (TextView) findViewById(R.id.txt_total_rate);
pref = getApplicationContext().getSharedPreferences("loginPrefs", MODE_PRIVATE);
Cursor cursor1 = database.getData("SELECT * FROM cart");
int count = cursor1.getCount();
cursor1.close();
title_bar_right_menu.setText(count+"");
setUpMenu();
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
getCategoryDataRefresh(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
private void getCategoryData(final int postion){
Ion.with(mContext)
.load(getResources().getString(R.string.api_main_url) + "categoryoriginal.php")
.setTimeout(30*1000)
.setBodyParameter("outlet_id",loginPreferences.getString("outlet_id",""))
.setBodyParameter("catid",String.valueOf(postion+1))
.asString().setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
dialog.hide();
if (e != null) {
e.printStackTrace();
DialogsClassTwoData(mContext, "Connection Timed Out!", "Message...",postion).show();
}
if (result != null) {
try {
Log.d("name",result);
JSONObject mainJson = new JSONObject(result);
String status = mainJson.getString("status");
if(status.equals("Success")){
JSONArray jsonArray = mainJson.getJSONArray("data");
setUpViewPager(pager,categoryItem,jsonArray);
}
}catch (Exception ex) {
ex.printStackTrace();
Log.d("exaption", ex.toString());
}
} else {
Log.d("exaption", e.toString());
}
}
});
}
private void getCategoryDataRefresh(final int postion){
dialog.show();
Ion.with(mContext)
.load(getResources().getString(R.string.api_main_url) + "categoryoriginal.php")
.setTimeout(30*1000)
.setBodyParameter("outlet_id",loginPreferences.getString("outlet_id",""))
.setBodyParameter("catid",String.valueOf(postion+1))
.asString().setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
dialog.hide();
if (e != null) {
e.printStackTrace();
DialogsClassTwoData(mContext, "Connection Timed Out!", "Message...",postion).show();
}
if (result != null) {
try {
Log.d("name",result);
JSONObject mainJson = new JSONObject(result);
String status = mainJson.getString("status");
if(status.equals("Success")){
Fragment frg = null;
frg = new OneFregment(mainJson.getJSONArray("data"));
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();
}
}catch (Exception ex) {
ex.printStackTrace();
Log.d("exaption", ex.toString());
}
} else {
Log.d("exaption", e.toString());
}
}
});
}
private void getCategoryName(){
dialog.show();
Ion.with(mContext)
.load(getResources().getString(R.string.api_main_url) + "categoryname.php")
.setTimeout(30*1000)
.asString().setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
// dialog.hide();
if (e != null) {
e.printStackTrace();
DialogsClassTwo(mContext, "Connection Timed Out!", "Message...").show();
}
if (result != null) {
try {
Log.d("name",result);
JSONObject mainJson = new JSONObject(result);
String status = mainJson.getString("status");
if(status.equals("Success")){
JSONObject jsonObject = mainJson.getJSONObject("data");
categoryItem = jsonObject.getJSONArray("items");
// setUpViewPager(pager,jsonObject.getJSONArray("items"));
Log.d("json",jsonObject+"");
getCategoryData(0);
//data = jsonObject.getJSONArray("items");
/* for(int i=0;i<data.length();i++){
JSONObject jsonObject1 = data.getJSONObject(i);
bigImage.add(jsonObject1.getString("bigimage"));
}
pager.setAdapter(new CustomPagerAdapter(getActivity(),data));
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
changeColor(currentColor);*/
}
}catch (Exception ex) {
ex.printStackTrace();
Log.d("exaption", ex.toString());
}
} else {
Log.d("exaption", e.toString());
}
}
});
}
private void setUpViewPager(ViewPager pager, JSONArray jsonArray,JSONArray products){
try {
// ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
adapter.addFrag(new OneFregment(products),jsonObject.getString("categoryname"));
}
pager.setAdapter(adapter);
tabLayout.setupWithViewPager(pager);
// tabLayout.tabSelectedTextColor
// getCategoryData();
}
catch (Exception e) {
Log.e("error", e.getMessage());
}
}
public AlertDialog.Builder DialogsClassTwo(Context cxt, final String message, String title){
return new AlertDialog.Builder(cxt).setTitle(title).setMessage(message).setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogs, int which) {
// here you can add functions
if (CheckInternetConection.isInternetConnection(mContext.getApplicationContext())){
getCategoryName();
// getCategoryData();
}else{
InternetDialoge.showDialogFinishActivity(
"Internet Connection Failed!", "connection error", mContext);
}
}
});
}
public AlertDialog.Builder DialogsClassTwoData(Context cxt, final String message, String title, final int postion){
return new AlertDialog.Builder(cxt).setTitle(title).setMessage(message).setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogs, int which) {
// here you can add functions
if (CheckInternetConection.isInternetConnection(mContext.getApplicationContext())){
//getCategoryName();
getCategoryData(postion);
}else{
InternetDialoge.showDialogFinishActivity(
"Internet Connection Failed!", "connection error", mContext);
}
}
});
}
private void setUpMenu() {
resideMenu = new ResideMenu(MenuActivity.this, R.layout.side_menu, R.layout.home);
//resideMenu.setBackground(Color.parseColor("#FAA514"));//FAA514
resideMenu.setBackground(R.drawable.slider_background);
resideMenu.attachToActivity(MenuActivity.this);
resideMenu.setScaleValue(0.5f);
View leftMenu = resideMenu.getLeftMenuView();
Shimmer shimmer = new Shimmer();//#faebd7
shimmer.setDuration(3000)
.setStartDelay(500)
.setDirection(Shimmer.ANIMATION_DIRECTION_LTR);
ShimmerTextView powered = (ShimmerTextView)leftMenu.findViewById(R.id.powered);
ListView list = (ListView) leftMenu.findViewById(R.id.list1);
list.setAdapter(new SideMenuAdapter(MenuActivity.this));
profile_image = (ImageView) leftMenu.findViewById(R.id.profile_image);
TextView title1 = (TextView) leftMenu.findViewById(R.id.title1);
TextView loction1 = (TextView) leftMenu.findViewById(R.id.loction1);
ImageView location_icon =(ImageView) leftMenu.findViewById(R.id.location_icon);
RelativeLayout ll_checkout = (RelativeLayout) findViewById(R.id.ll_checkout);
//loginPreferences = getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
title1.setText(loginPreferences.getString("fullname",""));
loction1.setText(loginPreferences.getString("address",""));
// if(!loginPreferences.getString("profileimage","").equals("")){
/* Picasso.with(MenuActivity.this)
.load(loginPreferences.getString("profileimage",""))
.error(R.drawable.images)
.placeholder(R.drawable.progress_animation)
.into(profile_image);*/
// File file = new File("/main_json/main_json/com.example.w.lazymojo/app_imageDir/profile.jpg");
shimmer.start(powered);
if(pref.getString("User_id", "").equals("")){
profile_image.setImageResource(R.drawable.images);
location_icon.setVisibility(View.INVISIBLE);
}
else {
Bitmap bitmap1 = BitmapFactory.decodeFile("/data/data/jbit.kanha/app_imageDir/profile.jpg");
if(bitmap1!=null){
Log.d("MenuActivity:-","image not null");
profile_image.setImageBitmap(bitmap1);
// Picasso.with(MenuActivity.this).load(file).resize(dpToPx(96),dpToPx(96)).centerCrop().into(profile_image);
}
else {
Log.d("MenuActivity:-","image is null");
profile_image.setImageResource(R.drawable.images);
}
}
profile_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(pref.getString("User_id", "").equals("")){
profile_image.setImageResource(R.drawable.images);
new AlertDialog.Builder(MenuActivity.this).setTitle("Login").setMessage("You have to login first").setPositiveButton("Login", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent in = new Intent(MenuActivity.this,LoginActivity.class);
startActivity(in);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
else {
Intent i = new Intent(MenuActivity.this, MyProfile.class);
startActivity(i);
}
}
});
// }
ll_checkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!pref.getString("User_id", "").equals("")){
Intent i = new Intent(MenuActivity.this,MyCart.class);
startActivity(i);
finish();
}
else
{
new AlertDialog.Builder(MenuActivity.this).setTitle("Login").setMessage("You must login first").setPositiveButton("Login", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MenuActivity.this,LoginActivity.class);
startActivity(intent);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
}
});
resideMenu.setSwipeDirectionDisable(ResideMenu.DIRECTION_RIGHT);
resideMenu.setSwipeDirectionDisable(ResideMenu.DIRECTION_LEFT);
findViewById(R.id.title_bar_left_menu).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
resideMenu.openMenu(ResideMenu.DIRECTION_LEFT);
}
});
findViewById(R.id.cart_img).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!pref.getString("User_id", "").equals("")){
Intent i = new Intent(MenuActivity.this,MyCart.class);
startActivity(i);
finish();
}
else
{
new AlertDialog.Builder(MenuActivity.this).setTitle("Login").setMessage("You must login first").setPositiveButton("Login", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MenuActivity.this,LoginActivity.class);
startActivity(intent);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
// resideMenu.openMenu(ResideMenu.DIRECTION_RIGHT);
}
});
}
#Override
public void onClick(View view) {
resideMenu.closeMenu();
}
private ResideMenu.OnMenuListener menuListener = new ResideMenu.OnMenuListener() {
#Override
public void openMenu() {
// Toast.makeText(mContext, "Menu is opened!", Toast.LENGTH_SHORT).show();
}
#Override
public void closeMenu() {
//Toast.makeText(mContext, "Menu is closed!", Toast.LENGTH_SHORT).show();
}
};
// What good method is to access resideMenu?
public ResideMenu getResideMenu(){
return resideMenu;
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
moveTaskToBack(true);
}
}
ViewPagerAdapter.java:
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
OneFregement:-
public class OneFregment extends Fragment {
JSONArray jsonArray;
ListView listView;
HomeLiatAdapter adapter;
public OneFregment() {
// Required empty public constructor
}
#SuppressLint("ValidFragment")
public OneFregment(JSONArray jsonArray){
this.jsonArray = jsonArray;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.home_child_layout, container, false);
listView = (ListView) v.findViewById(R.id.list);
try {
JSONObject obj = jsonArray.getJSONObject(0);
adapter = new HomeLiatAdapter(getContext(),obj.getJSONArray("items"),obj.getString("bigimage"));
listView.setAdapter(adapter);
}catch (Exception e){
e.printStackTrace();
}
return v;
}
/* public void update(){
try {
JSONObject obj = jsonArray.getJSONObject(0);
adapter = new HomeLiatAdapter(getContext(),obj.getJSONArray("items"),obj.getString("bigimage"));
listView.setAdapter(adapter);
}catch (Exception e){
e.printStackTrace();
}
}*/
}
I am do this but fregment is show previous data.I also try create update method in fregment class but all is wain.
I am new in Android Developing please help me. Thanks in advance.

you will have to write custom interface and implement in each fragment. And on onpagechangelistener you will have to call those method.
check this for more explanation. even i had to implement same for my project to get the fragments updated as normal fragment life-cycle wont work as you want. due to view pager adding and retaining of fragment as you swipe through.

Related

I have only one fragment and I want to change this fragment in viewpager dynamically according to recycler view item data

my problem is same as link given below
I have a ViewPager by same fragments RecyclerView just load items in one fragment of ViewPager
but at this post no one solve issue...
I have a recycler view items...I want when I click on recycler view item it takes me to viewpager fragment and shows that data of clicked item dynamically and on swiping viewpager it should move previous and next fragment accordingly...under fragment I want to show data of recyclerrview item using single fragment...
I have done this by using multiple fragment and using multiple instances by different name and different layout name and different id for its recyclerView and it works but i have a large number of fragments and it is not the solution for me ):
here is my viewpager code
public class AndroidViewPagerExample extends FragmentActivity {
ViewPager pager;
int positionring;
String rgtv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.mainuuuu);
Intent it = getIntent();
positionring = it.getIntExtra("POS", 0);
final int position = it.getIntExtra("POS", 0);
rgtv= it.getStringExtra("name");
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
pager.setPageTransformer(true, new RotateUpTransformer());
pager.setCurrentItem(position);
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
Boolean first = true;
Boolean userScrollChange=false;
public void onPageScrollStateChanged(int state) {
System.out.println("onPageScrollStateChanged");
System.out.println("Current position=="+position);
int curreentpos=position;
int newpos=curreentpos+1;
int previousState=curreentpos-1;
if (previousState == pager.SCROLL_STATE_DRAGGING
&& state == pager.SCROLL_STATE_SETTLING)
userScrollChange = true;
else if (previousState == pager.SCROLL_STATE_SETTLING
&& state == pager.SCROLL_STATE_IDLE)
userScrollChange = false;
previousState = state;
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
System.out.println("onPageScrolled");
}
public void onPageSelected(int position) {
// Check if this is the page you want.
System.out.println("onPageSelected");
Apples.newInstance(rgtv);
}
});
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
return Apples.newInstance(rgtv);
}
#Override
public int getCount() {
return ringtonelist.size();
}
}
#Override
public void onBackPressed() {
// if (pager.getCurrentItem() != 36) {
// pager.setCurrentItem(36);
// } else {
Vp_Ringtoneplaybtn.Playstop();
super.onBackPressed();
// }
}
}
code given below is adapter code
public class RingToneAdapter extends RecyclerView.Adapter<RingToneAdapter.RingToneViewHolder> {
public int mSelectedItem = -1;
static MediaPlayer mp;
View view;
static Context rcntx;
int oldpossssssss;
List<RingTone_Items> ringtonelist;
private TextView hello, close;
ImageView prev, next;
private ImageView iconplay;
private InterstitialAd mInterstitialAd;
Dialog MyDialog;
static final int[] resID = {R.raw.a48, R.raw.funny_hen, R.raw.funny_roster_1, R.raw.funny_roster_2, R.raw.rooster_1, R.raw.rooster_2,R.raw.rooster_3,R.raw.funny_cock,R.raw.a12,R.raw.a45,R.raw.a44,R.raw.a43,R.raw.a31, R.raw.a10,R.raw.chicken_1,R.raw.chick_2,R.raw.chick_3,R.raw.chick_4,R.raw.chick_5,R.raw.chick_6};
public RingToneAdapter(Context rcntx, List<RingTone_Items> ringtonelist) {
this.rcntx = rcntx;
this.ringtonelist = ringtonelist;
}
#NonNull
#Override
public RingToneViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
view = LayoutInflater.from(rcntx).inflate(R.layout.ringtone_values, viewGroup, false);
RingToneViewHolder ringToneViewHolder = new RingToneViewHolder(view);
return ringToneViewHolder;
}
#Override
public void onBindViewHolder(#NonNull final RingToneViewHolder ringToneViewHolder, final int i) {
final RingTone_Items ringTone_items = ringtonelist.get(i);
ringToneViewHolder.rtv.setText(ringTone_items.getRintonetv());
if (mSelectedItem == i) { // mSelectedItem = -1 and at 1st time
// there is no position selected...so the condition goes false...go
// to else condtion
ringToneViewHolder.iconplay.setImageResource(R.drawable.ic_pause_black_24dp);
} else {
ringToneViewHolder.iconplay.setImageResource(R.drawable.ic_play_arrow_black_24dp); // all icons will show play icon
}
ringToneViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// MyCustomAlertDialog(i);
if (mp != null && mp.isPlaying()) {
mp.stop();
mp.reset();
mp = null;
ringToneViewHolder.iconplay.setImageResource(R.drawable.ic_play_arrow_black_24dp);
}
//Intent it = new Intent(rcntx, ViewPager_Data.class);
Intent it = new Intent(rcntx, AndroidViewPagerExample.class);
it.putExtra("POS",i);
it.putExtra("name",ringTone_items.getRintonetv());
// mInterstitialAd = new InterstitialAd(rcntx);
// mInterstitialAd.setAdUnitId(rcntx.getResources().getString(R.string.ad_interstitial));
// AdRequest adRequest = new AdRequest.Builder().build();
// mInterstitialAd.loadAd(adRequest);
// mInterstitialAd.setAdListener(new AdListener() {
// public void onAdLoaded() {
// if (mInterstitialAd.isLoaded()) {
// mInterstitialAd.show();
// }
// }
// });
rcntx.startActivity(it);
}
});
ringToneViewHolder.iconplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mSelectedItem == i) {
mSelectedItem = -1;
oldpossssssss = i;
} else {
mSelectedItem = i;
}
notifyDataSetChanged(); //update the position of row...notifyDataSetChanged is bindview method
if (mp != null && mp.isPlaying()) {
mp.stop();
//mp.deselectTrack(resID[i]);
mp.reset();
mp.release();
mp = null;
if (oldpossssssss == i) {
} else {
mp = new MediaPlayer();
mp = MediaPlayer.create(rcntx, resID[i]);
mp.start();
}
} else {
// MyCustomAlertDialog(i);
mp = new MediaPlayer();
mp = MediaPlayer.create(rcntx, resID[i]);
mp.start();
}
}
});
}
#Override
public int getItemCount() {
return ringtonelist.size();
}
class RingToneViewHolder extends RecyclerView.ViewHolder {
private TextView rtv, hello, close;
private ImageView iconplay;
public RingToneViewHolder(#NonNull View itemView) {
super(itemView);
rtv = itemView.findViewById(R.id.ringtitle);
iconplay = itemView.findViewById(R.id.playicon);
}
}
public void InterstitialAdmob() {
mInterstitialAd = new InterstitialAd(rcntx);
mInterstitialAd.setAdUnitId(rcntx.getResources().getString(R.string.ad_interstitial));
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
requestNewInterstitial();
}
});
requestNewInterstitial();
}
protected void requestNewInterstitial() {
AdRequest adRequest = new AdRequest.Builder().build();
mInterstitialAd.loadAd(adRequest);
}
}
here is main activity code
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
RingToneAdapter adapter;
public static ArrayList<RingTone_Items> ringtonelist;
//final int[] resID = {R.raw.alert};
public static int posss;
private String[] fruitlist = new String[]{"Funny hen 1", "Funny hen 2", "Funny roaster 1", "Funny roaster 2","Funny roaster 3", "Funny roaster 4", "funny roaster 5","Funny cock", "Funny hen alarm","Abstracts", "Wake up", "Funny tone","Get up","Alarm","Hen sound 1","Hen sound 2","Hen sound 3","Hen sound 4","Hen sound 5","Hen sound 6"};
private boolean isFABOpen;
FloatingActionButton fab,fab1, fab3;
FrameLayout fab2;
AdView mAdView;
RelativeLayout layout_no, layoutrateus, layout_yes, adlayout, adlayout1;
private static final int PERMISSION_REQUEST_CODE = 1;
private String fNmae = String.valueOf(R.raw.alarm);
private String fPAth = "android.resource://packagename/raw/alarm";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler);
// Here, thisActivity is the current activity
if (Build.VERSION.SDK_INT >= 23) {
if (checkPermission()) {
if (Settings.System.canWrite(MainActivity.this)) {
//setRingtone();
} else {
Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS)
.setData(Uri.parse("package:" + getPackageName()))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
Log.e("value", "Permission already Granted, Now you can save image.");
} else {
requestPermission();
}
} else {
// setRingtone();
Log.e("value", "Not required for requesting runtime permission");
}
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
//recyclerView.setBackgroundColor(getResources().getColor(R.color.colorAccent));
recyclerView.setBackground(getResources().getDrawable(R.drawable.bg));
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// RecyclerView.LayoutManager mLayoutManager =
// new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
ringtonelist = getRingTone_Items();
adapter = new RingToneAdapter(this, ringtonelist);
recyclerView.setAdapter(adapter);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
RingTone_Items itemrg = ringtonelist.get(position);
posss=position;
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
protected boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
protected void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(MainActivity.this, "Write External Storage permission allows us to do store images. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e("value", "Permission Granted, Now you can save image .");
if (Build.VERSION.SDK_INT >= 23) {
if (Settings.System.canWrite(MainActivity.this)) {
// setRingtone();
} else {
Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS)
.setData(Uri.parse("package:" + getPackageName()))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
} else {
Log.e("value", "Permission Denied, You cannot save image.");
}
break;
}
}
private ArrayList<RingTone_Items> getRingTone_Items(){
ArrayList<RingTone_Items> list = new ArrayList<>();
for(int i = 0; i < 20; i++){
RingTone_Items model = new RingTone_Items();
model.setRintonetv(fruitlist[i]);
list.add(model);
}
return list;
}
public void onBackPressed(){
if (mp != null && mp.isPlaying()) {
mp.pause();
mp.stop();
mp.release();
mp = null;
}
onexit();
}
public void onexit() {
android.view.LayoutInflater layout1 = android.view.LayoutInflater.from(this);
View view1 = layout1.inflate(R.layout.backpress, null);
final RelativeLayout relativeLayout=(RelativeLayout) view1.findViewById(R.id.layout_top);
final AlertDialog.Builder gotoBuilder1 = new AlertDialog.Builder(this);
gotoBuilder1.setView(view1);
final AlertDialog gotoDialog1 = gotoBuilder1.create();
layout_no = view1.findViewById(R.id.layoutno);
layoutrateus = view1.findViewById(R.id.layoutrateus);
layout_yes = view1.findViewById(R.id.layout_yes);
layout_no.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
gotoDialog1.dismiss();
}
});
layoutrateus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
Intent mintent = new Intent(Intent.ACTION_VIEW);
mintent.setData(android.net.Uri.parse("market://details?id="
+ getPackageName()));
startActivity(mintent);
} catch (Exception e1) {
try {
android.net.Uri uriUrl = android.net.Uri
.parse("https://market.android.com/details?id="
+ getPackageName());
Intent launchBrowser = new Intent(Intent.ACTION_VIEW,
uriUrl);
startActivity(launchBrowser);
} catch (Exception e2) {
android.widget.Toast.makeText(getApplicationContext(),
"No Application Found to open link",
android.widget.Toast.LENGTH_SHORT).show();
}
}
gotoDialog1.dismiss();
}
});
layout_yes.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
} catch (Exception e) {
}
gotoDialog1.dismiss();
finish();
}
});
gotoDialog1.getWindow().setLayout(android.view.ViewGroup.LayoutParams.MATCH_PARENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
gotoDialog1.show();
}
public void onDestroy() {
super.onDestroy();
}
}
this is my fragment
public class Apples extends BaseFragment{
ImageView vpbtn;
MediaPlayer mp;
ImageView tvshare;
static String s;
static TextView rgtname;
int position = 0;
private ShareActionProvider mShareActionProvider;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.apple, container, false);
vpbtn = (ImageView) v.findViewById(R.id.iconplaypause);
mAdView = (AdView) v.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
rgtname=v.findViewById(R.id.rgtname);
rgtname.setText(s);
tvshare=v.findViewById(R.id.tvshare);
fab = v.findViewById(R.id.fab);
fab1 = v.findViewById(R.id.frm1);
fab2 = v.findViewById(R.id.frm2);
fab3 = v.findViewById(R.id.frm3);
// Vp_Ringtoneplaybtn.Setrintones(fab,fab1,fab2,fab3);
// tvshare.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Vp_Ringtoneplaybtn.shareapp();
// }
// });
Vp_Ringtoneplaybtn.shareapp(tvshare);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!isFABOpen){
showFABMenu();
}else{
closeFABMenu();
}
}
});
Vp_Ringtoneplaybtn.Setrintones(fab1,fab2,fab3,position);
vpbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vp_Ringtoneplaybtn.PlaySound( vpbtn, position);
}
});
return v;
}
public static Apples newInstance(String rgtvv) {
s=rgtvv;
Apples f16 = new Apples();
return f16;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (this.isVisible()) {
// If we are becoming invisible, then...
if (!isVisibleToUser) {
Vp_Ringtoneplaybtn.Playstop();
vpbtn.setImageResource(R.drawable.ic_play_arrow_black_24dp);
} else {
// do what you like
}
}
}
#Override
public void onPause() {
super.onPause();
}
}

count on chat does not working correctly QuickBlox

I am using quickblox for my android application. I am able to register, login user, even add custom objects and retrieve them from the quick-blox server, but in chatting listing screen my count is coming wrong.
I am getting issue with unread count
Here is my code flow:-
public class ConversationFragment extends Fragment implements Observer, DialogsManager.ManagingDialogsCallbacks {
ConversationViewModel conversationViewModel;
FragmentConversationBinding binding;
QBChatDialogMessageListener allDialogsMessagesListener;
SystemMessagesListener systemMessagesListener;
QBSystemMessagesManager systemMessagesManager;
QBIncomingMessagesManager incomingMessagesManager;
private DialogsManager dialogsManager;
public ConversationFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_conversation, container, false);
getActivity().getWindow().setBackgroundDrawableResource(R.drawable.bg_img);
View view = binding.getRoot();
systemMessagesListener = new SystemMessagesListener();
dialogsManager = new DialogsManager();
return view;
}
private void setUpModel() {
Bundle mBundle = getArguments();
if (mBundle != null) {
conversationViewModel = new ConversationViewModel(getActivity(), binding, getArguments().getString("DialogIdData"));
} else {
conversationViewModel = new ConversationViewModel(getActivity(), binding, "");
}
binding.setConversationViewModel(conversationViewModel);
setUpObserver(conversationViewModel);
}
private void setUpObserver(ConversationViewModel observer) {
observer.addObserver(this);
}
#Override
public void update(Observable o, Object arg) {
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onResume() {
super.onResume();
setUpModel();
}
#Override
public void onPause() {
super.onPause();
unregisterQbChatListeners();
}
public void unregisterQbChatListeners() {
if (incomingMessagesManager != null) {
incomingMessagesManager.removeDialogMessageListrener(allDialogsMessagesListener);
}
if (systemMessagesManager != null) {
systemMessagesManager.removeSystemMessageListener(systemMessagesListener);
}
dialogsManager.removeManagingDialogsCallbackListener(this);
}
#Override
public void onDialogCreated(QBChatDialog chatDialog) {
}
#Override
public void onDialogUpdated(String chatDialog) {
}
#Override
public void onNewDialogLoaded(QBChatDialog chatDialog) {
}
private class SystemMessagesListener implements QBSystemMessageListener {
#Override
public void processMessage(final QBChatMessage qbChatMessage) {
dialogsManager.onSystemMessageReceived(qbChatMessage);
}
#Override
public void processError(QBChatException e, QBChatMessage qbChatMessage) {
}
}
private BroadcastReceiver mNotificationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
}
Here is my Fragment viewModel code :-
public class ConversationViewModel extends Observable implements DialogsManager.ManagingDialogsCallbacks {
private static final int REQUEST_DIALOG_ID_FOR_UPDATE = 165;
public Context mContext;
FragmentConversationBinding binding;
private ActionMode currentActionMode;
public QBRequestGetBuilder requestBuilder;
private int skipRecords = 0;
private DialogsAdapter dialogsAdapter;
private QBChatDialogMessageListener allDialogsMessagesListener;
private SystemMessagesListener systemMessagesListener;
private QBSystemMessagesManager systemMessagesManager;
private QBIncomingMessagesManager incomingMessagesManager;
private DialogsManager dialogsManager;
private QBUser currentUser;
private String id;
public ConversationViewModel(Context mContext, FragmentConversationBinding binding, String Dialogid) {
this.mContext = mContext;
this.binding = binding;
this.id = Dialogid;
initUI();
}
public void initUI() {
allDialogsMessagesListener = new AllDialogsMessageListener();
systemMessagesListener = new SystemMessagesListener();
dialogsManager = new DialogsManager();
currentUser = ChatHelper.getCurrentUser();
initList();
registerQbChatListeners();
if (QbDialogHolder.getInstance().getDialogs().size() > 0) {
loadDialogsFromQb(true, true);
} else {
loadDialogsFromQb(false, true);
}
if (!id.isEmpty()) {
loadUpdatedDialog(id);
id = "";
} else {
updateDialogsList();
}
}
public void initList() {
dialogsAdapter = new DialogsAdapter(mContext, new ArrayList<>(QbDialogHolder.getInstance().getDialogs().values()));
binding.listDialogsChats.setAdapter(dialogsAdapter);
binding.listDialogsChats.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
QBChatDialog selectedDialog = (QBChatDialog) parent.getItemAtPosition(position);
if (currentActionMode == null) {
ChatActivity.startForResult(((Activity) mContext), REQUEST_DIALOG_ID_FOR_UPDATE, selectedDialog);
} else {
dialogsAdapter.toggleSelection(selectedDialog);
}
}
});
binding.listDialogsChats.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
QBChatDialog selectedDialog = (QBChatDialog) parent.getItemAtPosition(position);
dialogsAdapter.selectItem(selectedDialog);
return true;
}
});
requestBuilder = new QBRequestGetBuilder();
binding.swipyRefreshLayout.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh(SwipyRefreshLayoutDirection direction) {
requestBuilder.setSkip(skipRecords += ChatHelper.DIALOG_ITEMS_PER_PAGE);
loadDialogsFromQb(true, false);
}
});
}
private void loadUpdatedDialog(String dialogId) {
ChatHelper.getInstance().getDialogById(dialogId, new QbEntityCallbackImpl<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog result, Bundle bundle) {
QbDialogHolder.getInstance().addDialog(result);
updateDialogsAdapter();
}
#Override
public void onError(QBResponseException e) {
}
});
}
public void updateDialogsList() {
requestBuilder.setSkip(skipRecords = 0);
loadDialogsFromQb(true, true);
}
#Override
public void onDialogCreated(QBChatDialog chatDialog) {
updateDialogsAdapter();
}
#Override
public void onDialogUpdated(String chatDialog) {
updateDialogsAdapter();
}
#Override
public void onNewDialogLoaded(QBChatDialog chatDialog) {
updateDialogsAdapter();
}
private void registerQbChatListeners() {
incomingMessagesManager = QBChatService.getInstance().getIncomingMessagesManager();
systemMessagesManager = QBChatService.getInstance().getSystemMessagesManager();
if (incomingMessagesManager != null) {
incomingMessagesManager.addDialogMessageListener(allDialogsMessagesListener != null
? allDialogsMessagesListener : new AllDialogsMessageListener());
}
if (systemMessagesManager != null) {
systemMessagesManager.addSystemMessageListener(systemMessagesListener != null
? systemMessagesListener : new SystemMessagesListener());
}
dialogsManager.addManagingDialogsCallbackListener(this);
}
private class SystemMessagesListener implements QBSystemMessageListener {
#Override
public void processMessage(final QBChatMessage qbChatMessage) {
dialogsManager.onSystemMessageReceived(qbChatMessage);
}
#Override
public void processError(QBChatException e, QBChatMessage qbChatMessage) {
}
}
private class AllDialogsMessageListener extends QbChatDialogMessageListenerImp {
#Override
public void processMessage(final String dialogId, final QBChatMessage qbChatMessage, Integer senderId) {
if (!senderId.equals(ChatHelper.getCurrentUser().getId())) {
dialogsManager.onGlobalMessageReceived(dialogId, qbChatMessage);
}
}
}
public void updateDialogsAdapter() {
dialogsAdapter.updateList(new ArrayList<>(QbDialogHolder.getInstance().getDialogs().values()));
}
public void loadDialogsFromQb(final boolean silentUpdate, final boolean clearDialogHolder) {
if (!silentUpdate) {
binding.progressDialogs.setVisibility(View.VISIBLE);
}
ChatHelper.getInstance().getDialogs(requestBuilder, new QBEntityCallback<ArrayList<QBChatDialog>>() {
#Override
public void onSuccess(ArrayList<QBChatDialog> dialogs, Bundle bundle) {
binding.progressDialogs.setVisibility(View.GONE);
binding.swipyRefreshLayout.setRefreshing(false);
if (clearDialogHolder) {
QbDialogHolder.getInstance().clear();
}
QbDialogHolder.getInstance().addDialogs(dialogs);
updateDialogsAdapter();
}
#Override
public void onError(QBResponseException e) {
binding.progressDialogs.setVisibility(View.GONE);
binding.swipyRefreshLayout.setRefreshing(false);
Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
Here is my Chat Activity:-
public class ChatActivity extends BindingActivity<ActivityChatBinding> implements OnImagePickedListener {
ChatViewModel chatViewModel;
public static final int REQUEST_CODE_ATTACHMENT = 721;
public static final String EXTRA_DIALOG_ID = "dialogId";
#Override
protected int getLayoutId() {
return R.layout.activity_chat;
}
public static void startForResult(Activity activity, int code, QBChatDialog dialogId) {
Intent intent = new Intent(activity, ChatActivity.class);
intent.putExtra(ChatActivity.EXTRA_DIALOG_ID, dialogId);
activity.startActivityForResult(intent, code);
}
#Override
public void setInitBinding() {
getWindow().setBackgroundDrawableResource(R.drawable.bg_img);
chatViewModel = new ChatViewModel(this, binding);
binding.setChatViewModel(chatViewModel);
}
#Override
protected void setUpObserver() {
chatViewModel.addObserver(this);
}
#Override
public void update(Observable o, Object arg) {
}
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
#Override
public void onBackPressed() {
binding.getChatViewModel().releaseChat();
binding.getChatViewModel().sendDialogId();
super.onBackPressed();
}
#Override
public void onImagePicked(int requestCode, File file) {
switch (requestCode) {
case REQUEST_CODE_ATTACHMENT:
binding.getChatViewModel().attachmentPreviewAdapter.add(file);
break;
}
}
#Override
public void onImagePickError(int requestCode, Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onImagePickClosed(int requestCode) {
}
}
Chat Activity View Model :-
public class ChatViewModel extends Observable {
public Context mContext;
ActivityChatBinding binding;
public static final String TAG = ChatActivity.class.getSimpleName();
public static final int REQUEST_CODE_ATTACHMENT = 721;
public static final String PROPERTY_SAVE_TO_HISTORY = "save_to_history";
public static final String EXTRA_DIALOG_ID = "dialogId";
public ChatAdapter chatAdapter;
public AttachmentPreviewAdapter attachmentPreviewAdapter;
public QBChatDialog qbChatDialog;
public ArrayList<QBChatMessage> unShownMessages;
public int skipPagination = 0;
public ChatMessageListener chatMessageListener;
QBPrivacyList qbPrivacyList;
public static boolean mBlock;
public static int userId, recipientId;
public QBPrivacyListsManager privacyListsManager;
public ObservableField<String> chatMessage = new ObservableField<>("");
public ChatViewModel(Context mContext, ActivityChatBinding binding) {
this.mContext = mContext;
this.binding = binding;
Log.v(TAG, "onCreate ChaActivity on Thread ID = " + Thread.currentThread().getId());
qbChatDialog = (QBChatDialog) ((Activity) mContext).getIntent().getSerializableExtra(EXTRA_DIALOG_ID);
Log.v(TAG, "deserialized dialog = " + qbChatDialog);
qbChatDialog.initForChat(QBChatService.getInstance());
chatMessageListener = new ChatMessageListener();
qbPrivacyList = new QBPrivacyList();
privacyListsManager = QBChatService.getInstance().getPrivacyListsManager();
qbChatDialog.addMessageListener(chatMessageListener);
initViews();
initChat();
}
public void initViews() {
try {
recipientId = qbChatDialog.getRecipientId();
userId = qbChatDialog.getUserId();
getPrivacyList();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
}
attachmentPreviewAdapter = new AttachmentPreviewAdapter(mContext,
new AttachmentPreviewAdapter.OnAttachmentCountChangedListener() {
#Override
public void onAttachmentCountChanged(int count) {
binding.attachmentContainer.setVisibility(count == 0 ? View.GONE : View.VISIBLE);
}
},
new AttachmentPreviewAdapter.OnAttachmentUploadErrorListener() {
#Override
public void onAttachmentUploadError(QBResponseException e) {
Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show();
}
});
binding.attachmentAdapter.setAdapter(attachmentPreviewAdapter);
}
public void onAttachmentsClick(View view) {
new ImagePickHelper().pickAnImage(((FragmentActivity) mContext), REQUEST_CODE_ATTACHMENT);
}
private void initChat() {
switch (qbChatDialog.getType()) {
case PRIVATE:
loadDialogUsers();
break;
default:
Toaster.shortToast(String.format("%s %s", getString(R.string.chat_unsupported_type), qbChatDialog.getType().name()));
((Activity) mContext).finish();
break;
}
}
public void loadDialogUsers() {
ChatHelper.getInstance().getUsersFromDialog(qbChatDialog, new QBEntityCallback<ArrayList<QBUser>>() {
#Override
public void onSuccess(ArrayList<QBUser> users, Bundle bundle) {
String chatName = QbDialogUtils.getDialogName(qbChatDialog);
binding.dialogName.setText(chatName);
loadChatHistory();
}
#Override
public void onError(QBResponseException e) {
Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show();
}
});
}
public void loadChatHistory() {
ChatHelper.getInstance().loadChatHistory(qbChatDialog, skipPagination, new QBEntityCallback<ArrayList<QBChatMessage>>() {
#Override
public void onSuccess(ArrayList<QBChatMessage> messages, Bundle args) {
Collections.reverse(messages);
if (chatAdapter == null) {
chatAdapter = new ChatAdapter(mContext, qbChatDialog, messages);
chatAdapter.setPaginationHistoryListener(new PaginationHistoryListener() {
#Override
public void downloadMore() {
loadChatHistory();
}
});
chatAdapter.setOnItemInfoExpandedListener(new ChatAdapter.OnItemInfoExpandedListener() {
#Override
public void onItemInfoExpanded(final int position) {
if (isLastItem(position)) {
((Activity) mContext).runOnUiThread(new Runnable() {
#Override
public void run() {
binding.listChat.setSelection(position);
}
});
} else {
binding.listChat.smoothScrollToPosition(position);
}
}
private boolean isLastItem(int position) {
return position == chatAdapter.getCount() - 1;
}
});
if (unShownMessages != null && !unShownMessages.isEmpty()) {
List<QBChatMessage> chatList = chatAdapter.getList();
for (QBChatMessage message : unShownMessages) {
if (!chatList.contains(message)) {
chatAdapter.add(message);
}
}
}
binding.listChat.setAdapter(chatAdapter);
binding.listChat.setAreHeadersSticky(false);
binding.listChat.setDivider(null);
} else {
chatAdapter.addList(messages);
binding.listChat.setSelection(messages.size());
}
binding.progressBar.setVisibility(View.GONE);
}
#Override
public void onError(QBResponseException e) {
binding.progressBar.setVisibility(View.GONE);
skipPagination -= ChatHelper.CHAT_HISTORY_ITEMS_PER_PAGE;
Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show();
}
});
skipPagination += ChatHelper.CHAT_HISTORY_ITEMS_PER_PAGE;
QBRestChatService.markMessagesAsRead(qbChatDialog.getDialogId(), null);
}
public class ChatMessageListener extends QbChatDialogMessageListenerImp {
#Override
public void processMessage(String s, QBChatMessage qbChatMessage, Integer integer) {
showMessage(qbChatMessage);
}
}
public void showMessage(QBChatMessage message) {
if (chatAdapter != null) {
chatAdapter.add(message);
scrollMessageListDown();
} else {
if (unShownMessages == null) {
unShownMessages = new ArrayList<>();
}
unShownMessages.add(message);
}
}
public void scrollMessageListDown() {
binding.listChat.setSelection(binding.listChat.getCount() - 1);
}
public void onSendChatClick(View view) {
int totalAttachmentsCount = attachmentPreviewAdapter.getCount();
Collection<QBAttachment> uploadedAttachments = attachmentPreviewAdapter.getUploadedAttachments();
if (!uploadedAttachments.isEmpty()) {
if (uploadedAttachments.size() == totalAttachmentsCount) {
for (QBAttachment attachment : uploadedAttachments) {
sendChatMessage(null, attachment);
}
} else {
Toaster.shortToast(R.string.chat_wait_for_attachments_to_upload);
}
}
String text = binding.getChatViewModel().chatMessage.get().trim();
if (!TextUtils.isEmpty(text)) {
sendChatMessage(text, null);
}
}
public void sendChatMessage(String text, QBAttachment attachment) {
QBChatMessage chatMessage = new QBChatMessage();
if (attachment != null) {
chatMessage.addAttachment(attachment);
} else {
chatMessage.setBody(text);
}
chatMessage.setProperty(PROPERTY_SAVE_TO_HISTORY, "1");
chatMessage.setDateSent(System.currentTimeMillis() / 1000);
chatMessage.setMarkable(true);
if (!QBDialogType.PRIVATE.equals(qbChatDialog.getType()) && !qbChatDialog.isJoined()) {
Toaster.shortToast("You're still joining a group chat, please wait a bit");
return;
}
try {
qbChatDialog.sendMessage(chatMessage);
if (QBDialogType.PRIVATE.equals(qbChatDialog.getType())) {
showMessage(chatMessage);
}
if (attachment != null) {
attachmentPreviewAdapter.remove(attachment);
} else {
binding.getChatViewModel().chatMessage.set("");
}
} catch (SmackException.NotConnectedException e) {
Log.w(TAG, e);
Toaster.shortToast("Can't send a message, You are not connected to chat");
}
}
public void leaveGroupDialog() {
try {
ChatHelper.getInstance().leaveChatDialog(qbChatDialog);
} catch (XMPPException | SmackException.NotConnectedException e) {
Log.w(TAG, e);
}
}
public void releaseChat() {
qbChatDialog.removeMessageListrener(chatMessageListener);
if (!QBDialogType.PRIVATE.equals(qbChatDialog.getType())) {
leaveGroupDialog();
}
}
public void sendDialogId() {
Intent result = new Intent();
result.putExtra(EXTRA_DIALOG_ID, qbChatDialog.getDialogId());
((Activity) mContext).setResult(RESULT_OK, result);
}
public void finishActivity(View view) {
((Activity) mContext).finish();
}
public void clickButtonBlock(View view) {
AppUtils.dialog(mContext);
if (mBlock) {
onClickUnblock();
} else {
onClickBlock();
}
}
public void getPrivacyList() throws SmackException.NotConnectedException, XMPPException.XMPPErrorException, SmackException.NoResponseException {
QBPrivacyListsManager privacyListsManager = QBChatService.getInstance().getPrivacyListsManager();
QBPrivacyList privacyList = privacyListsManager.getPrivacyList("public");
List<QBPrivacyListItem> items = privacyList.getItems();
int i;
for (i = 0; i < privacyList.getItems().size(); i++) {
QBPrivacyListItem item = items.get(i);
String valueForType = item.getValueForType();
String[] splitvalueType = valueForType.split("-");
String blockId = splitvalueType[0];
if (blockId.equalsIgnoreCase(String.valueOf(recipientId))) {
mBlock = true;
binding.tvBlock.setText("Unblock");
break;
} else {
binding.tvBlock.setText("Block");
}
}
}
}
The problem is chatDialog.getUnreadMessageCount() giving me count 2 when I once enter in chat room and come back to my chat listing page.
Description on issue:-
Example:-
I have installed my application in two devices. when i send message from one (Device A) to other (Device B).The device B will display correct Unread count i.e 1 . Now when i click on chat dialog and get entered inside the chat room (of Device B). and come back to it's listing page and then again try to send message from Device A to device B . This time the unread count comes as 2 but it should be one as i already viewed my previous message. This get more worse if i try to open my chat room again to read the message(Device B) and get back to my listing page(Device B) after reading the message . This time if I send the message from Device A to Device B, Then the count came out as "5" just for my one message this thing is making me sick, I debugged the whole code, it's chatDialog .getUnreadMessageCount() who is returning me count "5", I don't know why my previous messages are not counted as being read messages and why everytime I open chat room one additional number gets added up inside the unread count.Please help me out , i am scratching my head from past two days.
Your help will be greatly Appreciated.
Thanks
Problem is that your AllDialogsMessageListener is not getting unregistered so unregister it by calling unregisterQbChatListeners(); when you will be opening your chat room screen . Every thing will work fine once you do that.
This what i mean :-
binding.listDialogsChats.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
QBChatDialog selectedDialog = (QBChatDialog) parent.getItemAtPosition(position);
if (currentActionMode == null) {
unregisterQbChatListeners();
ChatActivity.startForResult(((Activity) mContext), REQUEST_DIALOG_ID_FOR_UPDATE, selectedDialog);
} else {
dialogsAdapter.toggleSelection(selectedDialog);
}
}
});
private void unregisterQbChatListeners() {
if (incomingMessagesManager != null) {
incomingMessagesManager.removeDialogMessageListrener(allDialogsMessagesListener);
}
if (systemMessagesManager != null) {
systemMessagesManager.removeSystemMessageListener(systemMessagesListener);
}
dialogsManager.removeManagingDialogsCallbackListener(this);
}
cheers!!!
Please use this code below :
QBChatService.markMessagesAsRead("YOUR_DIALOG_ID", null, new QBEntityCallback<Void>() {
#Override
public void onSuccess(Void aVoid, Bundle bundle) {
QBRequestGetBuilder requestBuilder = new QBRequestGetBuilder();
requestBuilder.eq("_id", Team.getCurrent().getChatId());
QBChatService.getChatDialogs(null, requestBuilder, new QBEntityCallback<ArrayList<QBDialog>>() {
#Override
public void onSuccess(ArrayList<QBDialog> qbDialogs, Bundle bundle) {
if (qbDialogs != null && qbDialogs.size() > 0) {
QBDialog dialog = qbDialogs.get(0);//here you get your dialog with unreadMessageCount = 0
}
}
#Override
public void onError(QBResponseException e) {
}
});
}
#Override
public void onError(QBResponseException e) {
}
});

Refresh Listview of another fragment

I'm Using viewpager with 2 swiping tab layouts. In the first tablayout I post data to the server and when I switch the tab the Listview in not update. Only when I click on Listview Item and close it the Listview gets refreshed and the posted data is visible...
Question Is : How to automatically refresh Listview when data is posted to server can some one help please.
public class PagerAdapter extends FragmentStatePagerAdapter {
int numOfTabs;
public PagerAdapter(FragmentManager fm,int numOfTabs) {
super(fm);
this.numOfTabs=numOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
RaiseComplaintFragment RFragment=new RaiseComplaintFragment();
return RFragment;
case 1:
ComplaintListFragment CFragment=new ComplaintListFragment();
return CFragment;
default:
return null;
}
}
#Override
public int getCount() {
return numOfTabs;
}
}
This is the method which posts data to the server
public void postDataToServer(String complaintdata) throws JSONException {
String url = URLMap.getPostComplaintUrl();
String roleId = LoggedInUserStore.getLoggedInRoleId(getContext());
String branchId = LoggedInUserStore.getLoggedInBranchId(getContext());
String compid = LoggedInUserStore.getLoggedInCompanyId(getContext());
HashMap<String, String> params = new HashMap<>();
params.put("CallRecordID", "0"); //pass 0 if we are inserting a new record always
params.put("CompanyID", compid);
params.put("BranchID", branchId);
params.put("ServiceID", sId);
params.put("CallLocationID", lId);
params.put("RaisedByID", roleId);
params.put("ComplaintDetails", complaintdata);
params.put("CallStatusID", "1");
pDialog = new ProgressDialog(getContext());
pDialog.setMessage("Please wait..");
pDialog.setProgressStyle(pDialog.STYLE_SPINNER);
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
JsonObjectRequest req = new JsonObjectRequest(url, new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Complaint has been registered successfully");
builder.setMessage("").setCancelable(true);
AlertDialog alertDialog = builder.create();
alertDialog.show();
_complaintText.setText("");
serviceSpinner.setSelection(0);
locationSpinner.setSelection(0);
pDialog.dismiss();
/*((HomeActivity)getActivity()).getViewPager().setCurrentItem(1); //onCLick of Submit it just switches the tab
String tagName="android:switcher:"+R.id.pager+":"+1;
ComplaintListFragment f2=(ComplaintListFragment)getActivity().getSupportFragmentManager().findFragmentByTag(tagName);
f2.fetchComplaintData();*/
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Unable to register your request.\nPlease try later.");
builder.setCancelable(true);
AlertDialog alertDialog = builder.create();
alertDialog.show();
pDialog.dismiss();
}
});
req.setRetryPolicy(new VolleyRetryPolicy().getRetryPolicy());
RequestQueue requestQueue = ((VolleyRequestQueue) getActivity().getApplication()).getRequestQueue();
requestQueue.add(req);
}
My HomeActivity class which handles two tab layouts
viewPager = (ViewPager) findViewById(R.id.view_Pager);
tabLayout = (TabLayout) findViewById(R.id.tab_Layout);
String roleID = LoggedInUserStore.getLoggedInRoleId(getApplicationContext());
if (roleID.equals("4")) {
//RAISE COMPLAINT UI. IF ROLE ID == 4 MANAGER DASHBOARD
tabLayout.addTab(tabLayout.newTab().setText("Raise Complaint"));
tabLayout.addTab(tabLayout.newTab().setText("Complaint List"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final PagerAdapter adapter =
new com.six30labs.cms.adapters.PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
Second fragment which contains my listview
public class ComplaintListFragment extends Fragment {
private ListView complaintListView;
EditText _inputSearch;
ComplaintAdapter compadapter;
private static Parcelable mListViewScrollPos = null;
private RequestQueue mQueue;
ProgressBar progressBar;
String URL;
private View v;
String TAG="Second Fragment";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_complaint_list, container, false);
complaintListView = (ListView) v.findViewById(R.id.complaintListView);
_inputSearch = (EditText) v.findViewById(R.id.inputSearchforComplaintListFragment);
progressBar = (ProgressBar) v.findViewById(R.id.complaintListProgressBar);
fetchComplaintData();
_inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
compadapter.getFilter().filter(s.toString());
compadapter.notifyDataSetChanged();
}catch (NullPointerException e){
e.printStackTrace();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
if (mListViewScrollPos != null) {
complaintListView.onRestoreInstanceState(mListViewScrollPos);
}
return v;
}
public void fetchComplaintData() {
progressBar.setVisibility(View.VISIBLE);
URL = URLMap.getComplaintUrl("complaint_url");
URL = URL.replace("{id}", LoggedInUserStore.getLoggedInCompanyId(getContext()));
StringRequest request = new StringRequest(Request.Method.GET,URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
getCompliantList(response);
progressBar.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
request.setRetryPolicy(new VolleyRetryPolicy().getRetryPolicy());
RequestQueue queue=((VolleyRequestQueue)getActivity().getApplication()).getRequestQueue();
queue.add(request);
/* RequestQueue requestQueue
= Volley.newRequestQueue(getContext());
requestQueue.add(request);*/
}
public void getCompliantList(String response) {
try {
List complaint = new ArrayList<>();
JSONArray jArray = new JSONArray(response);
for (int i = 0; i < jArray.length(); i++) {
// complaint.add(Complaint.fromJson(jArray.getJSONObject(i)));
complaint.add(0,Complaint.fromJson(jArray.getJSONObject(i))); //To push the data to the top of the listview.
}
compadapter = new ComplaintAdapter(getContext(), complaint);
complaintListView.setAdapter(compadapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
//Method that will save the position the user when they scroll
//return it when the user comes back to the listView instead of it refreshing the data.
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mListViewScrollPos = complaintListView.onSaveInstanceState();
}
public void onPause() {
super.onPause();
}
public void onResume() {
super.onResume();
fetchComplaintData();
}
BroadcastReceiver For class Where your Listview is
private BroadcastReceiver updateProfileBroadcast = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Fire your event
}
};
Register Broadcast in onResume()
registerReceiver(updateProfileBroadcast, new IntentFilter("KEY"));
Now fire Broadcast From Fragment
Intent intent = new Intent("KEY");
getActivity().sendBroadcast(intent);
As an alternative to SID's answer you may use EventBus. It works by event-driven architecture and able to transfer information between components really easy and fast.
That's how you use it:
1) add to project in app gradle: compile 'org.greenrobot:eventbus:3.0.0'
2) Register EventBus in fragment's onCreate() where you need to update ListView: eventBus.register(this);. And don't forget to unregister it on onDestryView(): eventBus.unregister(this);
3) Add the method to your ListView fragment which will handle event with list update:
#SupressWarning("unused")
#Subscribe
public void onEvent(List<YourListViewData> event) {/* update `ListView` */};
4) Fire that event from activity\fragment when you need to update ListView:
EventBus bus = EventBus.getInstance();
eventBus.post(List<YourListViewData> yourData);

Android DialogFragment and EditText not restoring state

Please help me. I don't know why, but after screen rotation EditText is empty. I use setRetainInstance(true), but it doesn't help for me. Please tell me what is the right way to save dialog's state and EditText's state with selection and text
My code:
public class InputTextDialog extends DialogFragment implements OnClickListener {
static final String DIALOG_TAG = "InputTextDialog";
static EditText input;
String initialText;
InputTextDialogListener inputTextDialogListener = null;
public interface InputTextDialogListener {
void onChangeText(String text);
}
public void setInputTextDialogListener(InputTextDialogListener listener) {
inputTextDialogListener = listener;
}
public void setInitialText(String text) {
initialText = text;
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public void onDestroyView() {
if (getDialog() != null && getRetainInstance())
getDialog().setDismissMessage(null);
super.onDestroyView();
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
input = new EditText(getActivity());
input.setHint("Enter your text");
if (initialText != null) {
input.setText(initialText);
} else {
input.setText("");
}
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity())
.setTitle("Enter your text").setPositiveButton("Apply", this)
.setNegativeButton("Cancel", this).setView(input);
return adb.create();
}
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == Dialog.BUTTON_POSITIVE && inputTextDialogListener != null) {
inputTextDialogListener.onChangeText(input.getText().toString());
}
}
}
Show dialog in activity:
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
InputTextDialog inputDialog = new InputTextDialog();
inputDialog.setInitialText(initialText);
inputDialog.setInputTextDialogListener(new InputTextDialogListener() {
#Override
public void onChangeText(String text) {
resultText = text;
}
});
inputDialog.show(getSupportFragmentManager(), InputTextDialog.DIALOG_TAG);
}
});
Thanks I solved this by:
package com.xfakehopex.lovelywidget.Dialogs;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.EditText;
public class InputTextDialog extends DialogFragment implements OnClickListener {
public static final String DIALOG_TAG = "InputTextDialog";
private static final String DIALOG_TITLE_BUNDLE= "dialogTitle";
private static final String DIALOG_TEXT_BUNDLE= "dialogText";
private static final String DIALOG_TEXT_SELECTION_START_BUNDLE = "dialogTextSelectionStart";
private static final String DIALOG_TEXT_SELECTION_END_BUNDLE = "dialogTextSelectionEnd";
private EditText input;
private String initialText;
private String title;
InputTextDialogListener inputTextDialogListener = null;
public interface InputTextDialogListener {
void onChangeText(String text);
}
public void setInputTextDialogListener(InputTextDialogListener listener) {
inputTextDialogListener = listener;
}
public void setInitialText(String text) {
initialText = text;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
input = new EditText(getActivity());
input.setHint("Введите текст");
if (savedInstanceState != null) {
String text = savedInstanceState.getString(DIALOG_TEXT_BUNDLE);
title = savedInstanceState.getString(DIALOG_TITLE_BUNDLE);
int selectionStart = savedInstanceState.getInt(DIALOG_TEXT_SELECTION_START_BUNDLE);
int selectionEnd = savedInstanceState.getInt(DIALOG_TEXT_SELECTION_END_BUNDLE);
input.setText(text);
input.setSelection(selectionStart, selectionEnd);
}
else
{
if (initialText != null) {
input.setText(initialText);
} else {
input.setText("");
}
}
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity())
.setTitle(title).setPositiveButton("Apply", this)
.setNegativeButton("Cancel", this).setView(input);
return adb.create();
}
#Override
public void onSaveInstanceState(Bundle saved) {
super.onSaveInstanceState(saved);
saved.putString(DIALOG_TEXT_BUNDLE, input.getText().toString());
saved.putString(DIALOG_TITLE_BUNDLE, title);
saved.putInt(DIALOG_TEXT_SELECTION_START_BUNDLE, input.getSelectionStart());
saved.putInt(DIALOG_TEXT_SELECTION_END_BUNDLE, input.getSelectionEnd());
}
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == Dialog.BUTTON_POSITIVE && inputTextDialogListener != null) {
inputTextDialogListener.onChangeText(input.getText().toString());
}
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}

How to Flurry Intigration with FlurryAdListener in android

i want to integrate flurry in my app. in the following code i am integrate flurry but that was not working properly in android. flurry listener call its method two times. how it working please help me.
LoginActivity.java
public class LoginActivity extends Activity implements OnClickListener,
AsyncTaskCompleteListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance = this;
setContentView(R.layout.login_activity);
Map<String, String> map = new HashMap<String, String>();
map.put("url", NFLConstanants.LOGIN_URL);
map.put("username", strUser);
map.put("passwd", strPassword);
new ParseController(LoginActivity.this, map,
NFLConstanants.SERVICE_CODE0, 1);
}
#Override
protected void onStart() {
super.onStart();
System.out.println("call on start method");
FlurryAgent.onStartSession(this, MACUtils.APIKEY_FLURRY);
FlurryAgent.enableTestAds(true);
FlurryAgent.initializeAds(this);
FlurryAgent.setLogEnabled(true);
}
#Override
protected void onStop() {
super.onStop();
System.out.println("call on stop method");
FlurryAgent.onEndSession(this);
}
#Override
public void onTaskCompleted(String responce, int sc) {
if (FlurryAgent.isAdAvailable(LoginActivity.this,
MACUtils.myAdSpaceName,
FlurryAdSize.FULLSCREEN, MACUtils.timeout)) {
final String msgv = "To help keep this app free please watch this short video. Thanks";
AlertDialog.Builder dlg = new AlertDialog.Builder(
LoginActivity.this);
dlg.setCancelable(false);
dlg.setTitle("Message");
dlg.setMessage(msgv);
dlg.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
try {
MyAdListener myAdListener = new MyAdListener(
LoginActivity.this,
LoginActivity.this, "3");
FlurryAgent
.setAdListener(myAdListener);
FrameLayout container = new FrameLayout(
LoginActivity.this);
FlurryAgent
.getAd(LoginActivity.this,
MACUtils.myAdSpaceName,
container,
FlurryAdSize.FULLSCREEN,
MACUtils.timeout);
} catch (Exception e) {
e.printStackTrace();
}
}
});
AlertDialog alert = dlg.create();
alert.show();
}
}
}
MyAdListener.java
public class MyAdListener implements FlurryAdListener {
public Activity activity;
public Context ctx;
String pagePosition;
boolean isDialogLaunch = false;
public MyAdListener(Activity act, Context ctx, String page) {
this.activity = act;
this.pagePosition = page;
this.ctx = ctx;
this.isDialogLaunch = false;
}
#Override
public boolean shouldDisplayAd(String myAdSpaceName, FlurryAdType type) {
System.out.println("shouldDisplayAd:: " + type);
return true;
}
#Override
public void onAdClosed(String myAdSpaceName) {
System.out.println("onAdClosed::: " + myAdSpaceName);
if (pagePosition.equals("1") || pagePosition.equals("2")) {
actionOnFlurryVideo();
} else {
if (!FlurryAgent.isAdAvailable(activity, MACUtils.myAdSpaceName,
FlurryAdSize.FULLSCREEN, MACUtils.timeout)) {
Intent macIntent = new Intent(activity, MACCustomTab.class);
macIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(macIntent);
activity.finish();
}
}
}
#Override
public void onApplicationExit(String myAdSpaceName) {
System.out.println("onApplicationExit:: " + myAdSpaceName);
actionOnFlurryVideo();
}
#Override
public void onRenderFailed(String adSpace) {
System.out.println("onRenderFailed:: " + adSpace);
actionOnFlurryVideo();
}
#Override
public void spaceDidReceiveAd(String adSpace) {
System.out.println("spaceDidReceiveAd:: " + adSpace);
}
#Override
public void spaceDidFailToReceiveAd(String adSpace) {
System.out.println("spaceDidFailToReceiveAd:: " + adSpace);
}
#Override
public void onAdClicked(String id) {
System.out.println("onAdClicked:: " + id);
}
#Override
public void onAdOpened(String id) {
System.out.println("onAdOpened::: " + id);
}
public void actionOnFlurryVideo() {
System.out.println("call actionOnflurryvideo");
if (pagePosition.equals("1") || pagePosition.equals("2")) {
if (!isDialogLaunch) {
isDialogLaunch = true;
final String msg = "Thanks for supporting our free website. Your bet has now been confirmed.";
AlertDialog.Builder dlg = new AlertDialog.Builder(ctx);
dlg.setCancelable(false);
dlg.setTitle("Message");
dlg.setMessage(msg);
dlg.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
NavigationGroupActivity parent = ((NavigationGroupActivity) activity
.getParent());
parent.backToFirst();
}
});
AlertDialog alert = dlg.create();
alert.show();
}
} else {
Intent macIntent = new Intent(activity, MACCustomTab.class);
macIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(macIntent);
activity.finish();
}
}
}
This issue will be fixed in our next release which is expected to come out very soon.
(Full disclosure: I work in the Support team at Flurry)

Categories

Resources