I can not update an item list in the database room and add the item to the favorites list - database

I can not set an isfavorites value by clicking Add to Favorites .
Android Studio displays a null pointer exception for ringTonesDao .
I do not know how to fix this error.
On the other hand, because ringTonesDao is an interface, if I set its value to new RingTonesDao, I have to set all its functions.
this is RingTonesAdapter
//Imports and Package name
public class RingTonesAdapter extends
RecyclerView.Adapter<RingTonesAdapter.ringTonesViewHolder> {
private List<RingTones> ringTonesList;
RingTonesDao ringTonesDao; // <--This is null in logcat
public RingTonesAdapter(List<RingTones> ringTonesList) {
this.ringTonesList = ringTonesList;
}
#NonNull
#Override
public ringTonesViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.actv_main_list,
parent, false);
return new ringTonesViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ringTonesViewHolder holder, int position) {
//Set RingTone name to TextView
//Set RingTone Btn
//Set Alarm Btn
//Set Notification Btn
//Add To Favorites Btn
if (ringTonesList.get(position).isFavorite()) {
holder.btn_addToFavorites.setImageResource(R.drawable.ic_favorites);
} else {
holder.btn_addToFavorites.setImageResource(R.drawable.ic_addtofavorites);
}
holder.btn_addToFavorites.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Long id = ringTonesList.get(position).getId();
ringTonesDao.update(true,id);
}catch (NullPointerException e){
Toast.makeText(v.getContext(),"Null Pointer
Exception",Toast.LENGTH_LONG).show();
}
}
});
//Set Play Btn
//ringTonesViewHolder and count items
and this is RingTonesDao
//import and package
#Dao
public interface RingTonesDao {
#Insert
Long add(RingTones ringTones);
#Delete
int delete(RingTones ringTones);
#Query("SELECT * FROM tbl_ringtones")
List<RingTones> getRingTones();
#Query("SELECT * FROM tbl_ringtones WHERE favorites>0 ")
List<RingTones> favorites();
#Query("DELETE FROM tbl_ringtones")
void deleteAll();
#Query("UPDATE tbl_ringtones SET favorites=:favorites WHERE id=:id")
int update (Boolean favorites ,Long id);
}

You need to do something like this
DatabaseClient.getInstance(v.getContext()).getAppDatabase()
.RingTonesDao()
.update(true,id);
read more how to use Rom database : from this example
also there is a difference between Boolean and boolean in Java,
in your case try to use `boolean` instead `Boolean` in your update function.

Related

I'm trying to perform a search on my recycler adapter when onQueryTextChange gives error to make filter as static in adapter

