How to update the recyclerview that has deleted all data - java

I am migrating from SQL to ORM Room. I followed a tutorial, it usually worked to insert data, but when I delete an item it does not disappear. I have to open and close the App to show it is gone.
The tutorial I followed is this: https://medium.com/#anujguptawork/note-making-application-using-sqlite-vs-room-part-2-using-room-becf92672e29
public class MainActivity extends AppCompatActivity implements Contrato.MainViewInterface {
#BindView(R.id.recyclerHome)
RecyclerView recyclerView;
private HomeAdapter adapter;
private List<Clientes> clientesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
initViews();
loadNotes();
}
private void initViews() {
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
}
private void loadNotes(){
ClienteRepository.getInstance(this).getNotes(this);
}
#OnClick(R.id.fabAdicionar)
public void addNote(){
Intent i = new Intent(MainActivity.this, AdicionarActivity.class);
startActivity(i);
}
#OnClick(R.id.buttonDeletar)
public void buttonDeletar(){
ClienteRepository.getInstance(this).deletarNotes();
}
#Override
public void onNotesLoaded(List<Clientes> clientesList) {
clientesList = clientesList;
if(clientesList.size() == 0){
onDataNotAvailable();
}else {
adapter = new HomeAdapter(this, clientesList);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onDataNotAvailable() {
Toast.makeText(this,"Adicione uma nota",Toast.LENGTH_SHORT).show();
}
}
public class ClienteRepository {
private Context context;
private static ClienteRepository _instance;
private ClienteRoomDatabase db;
public static ClienteRepository getInstance(Context context) {
if (_instance == null) {
_instance = new ClienteRepository(context);
}
return _instance;
}
public ClienteRepository(Context context) {
this.context = context;
db = ClienteRoomDatabase.getClienteDatabase(context);
}
public void getNotes(final Contrato.MainViewInterface mainViewInterface) {
db.clienteDAO().getAllClientes().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<List<Clientes>>() {
#Override
public void accept(List<Clientes> notes) throws Exception {
mainViewInterface.onNotesLoaded(notes);
}
});
}
public void addNotes(final Contrato.AddNoteViewInterface addNoteViewInterface, final String nome) {
Completable.fromAction(new Action() {
#Override
public void run() throws Exception {
Clientes clientes = new Clientes(nome);
db.clienteDAO().insert(clientes);
}
}).observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io()).subscribe(new CompletableObserver() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onComplete() {
addNoteViewInterface.onNoteAdded();
}
#Override
public void onError(Throwable e) {
addNoteViewInterface.onDataNotAvailable();
}
});
}
public void deletarNotes() {
Completable.fromAction(new Action() {
#Override
public void run() throws Exception {
db.clienteDAO().deleteAll();
}
}).observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io()).subscribe(new CompletableObserver() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onComplete() {
}
#Override
public void onError(Throwable e) {
}
});
}
}
#Dao
public interface ClienteDAO {
#Insert
void insert(Clientes clientes);
#Query("DELETE FROM table_clientes")
void deleteAll();
#Query("SELECT * FROM table_clientes ORDER BY name ASC")
Maybe<List<Clientes>> getAllClientes();
}

Remove item from your dataset of your adapter then call adapter.notifyItemRemoved(position)

Related

How to implement admob rewarded video ads in a list view?

I want to know how to implement AdMob rewarded video ads in a list view?
I'm using the source code from here
and I want to use it in this class StickerPackDetailsActivity.java
and the layout is gonna like this
![layout][1]
I want to lock add to WhatsApp and unlock it by watching video reward.
but this stickerdetails showed from listview from
![here][2]
so, how to implement video reward ads only in 1 specified item of the listview not all of them?
public class MainActivity extends AppCompatActivity implements RewardedVideoAdListener {
private RewardedVideoAd mRewardedVideoAd;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this,"ca-app-pub111111111");
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
listitem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadRewardedVideoAd();
}
});
}
private void loadRewardedVideoAd() {
mRewardedVideoAd.loadAd("ca-app-pub-",
new AdRequest.Builder().build());
}
#Override
public void onRewardedVideoAdLoaded() {
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
#Override
public void onRewardedVideoCompleted() {
}
#Override
protected void onPause() {
mRewardedVideoAd.pause(this);
super.onPause();
}
#Override
protected void onResume() {
mRewardedVideoAd.resume(this);
super.onResume();
}
}

What to set on textview from the JSON response I'm getiing through retrofit for DashboardResponse?

