I am getting the following error when building my project using a Room Database.
C:\Users\russelg1\AndroidStudioProjects\CheckingIn\app\src\main\java\com\grgsolutions\checkingin\CheckInTableDao.java:19: error: Unused parameter: checkInTablePrimaryKey
List findCheckIn(int checkInTablePrimaryKey);
This is the DAO for the table in question
package com.grgsolutions.checkingin;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.Query;
import java.util.List;
#Dao
public interface CheckInTableDao {
#Insert
void insertCheckIn(CheckInTable... checkInTable);
#Query("DELETE FROM check_in_table WHERE checkInTablePrimaryKey = :checkInTablePrimaryKey")
void deleteCheckIn(int checkInTablePrimaryKey);
#Query("SELECT * FROM check_in_table")
LiveData<List<CheckInTable>> getAllCheckIn();
#Query("SELECT * FROM check_in_table where checkInTablePrimaryKey = checkInTablePrimaryKey")
List<CheckInTable> findCheckIn(int checkInTablePrimaryKey);
#Query("DELETE FROM check_in_table")
void deleteAllCheckIn();
}
This is the Room Repository for the table.
package com.grgsolutions.checkingin;
import android.content.Context;
import android.os.AsyncTask;
import android.text.PrecomputedText;
import android.util.Log;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import java.util.List;
import static androidx.constraintlayout.widget.Constraints.TAG;
public class CheckInTableRepository {
private MutableLiveData<List<CheckInTable>> searchCheckInResults =
new MutableLiveData<>();
private LiveData<List<CheckInTable>> allCheckIn;
private List<CheckInTable> foundCheckIn;
private CheckInTableDao checkInTableDao;
public CheckInTableRepository(Context appContext) {
CheckingInRoomDatabase db;
db = CheckingInRoomDatabase.getDatabase(appContext);
checkInTableDao = db.checkInTableDao();
allCheckIn = checkInTableDao.getAllCheckIn();
foundCheckIn = checkInTableDao.findCheckIn(0);
}
public LiveData<List<CheckInTable>> getAllCheckIn() {
Log.i(TAG, "getAllCheckIn: creating allCheckIn ");
return allCheckIn;
}
public void insertCheckIn(CheckInTable newcheckin) {
CheckInTableRepository.InsertAsyncTask task = new
CheckInTableRepository.InsertAsyncTask(checkInTableDao);
task.execute(newcheckin);
}
public void deleteCheckIn(int checkInTablePrimaryKey) {
CheckInTableRepository.DeleteAsyncTask task = new
CheckInTableRepository.DeleteAsyncTask(checkInTableDao);
task.execute();
}
public CheckInTable findCheckIn(int checkInTablePrimaryKey) {
CheckInTableRepository.QueryAsyncTask task = new
CheckInTableRepository.QueryAsyncTask(checkInTableDao);
task.delegate = this;
task.execute(checkInTablePrimaryKey);
}
private void asyncFinished(List<CheckInTable> result) {
foundCheckIn = result;
}
private static class QueryAsyncTask extends
AsyncTask<Integer, Void, List<CheckInTable>> {
private CheckInTableDao asyncTaskDao;
private CheckInTableRepository delegate = null;
QueryAsyncTask(CheckInTableDao dao) {
asyncTaskDao = dao;
}
#Override
protected List<CheckInTable> doInBackground(final Integer... params) {
return asyncTaskDao.findCheckIn(params[0]);
}
protected void onPostExecute(List<CheckInTable> result) {
delegate.asyncFinished(result);
}
}
private static class InsertAsyncTask extends AsyncTask<CheckInTable, Void, Void> {
private CheckInTableDao asyncTaskDao;
InsertAsyncTask(CheckInTableDao dao) {
asyncTaskDao = dao;
}
#Override
protected Void doInBackground(final CheckInTable... params) {
asyncTaskDao.insertCheckIn(params[0]);
return null;
}
}
private static class DeleteAsyncTask extends AsyncTask<Integer, Void, Void> {
private CheckInTableDao asyncTaskDao;
DeleteAsyncTask(CheckInTableDao dao) {
asyncTaskDao = dao;
}
#Override
protected Void doInBackground(final Integer... params) {
asyncTaskDao.deleteCheckIn(params[0]);
return null;
}
}
}
This is the View Model
package com.grgsolutions.checkingin;
import android.content.Context;
import android.util.Log;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;
import java.util.List;
import static androidx.constraintlayout.widget.Constraints.TAG;
public class MainViewModel extends ViewModel {
private CheckInRecipientsTableRepository checkInRecipientsTableRepository;
private LiveData<List<CheckInRecipientsTable>> allRecipients;
private ContactGroupsTableRepository contactGroupsTableRepository;
private LiveData<List<ContactGroupsTable>> allContactGroups;
private ContactTableRepository contactTableRepository;
private LiveData<List<ContactTable>> allContacts;
private CheckInTableRepository checkInTableRepository;
private LiveData<List<CheckInTable>> allCheckIn;
private List<CheckInTable> foundCheckIn;
public MainViewModel (Context appContext) {
//super(appContext);
Log.i(TAG, "MainViewModel: In the Main View Model");
checkInRecipientsTableRepository = new CheckInRecipientsTableRepository(appContext);
allRecipients = checkInRecipientsTableRepository.getAllCheckInRecipients();
Log.i(TAG, "MainViewModel: In the Main View Model");
checkInTableRepository = new CheckInTableRepository(appContext);
allCheckIn = checkInTableRepository.getAllCheckIn();
//checkInTableRepository = new CheckInTableRepository(appContext);
//foundCheckIn = checkInTableRepository.findCheckIn();
Log.i(TAG, "MainViewModel: In the Main View Model");
contactGroupsTableRepository = new ContactGroupsTableRepository(appContext);
allContactGroups = contactGroupsTableRepository.getAllContactGroups();
Log.i(TAG, "MainViewModel: In the Main View Model");
contactTableRepository = new ContactTableRepository(appContext);
allContacts = contactTableRepository.getAllContact();
}
LiveData<List<CheckInTable>> getAllCheckIn() {
Log.i(TAG, "getAllCheckIn: in main view model");
return allCheckIn;
}
public void findCheckIn(int checkInTablePrimaryKey) {
checkInTableRepository.findCheckIn(checkInTablePrimaryKey);
}
public void insertCheckIn(CheckInTable checkInTable) {
checkInTableRepository.insertCheckIn(checkInTable);
}
public void deleteCheckIn(int checkInTablePrimaryKey) {
checkInTableRepository.deleteCheckIn(checkInTablePrimaryKey);
}
LiveData<List<CheckInRecipientsTable>> getAllCheckInRecipients() {
return allRecipients;
}
public void insertCheckInRecipientsTable(CheckInRecipientsTable checkInRecipientsTable) {
checkInRecipientsTableRepository.insertCheckInRecipientsTable(checkInRecipientsTable);
}
public void deleteCheckInRecipient(int checkInPrimaryKey) {
checkInRecipientsTableRepository.deleteCheckInRecipient(checkInPrimaryKey);
}
public void deleteCheckInRecipientForCheckIn(int checkInPrimaryKey) {
checkInRecipientsTableRepository.deleteCheckInRecipientForCheckIn(checkInPrimaryKey);
}
public void findCheckInRecipient(int checkInPrimaryKey) {
checkInRecipientsTableRepository.findCheckInRecipient(checkInPrimaryKey);
}
LiveData<List<ContactGroupsTable>> getAllContactGroups() {
return allContactGroups;
}
public void insertContactGroupsTable(ContactGroupsTable contactGroupsTable) {
contactGroupsTableRepository.insertContactGroups(contactGroupsTable);
}
public void deleteContactGroups(int contactGroupsTablePrimaryKey) {
contactGroupsTableRepository.deleteContactGroups(contactGroupsTablePrimaryKey);
}
public void findContactGroups(int contactGroupsTablePrimaryKey) {
contactGroupsTableRepository.findContactGroups(contactGroupsTablePrimaryKey);
}
LiveData<List<ContactTable>> getAllContact() {
return allContacts;
}
public void insertContactTable(ContactTable contactTable) {
contactTableRepository.insertContact(contactTable);
}
public void deleteContact(int contactTablePrimaryKey) {
contactTableRepository.deleteContact(contactTablePrimaryKey);
}
public void findContact(int contactTablePrimaryKey) {
contactTableRepository.findContact(contactTablePrimaryKey);
}
}
Related
I downloaded a project from GitHub to modify but found some errors.
I have to update my firebase details.But after update found error: cannot find symbol import com.google.firebase.iid.FirebaseInstanceId; symbol.
My registerActivity.java:
package com.vserv.user.activity;
import com.google.firebase.iid.FirebaseInstanceId;
#Override
protected void onCreate(Bundle savedInstanceState) {
token = FirebaseInstanceId.getInstance().getToken();
}
private void upload(final String check) {
FirebaseInstanceId token = FirebaseInstanceId.getInstance();
request.setToken(token.getToken());
}
my baseapp.java
package com.vserv.user.constants;
import android.app.Application;
import android.content.Context;
import androidx.multidex.MultiDex;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
import com.vserv.user.models.FirebaseToken;
import com.vserv.user.models.User;
import io.realm.Realm;
import io.realm.RealmConfiguration;
/**
* Created by Ourdevelops Team on 10/13/2019.
*/
public class BaseApp extends Application {
private static final int SCHEMA_VERSION = 0;
private User loginUser;
private Realm realmInstance;
public static BaseApp getInstance(Context context) {
return (BaseApp) context.getApplicationContext();
}
#Override
public void onCreate() {
super.onCreate();
Realm.init(this);
RealmConfiguration config = new RealmConfiguration.Builder()
.schemaVersion(SCHEMA_VERSION)
.deleteRealmIfMigrationNeeded()
.build();
FirebaseToken token = new FirebaseToken(FirebaseInstanceId.getInstance().getToken());
FirebaseMessaging.getInstance().subscribeToTopic("ouride");
FirebaseMessaging.getInstance().subscribeToTopic("customer");
Realm.setDefaultConfiguration(config);
// realmInstance = Realm.getInstance(config);
realmInstance = Realm.getDefaultInstance();
realmInstance.beginTransaction();
realmInstance.delete(FirebaseToken.class);
realmInstance.copyToRealm(token);
realmInstance.commitTransaction();
start();
}
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
public User getLoginUser() {
return loginUser;
}
public void setLoginUser(User loginUser) {
this.loginUser = loginUser;
}
public final Realm getRealmInstance() {
return realmInstance;
}
private void start() {
Realm realm = getRealmInstance();
User user = realm.where(User.class).findFirst();
if (user != null) {
setLoginUser(user);
}
}
}
my firebasetoken.java
package com.vserv.user.models;
import io.realm.RealmObject;
/**
* Created by Ourdevelops Team on 10/13/2019.
*/
public class FirebaseToken extends RealmObject {
private String tokenId;
public FirebaseToken(String tokenId) {
this.tokenId = tokenId;
}
public FirebaseToken() {
}
public String getTokenId() {
return tokenId;
}
public void setTokenId(String tokenId) {
this.tokenId = tokenId;
}
}
Tried with watchig you tube videos but not solved.
I am new to androidstudio.
Please help.
how are you, I hope you are well
- I am using Room library to store products in RecyclerView.
- When using SearchView to search for a product by its name, the product name appears only when typing the first letter (that is, SearchView only interacts with the first letter of the product name).
Also, when you delete the letter, the complete list of products does not appear again.
Please help me find the error in the code
Warm regards, artist
dependencies
implementation "android.arch.persistence.room:runtime:1.1.1"
annotationProcessor "android.arch.persistence.room:compiler:1.1.1"
implementation "android.arch.lifecycle:extensions:1.1.1"
//noinspection LifecycleAnnotationProcessorWithJava8
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
ProductEntry
#Entity(tableName = "product")
public class ProductEntry {
#PrimaryKey(autoGenerate = true)
private int id;
#ColumnInfo(name = "productName")
private final String productName;
private final String productBarcode, productQuantity
, productPurchasingPrice, productSellingPrice, productDescription, productCategory;
#Ignore
public ProductEntry(String productName, String productBarcode, String productQuantity
, String productPurchasingPrice, String productSellingPrice, String productDescription, String productCategory) {
this.productName = productName;
this.productBarcode = productBarcode;
this.productQuantity = productQuantity;
this.productPurchasingPrice = productPurchasingPrice;
this.productSellingPrice = productSellingPrice;
this.productDescription = productDescription;
this.productCategory = productCategory;
}
public ProductEntry(int id, String productName, String productBarcode, String productQuantity
, String productPurchasingPrice, String productSellingPrice, String productDescription, String productCategory) {
this.id = id;
this.productName = productName;
this.productBarcode = productBarcode;
this.productQuantity = productQuantity;
this.productPurchasingPrice = productPurchasingPrice;
this.productSellingPrice = productSellingPrice;
this.productDescription = productDescription;
this.productCategory = productCategory;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProductName() {
return productName;
}
public String getProductBarcode() {
return productBarcode;
}
public String getProductQuantity() {
return productQuantity;
}
public String getProductPurchasingPrice() {
return productPurchasingPrice;
}
public String getProductSellingPrice() {
return productSellingPrice;
}
public String getProductDescription() {
return productDescription;
}
public String getProductCategory() {
return productCategory;
}
}
ProductDao
#Dao
public interface ProductDao {
#Query("SELECT * FROM product ORDER BY id")
LiveData<List<ProductEntry>> loadAllTasks();
#Query("SELECT * FROM product WHERE id = :id")
LiveData<ProductEntry> loadTaskById(int id);
#Query("SELECT * FROM product WHERE productName LIKE :findProductName")
LiveData<List<ProductEntry>> findProduct(String findProductName);
#Insert
void insertTask(ProductEntry productEntry);
#Update(onConflict = OnConflictStrategy.REPLACE)
void updateTask(ProductEntry productEntry);
#Delete
void deleteTask(ProductEntry productEntry);
}
FindProductViewModel
public class FindProductViewModel extends ViewModel {
private final LiveData<List<ProductEntry>> findProduct;
public FindProductViewModel(AppDatabase database, String searchQuery) {
findProduct = database.productDao().findProduct(searchQuery);
}
public LiveData<List<ProductEntry>> getFindProduct() {
return findProduct;
}
}
FindProductViewModelFactory
public class FindProductViewModelFactory extends ViewModelProvider.NewInstanceFactory {
private final AppDatabase mDb;
private final String mProductQuery;
public FindProductViewModelFactory(AppDatabase database, String productQuery) {
mDb = database;
mProductQuery = productQuery;
}
#NonNull
#Override
public <T extends ViewModel> T create(#NonNull Class<T> modelClass) {
//noinspection unchecked
return (T) new FindProductViewModel(mDb, mProductQuery);
}
}
ProductsActivity
public class ProductsActivity extends AppCompatActivity implements ProductAdapter.ItemClickListener {
private FloatingActionButton fabAddProduct;
private RecyclerView recyclerView;
private ProductAdapter productAdapter;
private AppDatabase mDb;
private View emptyView;
private SearchView productSearchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_products);
initView();
setupViewModel();
setupRecycleView();
fabAddProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent addProductIntent = new Intent(ProductsActivity.this, AddProductActivity.class);
startActivity(addProductIntent);
}
});
productSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
getItemFromDb(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
getItemFromDb(newText);
// productAdapter.getFilter().filter(newText);
return false;
}
});
}
private void getItemFromDb(String query) {
String searchText = "%" + query + "%";
FindProductViewModelFactory factory = new FindProductViewModelFactory(mDb, searchText);
final FindProductViewModel viewModel = ViewModelProviders
.of(ProductsActivity.this, (ViewModelProvider.Factory) factory)
.get(FindProductViewModel.class);
viewModel.getFindProduct().observe(this, new Observer<List<ProductEntry>>() {
#Override
public void onChanged(#Nullable List<ProductEntry> productEntries) {
viewModel.getFindProduct().removeObserver(this);
productAdapter.setProductEntries(productEntries);
}
});
}
private void initView() {
emptyView = findViewById(R.id.empty_view);
fabAddProduct = findViewById(R.id.fabAddProducts);
recyclerView = findViewById(R.id.recyclerViewProducts);
productSearchView = findViewById(R.id.productSearchView);
}
private void setupRecycleView() {
mDb = AppDatabase.getInstance(getApplicationContext());
productAdapter = new ProductAdapter(this, this, mDb);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(productAdapter);
}
private void setupViewModel() {
MainViewModel viewModel = ViewModelProviders.of(this).get(MainViewModel.class);
viewModel.getProducts().observe(this, new Observer<List<ProductEntry>>() {
#Override
public void onChanged(#Nullable List<ProductEntry> productEntries) {
productAdapter.setProductEntries(productEntries);
if (productAdapter.getItemCount() == 0) {
recyclerView.setVisibility(View.GONE);
emptyView.setVisibility(View.VISIBLE);
productSearchView.setVisibility(View.GONE);
} else {
recyclerView.setVisibility(View.VISIBLE);
emptyView.setVisibility(View.GONE);
productSearchView.setVisibility(View.VISIBLE);
}
}
});
}
#Override
public void onItemClickListener(int itemId) {
Intent intent = new Intent(ProductsActivity.this, AddProductActivity.class);
intent.putExtra(AddProductActivity.EXTRA_PRODUCT_ID, itemId);
startActivity(intent);
}
}
To give you the simple answer, the reason you are getting only the first update is the line with viewModel.getFindProduct().removeObserver(this);
Thank you very much
I solved the problem by adding the following code
package com.artist.bookkeeper.activities;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.artist.bookkeeper.database.entry.ProductEntry;
import com.artist.bookkeeper.viewmodel.MainViewModel;
import com.artist.bookkeeper.adapters.ProductsAdapter;
import com.artist.bookkeeper.R;
import com.artist.bookkeeper.database.AppDatabase;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
public class ProductStoreActivity extends AppCompatActivity implements ProductsAdapter.ItemClickListener {
private FloatingActionButton addProductFab;
private RecyclerView productsRv;
private ProductsAdapter productsAdapter;
private AppDatabase appDatabase;
private View productsEmptyView;
private SearchView productsSv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_store);
initProductView();
setupProductViewModel();
setupProductRecycleView();
addProductFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(ProductStoreActivity.this, AddProductActivity.class));
}
});
productsSv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
setupProductViewModel();
productsFilter(newText);
return true;
}
});
}
private void productsFilter(String text) {
ArrayList<ProductEntry> productsList = new ArrayList<>();
for (ProductEntry product : productsAdapter.getProductEntries()) {
if (product.getProductName().toLowerCase().contains(text.toLowerCase())) {
productsList.add(product);
}
}
if (productsList.isEmpty()) {
Toast.makeText(this, getString(R.string.no_product), Toast.LENGTH_SHORT).show();
} else {
productsAdapter.setProductEntries(productsList);
}
}
private void initProductView() {
productsEmptyView = findViewById(R.id.productEmptyView);
addProductFab = findViewById(R.id.addProductFab);
productsRv = findViewById(R.id.productRv);
productsSv = findViewById(R.id.productSv);
}
private void setupProductRecycleView() {
appDatabase = AppDatabase.getInstance(getApplicationContext());
productsAdapter = new ProductsAdapter(this, this, appDatabase);
productsRv.setHasFixedSize(true);
productsRv.setLayoutManager(new LinearLayoutManager(this));
productsRv.setAdapter(productsAdapter);
}
private void setupProductViewModel() {
MainViewModel mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
mainViewModel.getListProductsLiveData().observe(this, new Observer<List<ProductEntry>>() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onChanged(#Nullable List<ProductEntry> productEntries) {
productsAdapter.setProductEntries(productEntries);
productsAdapter.notifyDataSetChanged();
if (productsAdapter.getItemCount() == 0) {
productsRv.setVisibility(View.GONE);
productsEmptyView.setVisibility(View.VISIBLE);
productsSv.setVisibility(View.GONE);
} else {
productsRv.setVisibility(View.VISIBLE);
productsEmptyView.setVisibility(View.GONE);
productsSv.setVisibility(View.VISIBLE);
}
}
});
}
#Override
public void onItemClickListener(int productId, String productName) {
Intent intent = new Intent(ProductStoreActivity.this, ProductDetailsActivity.class);
intent.putExtra("productId", productId);
intent.putExtra("productName", productName);
startActivity(intent);
}
}
ModelOrderUser.java
package my.anupamroy.smartcanteenapp.models;
public class ModelOrderUser {
String orderId,orderTime,orderStatus,orderCost,orderBy,orderTo;
public ModelOrderUser(){
}
public ModelOrderUser(String orderId, String orderTime, String orderStatus, String orderCost, String orderBy, String orderTo) {
this.orderId = orderId;
this.orderTime = orderTime;
this.orderStatus = orderStatus;
this.orderCost = orderCost;
this.orderBy = orderBy;
this.orderTo = orderTo;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getOrderTime() {
return orderTime;
}
public void setOrderTime(String orderTime) {
this.orderTime = orderTime;
}
public String getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
public String getOrderCost() {
return orderCost;
}
public void setOrderCost(String orderCost) {
this.orderCost = orderCost;
}
public String getOrderBy() {
return orderBy;
}
public void setOrderBy(String orderBy) {
this.orderBy = orderBy;
}
public String getOrderTo() {
return orderTo;
}
public void setOrderTo(String orderTo) {
this.orderTo = orderTo;
}
}
AdapterOrderUser.java
package my.anupamroy.smartcanteenapp.adapters;
import android.content.Context;
import android.text.Layout;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Calendar;
import my.anupamroy.smartcanteenapp.R;
import my.anupamroy.smartcanteenapp.models.ModelOrderUser;
public class AdapterOrderUser extends RecyclerView.Adapter<AdapterOrderUser.HolderOrderUser>{
private Context context;
private ArrayList<ModelOrderUser> orderUserList;
public AdapterOrderUser(Context context, ArrayList<ModelOrderUser> orderUserList) {
this.context = context;
this.orderUserList = orderUserList;
}
#NonNull
#Override
public HolderOrderUser onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//inflate layout
View view = LayoutInflater.from(context).inflate(R.layout.row_order_user,parent,false);
return new HolderOrderUser(view);
}
#Override
public void onBindViewHolder(#NonNull HolderOrderUser holder, int position) {
//get data
ModelOrderUser modelOrderUser=orderUserList.get(position);
String orderId = modelOrderUser.getOrderId();
String orderBy = modelOrderUser.getOrderBy();
String orderCost = modelOrderUser.getOrderCost();
String orderStatus = modelOrderUser.getOrderStatus();
String orderTime = modelOrderUser.getOrderTime();
String orderTo = modelOrderUser.getOrderTo();
//get shop info
loadShopInfo(modelOrderUser,holder);
//set data
holder.amountTv.setText("Amount: ₹" +orderCost);
holder.statusTv.setText(orderStatus);
holder.orderIdTv.setText("OrderID:"+orderId);
// change order status text color
if(orderStatus.equals("In Progress")){
holder.statusTv.setTextColor(context.getResources().getColor(R.color.colorPrimary));
}
else if(orderStatus.equals("Completed")){
holder.statusTv.setTextColor(context.getResources().getColor(R.color.colorGreen));
}
else if(orderStatus.equals("Cancelled")){
holder.statusTv.setTextColor(context.getResources().getColor(R.color.colorRed));
}
//convert timestamp to proper format
Calendar calendar =Calendar.getInstance();
calendar.setTimeInMillis(Long.parseLong(orderTime));
String formatedDate= DateFormat.format("dd/MM/yyy",calendar).toString();
holder.dateTv.setText(formatedDate);
}
private void loadShopInfo(ModelOrderUser modelOrderUser, final HolderOrderUser holder) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
ref.child(modelOrderUser.getOrderTo())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String shopName =""+dataSnapshot.child("shopName").getValue();
holder.shopNameTv.setText(shopName);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public int getItemCount() {
return orderUserList.size();
}
//view holder class
class HolderOrderUser extends RecyclerView.ViewHolder{
private TextView orderIdTv,dateTv,shopNameTv,amountTv,statusTv;
public HolderOrderUser(#NonNull View itemView) {
super(itemView);
//init views of layout
orderIdTv=itemView.findViewById(R.id.orderIdTv);
dateTv=itemView.findViewById(R.id.dateTv);
shopNameTv=itemView.findViewById(R.id.shopNameTv);
amountTv=itemView.findViewById(R.id.amountTv);
statusTv=itemView.findViewById(R.id.statusTv);
}
}
}
I am facing the following while executing don't know what is happening
java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
at com.google.firebase.database.DatabaseReference.child(DatabaseReference.java:96)
at my.anupamroy.smartcanteenapp.adapters.AdapterOrderUser.loadShopInfo(AdapterOrderUser.java:84)
at my.anupamroy.smartcanteenapp.adapters.AdapterOrderUser.onBindViewHolder(AdapterOrderUser.java:56)
at my.anupamroy.smartcanteenapp.adapters.AdapterOrderUser.onBindViewHolder(AdapterOrderUser.java:26)
Please help me out with this error
don't know why the code is throwing errors for me
please help me out
I am getting errors in lines number 84,56,26
I try to get data from my Api, I can get data and convert it into an object class I created and show it but I can't store all objects instances in an list. Someone knows ?
I tried to add every element I got in a List then try to get elements from it after but doesn't work, the list stays empty.
This is what my API returns :
{"_id":"60683c5bcdfcb74689bc8382","questionId":3,"question":"Question 3","choices":"1-/-2-/-3-/-4","category":"Other","difficulty":"Easy"}
This is my "ApiTest activity" :
package com.jojo.jojozquizz;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.jojo.jojozquizz.model.Question;
import com.jojo.jojozquizz.model.QuestionBank;
import com.jojo.jojozquizz.tools.APIListener;
import org.json.JSONException;
import org.json.JSONObject;
public class ApiTests extends AppCompatActivity implements APIListener {
private TextView text;
public static final String TAG = "MyTag";
private QuestionBank mQuestionBank;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_api_tests);
mQuestionBank = new QuestionBank();
text = findViewById(R.id.api_text);
String url = "https://nextfor.studio/questions/test";
getQuestionFromApi(url);
}
private void getQuestionFromApi(String url) {
APIListener listener = this;
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d(TAG, "onResponse: " + response.toString());
Question question = new Question();
question.setId(response.getInt("questionId"));
question.setQuestion(response.getString("question"));
question.setChoices(response.getString("choices"));
question.setCategory(response.getString("category"));
question.setDifficulty(response.getString("difficulty"));
listener.questionReceived(question);
} catch (JSONException e) {
Log.i(TAG, e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse: " + error.getMessage());
}
});
requestQueue.add(jsonObjectRequest);
}
#Override
public void questionReceived(Question q) {
mQuestionBank.addQuestion(q);
}
}
Question class :
package com.jojo.jojozquizz.model;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;
import java.io.Serializable;
import java.util.List;
#Entity(tableName = "questions")
public class Question implements Serializable {
#PrimaryKey()
#ColumnInfo(name = "id")
private long id;
#ColumnInfo(name = "question")
private String mQuestion;
#Ignore
private List<String> mChoiceList;
#ColumnInfo(name = "choices")
private String mChoices;
#ColumnInfo(name = "answer_index")
private int mAnswerIndex;
#ColumnInfo(name = "categorie")
private String mCategory;
#Ignore
private String mTrueAnswer;
#ColumnInfo(name = "difficulty")
private String mDifficulty;
public Question() {
}
public Question(int id, String mQuestion, List<String> mChoiceList, String mCategorie, String mDifficulty) {
this.id = id;
this.mQuestion = mQuestion;
this.mChoices = mChoiceList.get(0) + "-/-" + mChoiceList.get(1) + "-/-" + mChoiceList.get(2) + "-/-" + mChoiceList.get(3);
this.mAnswerIndex = 0;
this.mCategory = mCategorie;
this.mDifficulty = mDifficulty;
}
public Question(String mQuestion, List<String> mChoiceList, String mCategorie, String mDifficulty) {
this.mQuestion = mQuestion;
this.mChoices = mChoiceList.get(0) + "-/-" + mChoiceList.get(1) + "-/-" + mChoiceList.get(2) + "-/-" + mChoiceList.get(3);
this.mAnswerIndex = 0;
this.mCategory = mCategorie;
this.mDifficulty = mDifficulty;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getQuestion() {
return mQuestion;
}
public void setQuestion(String question) {
mQuestion = question;
}
public List<String> getChoiceList() {
return mChoiceList;
}
public void setChoiceList(List<String> choiceList) {
mChoiceList = choiceList;
}
public String getChoices() {
return mChoices;
}
public void setChoices(String choices) {
mChoices = choices;
}
public void setAnswerIndex(int mAnswerIndex) {
this.mAnswerIndex = mAnswerIndex;
}
public int getAnswerIndex() {
return mAnswerIndex;
}
public String getCategory() {
return mCategory;
}
public void setCategory(String categorie) {
mCategory = categorie;
}
public String getTrueAnswer() {
return mTrueAnswer;
}
public void setTrueAnswer(String trueAnswer) {
mTrueAnswer = trueAnswer;
}
public String getDifficulty() {
return mDifficulty;
}
public void setDifficulty(String difficulty) {
mDifficulty = difficulty;
}
}
QuestionBank (this is like a list of Questions) :
package com.jojo.jojozquizz.model;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class QuestionBank {
private List<Question> mQuestionList;
public int mNextQuestionIndex;
public QuestionBank() {
mQuestionList = new LinkedList<>();
mNextQuestionIndex = 0;
}
public QuestionBank(List<Question> questionList, boolean shuffle) {
mQuestionList = questionList;
if (shuffle)
Collections.shuffle(mQuestionList);
mNextQuestionIndex = 0;
}
public Question getQuestion() {
if (mNextQuestionIndex == mQuestionList.size())
mNextQuestionIndex = 0;
return mQuestionList.get(mNextQuestionIndex++);
}
public Question getQuestion(int i) {
return mQuestionList.get(i);
}
public void reShuffle() {
Collections.shuffle(mQuestionList);
}
public void addQuestion(Question question) {
mQuestionList.add(question);
}
public int returnListSize() {
return mQuestionList.size();
}
}
And APIListener :
package com.jojo.jojozquizz.tools;
import com.jojo.jojozquizz.model.Question;
public interface APIListener {
void questionReceived(Question q);
}
API calling is an asynchronous process. So getQuestionFromApi(url); might took some time, so if you try text.setText(mQuestionBank.getQuestion(0).getQuestion()); after getQuestionFromApi(url); line, it won't work. You could use LiveData to handle this case. Like:
class QuestionBank {
MutableLiveData<List<Question>> mQuestionList;
public int mNextQuestionIndex;
public QuestionBank() {
mQuestionList = new MutableLiveData<>(new LinkedList<>());
mNextQuestionIndex = 0;
}
public QuestionBank(List<Question> questionList, boolean shuffle) {
mQuestionList.setValue(questionList);
if (shuffle)
Collections.shuffle(mQuestionList.getValue());
mNextQuestionIndex = 0;
}
public Question getQuestion() {
if (mNextQuestionIndex == mQuestionList.getValue().size())
mNextQuestionIndex = 0;
return mQuestionList.getValue().get(mNextQuestionIndex++);
}
public Question getQuestion(int i) {
return mQuestionList.getValue().get(i);
}
public void reShuffle() {
Collections.shuffle(mQuestionList.getValue());
}
public void addQuestion(Question question) {
List<Question> tempQ = mQuestionList.getValue();
tempQ.add(question);
mQuestionList.setValue(tempQ);
}
public int returnListSize() {
return mQuestionList.getValue().size();
}
}
And inside onCreate() observe if any data has been added or not and then setText() to TextView. Like:
QuestionBank questionBank = new QuestionBank();
questionBank.mQuestionList.observe(getViewLifecycleOwner(), new Observer<List<Question>>() {
#Override
public void onChanged(List<Question> questions) {
if (!questions.isEmpty()){
textView.setText(questions.get(0).getQuestion());
Log.d("TAG==>>","New Question added Total size = "+questions.size());
}
}
});
Whenever I want to start my "NotenActivity", it Shows me this error:
Caused by: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
at androidx.room.RoomDatabase.assertNotMainThread(RoomDatabase.java:209)
at androidx.room.RoomDatabase.query(RoomDatabase.java:237)
at com.example.mykolproject.persistance.dao.NoteDao_Impl.getnAll(NoteDao_Impl.java:121)
at com.example.mykolproject.NoteRepository.<init>(NoteRepository.java:23)
at com.example.mykolproject.NoteViewModel.<init>(NoteViewModel.java:20)
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:200)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:135)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:103)
at com.example.mykolproject.NotenActivity.onCreate(NotenActivity.java:130)
at android.app.Activity.performCreate(Activity.java:7458)
at android.app.Activity.performCreate(Activity.java:7448)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1286)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3409)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3614)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199)
at android.os.Handler.dispatchMessage(Handler.java:112)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
Here are my affected Activitys:
package com.example.mykolproject.persistance.dao;
import android.database.Cursor;
import androidx.room.EntityDeletionOrUpdateAdapter;
import androidx.room.EntityInsertionAdapter;
import androidx.room.RoomDatabase;
import androidx.room.RoomSQLiteQuery;
import androidx.sqlite.db.SupportSQLiteStatement;
import com.example.mykolproject.persistance.entities.Note;
import java.lang.Override;
import java.lang.String;
import java.lang.SuppressWarnings;
import java.util.ArrayList;
import java.util.List;
#SuppressWarnings("unchecked")
public final class NoteDao_Impl implements NoteDao {
private final RoomDatabase __db;
private final EntityInsertionAdapter __insertionAdapterOfNote;
private final EntityDeletionOrUpdateAdapter __deletionAdapterOfNote;
private final EntityDeletionOrUpdateAdapter __updateAdapterOfNote;
public NoteDao_Impl(RoomDatabase __db) {
this.__db = __db;
this.__insertionAdapterOfNote = new EntityInsertionAdapter<Note>(__db) {
#Override
public String createQuery() {
return "INSERT OR ABORT INTO `note_table`(`id`,`titlefach`,`noten`) VALUES (nullif(?, 0),?,?)";
}
#Override
public void bind(SupportSQLiteStatement stmt, Note value) {
stmt.bindLong(1, value.getId());
if (value.titlefach == null) {
stmt.bindNull(2);
} else {
stmt.bindString(2, value.titlefach);
}
if (value.getNoten() == null) {
stmt.bindNull(3);
} else {
stmt.bindString(3, value.getNoten());
}
}
};
this.__deletionAdapterOfNote = new EntityDeletionOrUpdateAdapter<Note>(__db) {
#Override
public String createQuery() {
return "DELETE FROM `note_table` WHERE `id` = ?";
}
#Override
public void bind(SupportSQLiteStatement stmt, Note value) {
stmt.bindLong(1, value.getId());
}
};
this.__updateAdapterOfNote = new EntityDeletionOrUpdateAdapter<Note>(__db) {
#Override
public String createQuery() {
return "UPDATE OR ABORT `note_table` SET `id` = ?,`titlefach` = ?,`noten` = ? WHERE `id` = ?";
}
#Override
public void bind(SupportSQLiteStatement stmt, Note value) {
stmt.bindLong(1, value.getId());
if (value.titlefach == null) {
stmt.bindNull(2);
} else {
stmt.bindString(2, value.titlefach);
}
if (value.getNoten() == null) {
stmt.bindNull(3);
} else {
stmt.bindString(3, value.getNoten());
}
stmt.bindLong(4, value.getId());
}
};
}
#Override
public void insert(Note note) {
__db.beginTransaction();
try {
__insertionAdapterOfNote.insert(note);
__db.setTransactionSuccessful();
} finally {
__db.endTransaction();
}
}
#Override
public void delete(Note note) {
__db.beginTransaction();
try {
__deletionAdapterOfNote.handle(note);
__db.setTransactionSuccessful();
} finally {
__db.endTransaction();
}
}
#Override
public void update(Note note) {
__db.beginTransaction();
try {
__updateAdapterOfNote.handle(note);
__db.setTransactionSuccessful();
} finally {
__db.endTransaction();
}
}
#Override
public List<Note> getnAll() {
final String _sql = "SELECT * FROM note_table";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 0);
final Cursor _cursor = __db.query(_statement);
try {
final int _cursorIndexOfId = _cursor.getColumnIndexOrThrow("id");
final int _cursorIndexOfTitlefach = _cursor.getColumnIndexOrThrow("titlefach");
final int _cursorIndexOfNoten = _cursor.getColumnIndexOrThrow("noten");
final List<Note> _result = new ArrayList<Note>(_cursor.getCount());
while(_cursor.moveToNext()) {
final Note _item;
final String _tmpTitlefach;
_tmpTitlefach = _cursor.getString(_cursorIndexOfTitlefach);
final String _tmpNoten;
_tmpNoten = _cursor.getString(_cursorIndexOfNoten);
_item = new Note(_tmpTitlefach,_tmpNoten);
final int _tmpId;
_tmpId = _cursor.getInt(_cursorIndexOfId);
_item.setId(_tmpId);
_result.add(_item);
}
return _result;
} finally {
_cursor.close();
_statement.release();
}
}
}
package com.example.mykolproject;
import android.app.Application;
import android.os.AsyncTask;
import androidx.lifecycle.LiveData;
import com.example.mykolproject.persistance.dao.NoteDao;
import com.example.mykolproject.persistance.entities.AppDatabase;
import com.example.mykolproject.persistance.entities.Note;
import java.util.List;
public class NoteRepository {
private NoteDao notenDao;
private LiveData<List<Note>> allNoten;
public NoteRepository(Application application) {
AppDatabase database = AppDatabase.getInstance(application);
notenDao = database.NoteDao();
allNoten = (LiveData<List<Note>>) notenDao.getnAll();
}
public void insert(LiveData<List<Note>> note) {
new InsertNoteAsyncTask(notenDao).execute((Runnable) note);
}
public void update(LiveData<List<Note>> note) {
new UpdateNoteAsyncTask(notenDao).execute((Runnable) note);
}
public void delete(LiveData<List<Note>> note) {
new DeleteNoteAsyncTask(notenDao).execute((Runnable) note);
}
public LiveData<List<Note>> getAllNoten() {
return getAllNoten();
}
private static class InsertNoteAsyncTask extends AsyncTask<Note, Void, Void> {
private NoteDao noteDao;
private InsertNoteAsyncTask(NoteDao noteDao) {
this.noteDao = noteDao;
}
#Override
protected Void doInBackground(Note... noten) {
noteDao.insert(noten[0]);
return null;
}
}
private static class UpdateNoteAsyncTask extends AsyncTask<Note, Void, Void> {
private NoteDao noteDao;
private UpdateNoteAsyncTask(NoteDao noteDao) {
this.noteDao = noteDao;
}
#Override
protected Void doInBackground(Note... noten) {
noteDao.update(noten[0]);
return null;
}
}
private static class DeleteNoteAsyncTask extends AsyncTask<Note, Void, Void> {
private NoteDao noteDao;
private DeleteNoteAsyncTask(NoteDao noteDao) {
this.noteDao = noteDao;
}
#Override
protected Void doInBackground(Note... noten) {
noteDao.delete(noten[0]);
return null;
}
}
}
package com.example.mykolproject;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import com.example.mykolproject.persistance.entities.Note;
import java.util.List;
public class NoteViewModel extends AndroidViewModel {
private NoteRepository repository;
private LiveData<List<Note>> allNoten;
public NoteViewModel(#NonNull Application application) {
super(application);
repository = new NoteRepository(application);
allNoten = repository.getAllNoten();
}
public void insert(Note note) {
repository.insert(allNoten);
}
public void update(Note note) {
repository.update(allNoten);
}
public void delete(Note note) {
repository.delete(allNoten);
}
public LiveData<List<Note>> getAllNotes() {
return allNoten;
}
}
package com.example.mykolproject;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.mykolproject.persistance.entities.Note;
import java.util.List;
public class NotenActivity extends AppCompatActivity {
public String TAG = "NotenActivity";
public static final String NOTEN_MESSAGE = "com.example.MyOLProject.NOTEN";
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
public static final int ADD_NOTE_REQUEST = 1;
public static final int EDIT_NOTE_REQUEST = 2;
private NoteViewModel noteViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_noten);
// final EditText editFach = findViewById(R.id.edit_fach);
recyclerView = (RecyclerView) findViewById(R.id.notenList);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
Button btnAddNoten = findViewById(R.id.btn_addNote);
btnAddNoten.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "onClick: AddNoten");
startAddNoten();
}
});
ImageButton btnFach = findViewById(R.id.ibFach);
btnFach.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Log.i(TAG,"onClick: Fach");
startFach();
}
});
ImageButton btnHome = findViewById(R.id.ibHome);
btnHome.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Log.i(TAG,"onClick: Home");
startHome();
}
});
ImageButton btnHausaufgaben = findViewById(R.id.ibHausaufgaben);
btnHausaufgaben.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Log.i(TAG,"onClick: Hausaufgaben");
startHausaufgaben();
}
});
ImageButton btnKalender = findViewById(R.id.ibInfo);
btnKalender.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Log.i(TAG,"onClick: Kalender");
startKalender();
}
});
Button buttonAddNote = findViewById(R.id.btn_addNote);
buttonAddNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(NotenActivity.this, AddEditNoteActivity.class);
startActivityForResult(intent, ADD_NOTE_REQUEST);
}
});
RecyclerView recyclerView = findViewById(R.id.notenList);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
final NotenListAdapter adapter = new NotenListAdapter();
recyclerView.setAdapter(adapter);
noteViewModel = ViewModelProviders.of(this).get(NoteViewModel.class);
noteViewModel.getAllNotes().observe(this, new Observer<List<Note>>() {
#Override
public void onChanged(#Nullable List<Note> noten) {
adapter.setNotes(noten);
}
});
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
noteViewModel.delete(adapter.getNoteAt(viewHolder.getAdapterPosition()));
Toast.makeText(NotenActivity.this, "Note deleted", Toast.LENGTH_SHORT).show();
}
}).attachToRecyclerView(recyclerView);
adapter.setOnItemClickListener(new NotenListAdapter.OnItemClickListener() {
#Override
public void onItemClick(Note note) {
Intent intent = new Intent(NotenActivity.this, AddEditNoteActivity.class);
intent.putExtra(AddEditNoteActivity.EXTRA_ID, note.getId());
intent.putExtra(AddEditNoteActivity.EXTRA_TITLE, note.getTitleFach());
intent.putExtra(AddEditNoteActivity.EXTRA_DESCRIPTION, note.getNoten());
startActivityForResult(intent, EDIT_NOTE_REQUEST);
}
});
}
private void startAddNoten(){
Intent addNotenIntent = new Intent(this,AddNotenActivity.class);
startActivity(addNotenIntent);
}
private void startFach(){
Intent fachIntent = new Intent(this,FachActivity.class);
startActivity(fachIntent);
}
private void startHome(){
Intent homeIntent = new Intent(this,MainActivity.class);
startActivity(homeIntent);
}
private void startHausaufgaben(){
Intent hausaufgabenIntent = new Intent(this,HausaufgabenActivity.class);
startActivity(hausaufgabenIntent);
}
private void startKalender(){
Intent kalenderIntent = new Intent(this,InfoActivity.class);
startActivity(kalenderIntent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ADD_NOTE_REQUEST && resultCode == RESULT_OK) {
String title = data.getStringExtra(AddEditNoteActivity.EXTRA_TITLE);
String description = data.getStringExtra(AddEditNoteActivity.EXTRA_DESCRIPTION);
Note note = new Note(title, description);
noteViewModel.insert(note);
Toast.makeText(this, "Note saved", Toast.LENGTH_SHORT).show();
} else if (requestCode == EDIT_NOTE_REQUEST && resultCode == RESULT_OK) {
int id = data.getIntExtra(AddEditNoteActivity.EXTRA_ID, -1);
if (id == -1) {
Toast.makeText(this, "Note can't be updated", Toast.LENGTH_SHORT).show();
return;
}
String title = data.getStringExtra(AddEditNoteActivity.EXTRA_TITLE);
String description = data.getStringExtra(AddEditNoteActivity.EXTRA_DESCRIPTION);
Note note = new Note(title, description);
note.setId(id);
noteViewModel.update(note);
Toast.makeText(this, "Note updated", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Note not saved", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu, menu);
return true;
}
/* #Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.delete_all_notes:
noteViewModel.deleteAllNotes();
Toast.makeText(this, "All notes deleted", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}*/
}
If you Need any other activities just let me know. My "NotenActivity" is like my MainActivity.
Thank you very much !
Try using some RxJava, that can probably help you out.
But since you're using Room, LiveData, and ViewModel you can probably try using this AppExecutor class. This usually helps me out when I'm doing Database and Network operations.
Also be careful when running on the UI/Main Thread, for Database operations with lots of data its always best practice to do it on a separate thread.
import android.os.Looper;
import android.support.annotation.NonNull;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class AppExecutors {
private static final Object LOCK = new Object();
private static AppExecutors sInstance;
private final Executor diskIO;
private final Executor mainThread;
private final Executor networkIO;
private AppExecutors(Executor diskIO, Executor networkIO, Executor mainThread) {
this.diskIO = diskIO;
this.networkIO = networkIO;
this.mainThread = mainThread;
}
public static AppExecutors getInstance() {
if (sInstance == null) {
synchronized (LOCK) {
sInstance = new AppExecutors(Executors.newSingleThreadExecutor(),
Executors.newFixedThreadPool(3),
new MainThreadExecutor());
}
}
return sInstance;
}
public Executor diskIO() {
return diskIO;
}
public Executor mainThread() {
return mainThread;
}
public Executor networkIO() {
return networkIO;
}
private static class MainThreadExecutor implements Executor {
private Handler mainThreadHandler = new Handler(Looper.getMainLooper());
#Override
public void execute(#NonNull Runnable command) {
mainThreadHandler.post(command);
}
}
}
//Then you can do something like this.
```AppExecutors.getInstance().getDiskIO.execute(()->database.NoteDao().getnAll());```
Maybe you could look on widely accepted solution of this problem, it could bring you to solution of your problem too...