This is my activity_course_details.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CourseDetails">
<SearchView
android:id="#+id/search"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:iconifiedByDefault="false">
<requestFocus />
</SearchView>
<!--Recycler view for displaying
our data from Firestore-->
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/idRVCourses"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp" />
<!--Progress bar for showing loading screen-->
<ProgressBar
android:id="#+id/idProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
CoursesDetails.java
public class CourseDetails extends AppCompatActivity implements
SearchView.OnQueryTextListener{
// creating variables for our recycler view,
// array list, adapter, firebase firestore
// and our progress bar.
private RecyclerView courseRV;
private ArrayList<Courses> coursesArrayList;
private CourseRVAdapter courseRVAdapter;
private FirebaseFirestore db;
ProgressBar loadingPB;
SearchView editsearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_details);
editsearch = (SearchView) findViewById(R.id.search);
editsearch.setOnQueryTextListener((SearchView.OnQueryTextListener) this);
// initializing our variables.
courseRV = findViewById(R.id.idRVCourses);
loadingPB = findViewById(R.id.idProgressBar);
// initializing our variable for firebase
// firestore and getting its instance.
db = FirebaseFirestore.getInstance();
// creating our new array list
coursesArrayList = new ArrayList<>();
courseRV.setHasFixedSize(true);
courseRV.setLayoutManager(new LinearLayoutManager(this));
// adding our array list to our recycler view adapter class.
courseRVAdapter = new CourseRVAdapter(coursesArrayList, this);
// setting adapter to our recycler view.
courseRV.setAdapter(courseRVAdapter);
// below line is use to get the data from Firebase Firestore.
// previously we were saving data on a reference of Courses
// now we will be getting the data from the same reference.
db.collection("Courses").get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
// after getting the data we are calling on success method
// and inside this method we are checking if the received
// query snapshot is empty or not.
if (!queryDocumentSnapshots.isEmpty()) {
// if the snapshot is not empty we are
// hiding our progress bar and adding
// our data in a list.
loadingPB.setVisibility(View.GONE);
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot d : list) {
// after getting this list we are passing
// that list to our object class.
Courses c = d.toObject(Courses.class);
// and we will pass this object class
// inside our arraylist which we have
// created for recycler view.
coursesArrayList.add(c);
}
// after adding the data to recycler view.
// we are calling recycler view notifuDataSetChanged
// method to notify that data has been changed in recycler view.
courseRVAdapter.notifyDataSetChanged();
} else {
// if the snapshot is empty we are displaying a toast message.
Toast.makeText(CourseDetails.this, "No data found in Database", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// if we do not get any data or any error we are displaying
// a toast message that we do not get any data
Toast.makeText(CourseDetails.this, "Fail to get the data.", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
String text = newText;
CourseRVAdapter.filter(text);
return false;
}
}
CoursesRVAdapter.java
public class CourseRVAdapter extends RecyclerView.Adapter<CourseRVAdapter.ViewHolder> {
// creating variables for our ArrayList and context
private ArrayList<Courses> coursesArrayList = null;
private Context context;
private ArrayList<Courses> arrayList;
// creating constructor for our adapter class
public CourseRVAdapter(ArrayList<Courses> coursesArrayList, Context context) {
this.coursesArrayList = coursesArrayList;
this.context = context;
this.arrayList = new ArrayList<Courses>();
this.arrayList.addAll(coursesArrayList);
}
#NonNull
#Override
public CourseRVAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// passing our layout file for displaying our card item
return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.course_item, parent, false));
}
#Override
public void onBindViewHolder(#NonNull CourseRVAdapter.ViewHolder holder, int position) {
// setting data to our text views from our modal class.
Courses courses = coursesArrayList.get(position);
holder.courseNameTV.setText(courses.getCourseName());
holder.courseDurationTV.setText(courses.getCourseDuration());
holder.courseDescTV.setText(courses.getCourseDescription());
}
#Override
public int getItemCount() {
// returning the size of our array list.
return coursesArrayList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
// creating variables for our text views.
private final TextView courseNameTV;
private final TextView courseDurationTV;
private final TextView courseDescTV;
public ViewHolder(#NonNull View itemView) {
super(itemView);
// initializing our text views.
courseNameTV = itemView.findViewById(R.id.idTVCourseName);
courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration);
courseDescTV = itemView.findViewById(R.id.idTVCourseDescription);
}
}
#Override
public long getItemId(int position) {
return position;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
coursesArrayList.clear();
if (charText.length() == 0) {
arrayList.addAll(coursesArrayList);
} else {
for (Courses wp : arrayList) {
if (wp.getCourseName().toLowerCase(Locale.getDefault()).contains(charText)) {
coursesArrayList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Courses.java
public class Courses {
// variables for storing our data.
private String courseName, courseDescription, courseDuration;
public Courses() {
// empty constructor
// required for Firebase.
}
// Constructor for all variables.
public Courses(String courseName, String courseDescription, String courseDuration) {
this.courseName = courseName;
this.courseDescription = courseDescription;
this.courseDuration = courseDuration;
}
// getter methods for all variables.
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getCourseDescription() {
return courseDescription;
}
// setter method for all variables.
public void setCourseDescription(String courseDescription) {
this.courseDescription = courseDescription;
}
public String getCourseDuration() {
return courseDuration;
}
public void setCourseDuration(String courseDuration) {
this.courseDuration = courseDuration;
}
}
i dont want to make this classs as static it give me error to uch so icant to amke search option in my android application i cant resolve this issue please help to resolve this issue.
i getting error in CourseRVAdapter.filter(text);
this to make filter as static this filter is make in CoursesRVAdapter public void filter(String charText) {------}
is the classs so what can do for making search option in recyclerview adapter list in android.
and please if you getting any suggesion for me please give me
i appreciating all of the things that you will says to me
thank you so much

RecyclerView: how to start Contextual Action Bar CAB with a Checkbox?

I have a RecyclerView list of CardViews and am using AppCompatActivity. Each CardView has a checkbox. When I click on the checkbox I would like to start a Contextual Action Bar. I would like to use an OnCheckedChangeListener and am having no luck. The checkmark correctly becomes visible when the "chkSelected" Checkbox is clicked on and it becomes invisible when the "chkSelected is clicked on again. What am I missing here?
public class MyRecylerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
...
private static ActionMode.Callback actionModeCallback = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
};
...
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_contact_item, parent, false);
final ItemHolder itemHolder = new ItemHolder(view);
return itemHolder;
}
private static class ItemHolder extends RecyclerView.ViewHolder {
private CheckBox chkSelected;
private ItemHolder(View itemView) {
super(itemView);
chkSelected = (CheckBox) itemView.findViewById(R.id.chkSelected);
chkSelected.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
mActionMode = ((AppCompatActivity) buttonView.getContext()).startSupportActionMode(actionModeCallback);
}
});
}
I also tried an OnClickListener() in the ItemHolder() with no luck. Code is below. The Toast in the onClick() is showing properly so there must be something wrong with the startSupportActionMode().
chkSelected.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(),"Checkbox was clicked",Toast.LENGTH_LONG).show();
if(mActionMode == null) {
// Start the Contextual Action Bar (CAB) using the ActionMode.Callback defined above
mActionMode = ((AppCompatActivity) view.getContext()).startSupportActionMode(mActionModeCallback);
}
}
});
Solution was to set up a method in onBindViewHolder() that would update the item views for the OnClickListeners in Itemholder().