I'm getting nullPointerException when I try to set data to textviews from the JSON response,I'm getting through retrofit. I would like to set the total sale, total expense and total purchase values to the textviews:
tv_total_purchase_today,
tv_total_sale_today,
tv_total_expense_today
What should I put in the setsaleInformations method?
Here's my code:
API Response
public class DashboardResponse extends CommonResponse {
#Expose
#SerializedName("graph_data")
private ArrayList<Graph> graph_data;
#Expose
#SerializedName("total_sale")
private String total_sale;
#Expose
#SerializedName("total_purchase")
private String total_purchase;
#Expose
#SerializedName("total_expense")
private String total_expense;
public ArrayList<Graph> getGraph_data() {
return graph_data;
}
public void setGraph_data(ArrayList<Graph> graph_data) {
this.graph_data = graph_data;
}
public String getTotal_sale() {
return total_sale;
}
public void setTotal_sale(String total_sale) {
this.total_sale = total_sale;
}
public String getTotal_purchase() {
return total_purchase;
}
public void setTotal_purchase(String total_purchase) {
this.total_purchase = total_purchase;
}
public String getTotal_expense() {
return total_expense;
}
public void setTotal_expense(String total_expense) {
this.total_expense = total_expense;
}
}
API Interactor Implementation
#Override
public void getDashboard(final DashboardListener dashboardListener) {
Call<DashboardResponse> call = apiServiceInterface.getDashboard();
call.enqueue(new Callback<DashboardResponse>() {
#Override
public void onResponse(Call<DashboardResponse> call, Response<DashboardResponse> response) {
if(isResponseValid(response) && response.body().isSuccess()){
dashboardListener.onDashboardFetch(response.body());
}else{
dashboardListener.onFailed(prepareFailedMessage(response), APIConstants.DASHBOARD);
}
}
Dashboard Fragment
public class DashboardFragment extends Fragment {
private Context context;
private SalesUtils salesUtils;
private DashboardResponse dashboardResponse;
private HomePresenter homePresenter;
private HomeView homeView;
#BindView(R.id.tv_total_sale_today)
TextView tv_total_sale_today;
#BindView(R.id.tv_total_purchase_today)
TextView tv_total_purchase_today;
#BindView(R.id.tv_total_expense_today)
TextView tv_total_expense_today;
#BindView(R.id.cv_sale_today)
CardView cv_sale_today;
#BindView(R.id.cv_purchase_today)
CardView cv_purchase_today;
#BindView(R.id.cv_expense_today)
CardView cv_expense_today;
private ArrayList<Sale> salesToday;
private ArrayList<Product> productSoldToday;
private SimpleDateFormat simpleDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
public DashboardFragment() {
// Required empty public constructor
}
public static DashboardFragment newInstance(HomePresenter homePresenter) {
DashboardFragment fragment = new DashboardFragment();
fragment.initializeSaleInfo(homePresenter);
return fragment;
}
private void initializeSaleInfo(HomePresenter homePresenter) {
this.homePresenter = homePresenter;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
homeView = (HomeView) getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_dashboard, container, false);
ButterKnife.bind(this, rootView);
cv_sale_today.startAnimation(AnimationUtils.loadSlideInLeftAnimation(context));
cv_purchase_today.startAnimation(AnimationUtils.loadFadeInAnimation(context));
cv_expense_today.startAnimation(AnimationUtils.loadSlideInRightAnimation(context));
homePresenter.fetchDashboard();
setListeners();
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
if(homeView!=null) {
homeView.changeSearchState(false);
}
}
#Override
public void onPause() {
super.onPause();
if(homeView != null)
homeView.setIsInSaleInfo(false);
}
public void setSaleInformations() {
if (getActivity() != null && isAdded())
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
tv_total_purchase_today.setText();
tv_total_sale_today.setText();
tv_total_expense_today.setText();
}
});
}
private Thread resumeSaleInfo = new Thread(new Runnable() {
#Override
public void run() {
salesToday = salesUtils.getSalesDuring(ApplicationUtils.getStartingDateTime(simpleDateTimeFormat.format(System.currentTimeMillis())), ApplicationUtils.getEndingDateTime(simpleDateTimeFormat.format(System.currentTimeMillis())));
if (getActivity() != null && isAdded())
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
tv_total_purchase_today.setText(ApplicationUtils.getBengaliNumber(salesToday.size() + "") + " " + getString(R.string.buy_today_label));
tv_total_sale_today.setText(ApplicationUtils.currencyFormat(SalesUtils.getTotalSale(salesToday)));
tv_total_expense_today.setText(ApplicationUtils.getBengaliNumber(SalesUtils.countUnitSold(productSoldToday) + "") + " " + getString(R.string.unit_sold));
}
});
}
});
private void setListeners() {
cv_sale_today.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
homePresenter.showSaleAt(simpleDateTimeFormat.format(System.currentTimeMillis()));
}
});
cv_purchase_today.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
homePresenter.showSaleAt(simpleDateTimeFormat.format(System.currentTimeMillis()));
}
});
cv_expense_today.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
homePresenter.showUnitSold(simpleDateTimeFormat.format(System.currentTimeMillis()), simpleDateTimeFormat.format(System.currentTimeMillis()));
}
});
}
public void setDashboard(DashboardResponse dashboardResponse) {
Log.e("DASHBOARD", new Gson().toJson(dashboardResponse));
this.dashboardResponse = dashboardResponse;
setSaleInformations();
}
}
That means either the text views haven't loaded onto the screen yet or the views haven't been initialized yet.

Cannot call method from another activity

I cannot call method from another activity in OnNotificationPosted. I also tried to make instance of activity but failed. I searched alot but no success. please help
NotificationListener
public class NotificationListener extends NotificationListenerService {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
otherActivity oth = new otherActivity();
oth.loc();
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i("Msg", "Notification Removed");
}
}
otherActivity
public class OtherActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_other);
}
public void loc() {
//code body
}
}
public class OtherActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_other);
}
public static void loc(){
//code body
}
}
how to using : otherActivity.loc();
public class NotificationListener extends NotificationListenerService {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
otherActivity.loc();
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i("Msg","Notification Removed");
}

Unable to resolve 'AppCompatPreferenceActivity' in SettingsActivity

I have an AppCompatPreferenceActivity.java. But it shows an error in this
public class SettingsActivity extends AppCompatPreferenceActivity
It says it couldn't resolve 'AppCompatPreferenceActivity'.
And it seems like I am the only one with this problem. Any idea?
Error:(21, 39) error: cannot find symbol class AppCompatPreferenceActivity
AppCompatPreferenceActivity does not existing in google support libary,
you should create a class with same name and use this source:
public abstract class AppCompatPreferenceActivity extends PreferenceActivity {
private AppCompatDelegate mDelegate;
#Override
protected void onCreate(Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
getDelegate().onPostCreate(savedInstanceState);
}
public ActionBar getSupportActionBar() {
return getDelegate().getSupportActionBar();
}
public void setSupportActionBar(#Nullable Toolbar toolbar) {
getDelegate().setSupportActionBar(toolbar);
}
#Override
public MenuInflater getMenuInflater() {
return getDelegate().getMenuInflater();
}
#Override
public void setContentView(#LayoutRes int layoutResID) {
getDelegate().setContentView(layoutResID);
}
#Override
public void setContentView(View view) {
getDelegate().setContentView(view);
}
#Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().setContentView(view, params);
}
#Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().addContentView(view, params);
}
#Override
protected void onPostResume() {
super.onPostResume();
getDelegate().onPostResume();
}
#Override
protected void onTitleChanged(CharSequence title, int color) {
super.onTitleChanged(title, color);
getDelegate().setTitle(title);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getDelegate().onConfigurationChanged(newConfig);
}
#Override
protected void onStop() {
super.onStop();
getDelegate().onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
getDelegate().onDestroy();
}
public void invalidateOptionsMenu() {
getDelegate().invalidateOptionsMenu();
}
private AppCompatDelegate getDelegate() {
if (mDelegate == null) {
mDelegate = AppCompatDelegate.create(this, null);
}
return mDelegate;
}
}

how to work with the loader when the screen is rotated

I try to use Loaders instead AsyncTask.I can not figure out how to correctly organize the conservation status when the screen is rotated. I receive information from Json and trying create list.
public class FragmentWeatherTestApplication extends Fragment
implements LoaderManager.LoaderCallbacks<List<WeatherItem>> {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
getLoaderManager().initLoader(0,null,this).forceLoad();
}
...
#Override
public Loader<List<WeatherItem>> onCreateLoader(int id, Bundle args) {
Log.i(TAG, "onCreateLoader");
return new FetchWeatherLoader(getActivity());
}
#Override
public void onLoadFinished(Loader<List<WeatherItem>> loader, List<WeatherItem> data) {
Log.i(TAG, "onLoadFinished");
mItems = data;
setupAdapter();
}
#Override
public void onLoaderReset(Loader<List<WeatherItem>> loader) {
Log.i(TAG, "onLoaderReset");
}
....
private static class FetchWeatherLoader extends AsyncTaskLoader<List<WeatherItem>>{
public FetchWeatherLoader(Context context) {
super(context);
}
#Override
public List<WeatherItem> loadInBackground() {
return new OpenWeatherFetch().fetchItems();
}
}

Categories

Resources