Tableview update database on edit

So the thing that i want to happen, is making the tableview update the data in the database after editing it. I wanted to use the SetOnEditCommit method here. The cell editing does work, but it never gets updated, with no error either. In the first place im a bit clueless if this method is actually efficient (probably not), since its hard to find some sources for this specific thing. And the sources that i found weren't really helpful. So it would be nice if someone had an idea as to why it doesn't update, or maybe provide an alternate option here.
The mentioned part:
columnType.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<UserDetails, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<UserDetails, String> event) {
updataData();
}
});
tableview.setItems(null);
tableview.setItems(data);
}
public void updataData() {
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://37.128.148.113:3306/FYS", "FYS", "Kcj8g87~");
Statement con = connection.createStatement();
//connection
TablePosition pos = tableview.getSelectionModel().getSelectedCells().get(0);
int row = pos.getRow();
TableColumn col = pos.getTableColumn();
String data1 = (String) col.getCellObservableValue(row).getValue();
//cell
UserDetails row1 = tableview.getSelectionModel().getSelectedItem();
c1 = row1.getId();
//row
//tableview variables
con.execute("UPDATE gevonden_bagage SET type = 'data1' WHERE koffer_id = 'c1' ");
//Query
} catch (SQLException ex) {
System.err.println("Error" + ex);
}
}
//get connection, get celldata, get id data from first row, update cell with selected id
full controller class:
package simple;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TablePosition;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
/**
*
* #author admin
*/
public class FXMLUserController extends SimpleController implements Initializable {
#FXML
public TableView<UserDetails> tableview;
#FXML
public TableColumn<UserDetails, String> columnId;
#FXML
public TableColumn<UserDetails, String> columnType;
#FXML
public TableColumn<UserDetails, String> columnKleur;
#FXML
public TableColumn<UserDetails, String> columnLuchthaven;
#FXML
public TableColumn<UserDetails, String> columnKenmerken;
#FXML
public TableColumn<UserDetails, String> columnStatus;
#FXML
public TableColumn<UserDetails, String> columnDatum;
#FXML
private Button btnLoad;
//declare observable list for database data
private ObservableList<UserDetails> data;
private DbConnection dc;
String c1;
#FXML
//strings for getRow method
#Override
public void initialize(URL url, ResourceBundle rb) {
dc = new DbConnection();
loadDataFromDatabase();
}
#FXML
public void loadDataFromDatabase() {
try {
Connection conn = dc.Connect();
data = FXCollections.observableArrayList();
// Execute query and store result in a resultset
ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM gevonden_bagage");
while (rs.next()) {
//get strings
data.add(new UserDetails(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5),
rs.getString(6), rs.getString(7)));
}
} catch (SQLException ex) {
System.err.println("Error" + ex);
}
//Set cell values to tableview.
tableview.setEditable(true);
tableview.getSelectionModel().setCellSelectionEnabled(true);
columnType.setCellFactory(TextFieldTableCell.forTableColumn());
columnKleur.setCellFactory(TextFieldTableCell.forTableColumn());
columnLuchthaven.setCellFactory(TextFieldTableCell.forTableColumn());
columnKenmerken.setCellFactory(TextFieldTableCell.forTableColumn());
columnStatus.setCellFactory(TextFieldTableCell.forTableColumn());
columnDatum.setCellFactory(TextFieldTableCell.forTableColumn());
//makes columns editable
columnId.setCellValueFactory(new PropertyValueFactory<>("id"));
columnType.setCellValueFactory(new PropertyValueFactory<>("type"));
columnKleur.setCellValueFactory(new PropertyValueFactory<>("kleur"));
columnLuchthaven.setCellValueFactory(new PropertyValueFactory<>("luchthaven"));
columnKenmerken.setCellValueFactory(new PropertyValueFactory<>("kenmerken"));
columnStatus.setCellValueFactory(new PropertyValueFactory<>("status"));
columnDatum.setCellValueFactory(new PropertyValueFactory<>("datum"));
columnType.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<UserDetails, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<UserDetails, String> event) {
updataData();
}
});
tableview.setItems(null);
tableview.setItems(data);
}
public void updataData() {
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://37.128.148.113:3306/FYS", "FYS", "Kcj8g87~");
Statement con = connection.createStatement();
//connection
TablePosition pos = tableview.getSelectionModel().getSelectedCells().get(0);
int row = pos.getRow();
TableColumn col = pos.getTableColumn();
String data1 = (String) col.getCellObservableValue(row).getValue();
//cell
UserDetails row1 = tableview.getSelectionModel().getSelectedItem();
c1 = row1.getId();
//row
//tableview variables
con.execute("UPDATE gevonden_bagage SET type = 'data1' WHERE koffer_id = 'c1' ");
//Query
} catch (SQLException ex) {
System.err.println("Error" + ex);
}
}
//get connection, get celldata, get id data from first row, update cell with selected id
#FXML
public void getRow() {
TablePosition pos = tableview.getSelectionModel().getSelectedCells().get(0);
int row = pos.getRow();
TableColumn col = pos.getTableColumn();
// this gives the value in the selected cell:
String data1 = (String) col.getCellObservableValue(row).getValue();
System.out.println(data1);
//CURRENTLY UNUSED METHOD
}
}
Model class:
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
*
* #author admin
*/
public class UserDetails {
private final StringProperty id;
private final StringProperty type;
private final StringProperty kleur;
private final StringProperty luchthaven;
private final StringProperty kenmerken;
private final StringProperty status;
private final StringProperty datum;
//Default constructor
public UserDetails(String id, String type, String kleur, String luchthaven, String kenmerken, String status, String datum) {
this.id = new SimpleStringProperty(id);
this.type = new SimpleStringProperty(type);
this.kleur = new SimpleStringProperty(kleur);
this.luchthaven = new SimpleStringProperty(luchthaven);
this.kenmerken = new SimpleStringProperty(kenmerken);
this.status = new SimpleStringProperty(status);
this.datum = new SimpleStringProperty(datum);
}
//getters
public String getId() {
return id.get();
}
public String getType() {
return type.get();
}
public String getKleur() {
return kleur.get();
}
public String getLuchthaven() {
return luchthaven.get();
}
public String getKenmerken() {
return kenmerken.get();
}
public String getStatus() {
return status.get();
}
public String getDatum() {
return datum.get();
}
//setters
public void setId(String value) {
id.set(value);
}
public void setType(String value) {
type.set(value);
}
public void setKleur(String value) {
kleur.set(value);
}
public void setLuchthaven(String value) {
luchthaven.set(value);
}
public void setKenmerken(String value) {
kenmerken.set(value);
}
public void setStatus(String value) {
status.set(value);
}
public void setDatum(String value) {
datum.set(value);
}
//property values
public StringProperty idProperty() {
return id;
}
public StringProperty typeProperty() {
return type;
}
public StringProperty kleurProperty() {
return kleur;
}
public StringProperty luchthavenProperty() {
return luchthaven;
}
public StringProperty kenmerkenProperty() {
return kenmerken;
}
public StringProperty statusProperty() {
return status;
}
public StringProperty datumProperty() {
return datum;
}
}
From the TableView documentation:
By default the TableColumn edit commit handler is non-null, with a
default handler that attempts to overwrite the property value for the
item in the currently-being-edited row. It is able to do this as the
Cell.commitEdit(Object) method is passed in the new value, and this is
passed along to the edit commit handler via the CellEditEvent that is
fired. It is simply a matter of calling
TableColumn.CellEditEvent.getNewValue() to retrieve this value.
It is very important to note that if you call
TableColumn.setOnEditCommit(javafx.event.EventHandler) with your own
EventHandler, then you will be removing the default handler. Unless
you then handle the writeback to the property (or the relevant data
source), nothing will happen.
So the problem is that by setting the onEditCommit on columnType, you remove the default handler that actually updates typeProperty in the UserDetails instance. Consequently
String data1 = (String) col.getCellObservableValue(row).getValue();
gives the old value, and your update to the database won't change anything.
Additionally, you have errors in the way you create the SQL statement. You are making the id in the WHERE clause the literal value 'c1' (instead of the value contained in the variable c1, and similarly setting the value of type to the literal value 'data1', instead of the value in the variable data1.
Here is a fix, along with some simplification of the code and some better practices for avoiding SQL injection attacks:
columnType.setOnEditCommit(event -> {
UserDetails user = event.getRowValue();
user.setType(event.getNewValue());
updateData("type", event.getNewValue(), user.getId());
});
and then
private void updateData(String column, String newValue, String id) {
// btw it is way better to keep the connection open while the app is running,
// and just close it when the app shuts down....
// the following "try with resources" at least makes sure things are closed:
try (
Connection connection = DriverManager.getConnection("jdbc:mysql://37.128.148.113:3306/FYS", "FYS", "Kcj8g87~");
PreparedStatement stmt = connection.prepareStatement("UPDATE gevonden_bagage SET "+column+" = ? WHERE koffer_id = ? ");
) {
stmt.setString(1, newValue);
stmt.setString(2, id);
stmt.execute();
} catch (SQLException ex) {
System.err.println("Error");
// if anything goes wrong, you will need the stack trace:
ex.printStackTrace(System.err);
}
}

Accessing XML Image Array within an ImageAdapter

My question is very similar to this thread, however it was never properly answered.
I have an ImageAdapter setup as so;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
int[] mImages;
public ImageAdapter(Context c, int[] images) {
mContext = c;
mImages = images;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(200, 200));
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mImages[position]);
return imageView;
}
}
And I want the images to be from an XML;
<integer-array name="images">
<item>#drawable/image1</item>
<item>#drawable/image2</item>
<item>#drawable/image3</item>
</integer-array>
In my MainActivity class I have tried to get the image array and pass it into the ImageAdapter but I can't;
public class MainActivity extends AppCompatActivity {
private int images[] = getResources().getIntArray(R.array.images);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridview = (GridView) findViewById(R.id.gridView);
gridview.setAdapter(new ImageAdapter(MainActivity.this, images));
}
}
I am currently getting an error message:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
with my app crashing on load up. I want to make my ImageAdapter display images from an XML in my GridView.
try to use
private int images[] = {R.drawable.image1, R.drawable.image3, R.drawable.image3};
instead of
private int images[] = getResources().getIntArray(R.array.images);

JavaFX 8: Checkbox in TableView and Add-on into to selected Item?

I would like to create a payroll program such that when the user tick a CheckBox in TableView, the name (String) will be carried on to the panel on the right and with TextFields to enter more info such as this:
I tried to follow the MVC hierarchy thus far as I code:
PayrollMainApp.java
public class PayrollMainApp extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
private ObservableList<Employee> selectEmployeeTable = FXCollections.observableArrayList();
public PayrollMainApp(){
selectEmployeeTable.add(new Employee(false,"Hans Muster"));
selectEmployeeTable.add(new Employee(true,"Ruth Mueller"));
selectEmployeeTable.add(new Employee(false,"Heinz Kurz"));
selectEmployeeTable.add(new Employee(false,"Cornelia Meier"));
selectEmployeeTable.add(new Employee(false,"Werner Meyer"));
selectEmployeeTable.add(new Employee(false,"Lydia Kunz"));
selectEmployeeTable.add(new Employee(false,"Anna Best"));
selectEmployeeTable.add(new Employee(false,"Stefan Meier"));
selectEmployeeTable.add(new Employee(false,"Martin Mueller"));
}
public ObservableList<Employee> getSelectEmployeeTable(){
return selectEmployeeTable;
}
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("PayrollApp");
initRootLayout();
showEmployeeOverview();
}
/**
* Initializes the root layout.
*/
public void initRootLayout() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(PayrollMainApp.class.getResource("view/RootLayout.fxml"));
rootLayout = (BorderPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Shows the person overview inside the root layout.
*/
public void showEmployeeOverview() {
try {
// Load person overview.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(PayrollMainApp.class.getResource("view/EmployeeOverview.fxml"));
AnchorPane personOverview = (AnchorPane) loader.load();
// Set person overview into the center of root layout.
rootLayout.setCenter(personOverview);
// Give the controller access to the main app
EmployeeOverviewController controller = loader.getController();
controller.setMainApp(this);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Returns the main stage.
* #return
*/
public Stage getPrimaryStage() {
return primaryStage;
}
public static void main(String[] args) {
launch(args);
}
}
Employee.java
public class Employee {
private BooleanProperty checkedBox = new SimpleBooleanProperty(false);
private StringProperty employeeName = new SimpleStringProperty();
public Employee(){
super();
}
public Employee(boolean checkedBox, String employeeName){
this.checkedBox = new SimpleBooleanProperty(false);
this.employeeName = new SimpleStringProperty(employeeName);
}
public BooleanProperty checkedBoxProperty(){
return this.checkedBox;
}
public StringProperty employeeNameProperty(){
return this.employeeName;
}
public java.lang.Boolean getSelectBox() {
return this.checkedBoxProperty().get();
}
public StringProperty getEmployeeName() {
return employeeName;
}
public void setSelectBox(final java.lang.Boolean checkedBox){
this.checkedBoxProperty().set(checkedBox);
}
public void setEmployeeName(StringProperty employeeName) {
this.employeeName = employeeName;
}
}
EmployeeOverviewController.java
public class EmployeeOverviewController {
#FXML
private TableView<Employee> selectEmployeeTable;
#FXML
private TableColumn<Employee, String> employeeNameColumn;
#FXML
private TableColumn<Employee, Boolean> checkBoxColumn;
private PayrollMainApp mainApp;
public EmployeeOverviewController() {
}
#FXML
public void initialize() {
checkBoxColumn.setCellValueFactory(cellData -> cellData.getValue().checkedBoxProperty());
checkBoxColumn.setCellFactory(param -> new CheckBoxTableCell<Employee, Boolean>());
employeeNameColumn.setCellValueFactory(cellData -> cellData.getValue().employeeNameProperty());
}
public void setMainApp(PayrollMainApp mainApp){
this.mainApp = mainApp;
//Add observable list data to the table
selectEmployeeTable.setItems(mainApp.getSelectEmployeeTable());
}
}
And a util class to make the checkBox visible in the table:
SelectBoxCellFactory.java
public class SelectBoxCellFactory implements Callback {
#Override
public TableCell call(Object param) {
CheckBoxTableCell<Employee,Boolean> checkBoxCell = new CheckBoxTableCell();
return checkBoxCell;
}
}
Here is my output thus far:
I know this has a table in it as compared to the previous output. Honestly I'm still indecisive as to use which, because I think using TextFields would make it look better. But all I hope for now is that this design is not impossible to code...
I really hope you can help me... Thank you for your help in advance.
It's probably easiest to use a TableView for the right panel. You can create a FilteredList from your original list:
FilteredList<Employee> selectedEmployees
= new FilteredList<>(selectEmployeeTable, Employee::getSelectBox);
and then use that for your second table.
If you prefer to use text fields (in what looks like a GridPane?) you can still use the filtered list above, but you will need to register a listener with it and update the layout "by hand" when items are added and removed.

Resources