0

first user give input sub,classAttended,Total class in other activity then i store in database and then i show data on recycler view with the help of list the i want when user click on +/- then that subject attendance increase by 1 and also total class by 1 but my app get crash when i click on that +/-btn

RecVIewAdapter

public class recViewAdapter extends RecyclerView.Adapter<recViewAdapter.viewHolder> {

private Context mContext;
MyHelper helper = new MyHelper(mContext);
List<SubjectModel> list;

public recViewAdapter(List<SubjectModel> list) {
    this.list = list;
    notifyDataSetChanged();
}

@NonNull
@Override
public viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_recview, parent, false);
    return new viewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull final viewHolder holder, final int position) {

    holder.subject.setText(list.get(position).getSubject());
    holder.classesAttended.setText(list.get(position).getClassesAttended());
    holder.totalClasses.setText("/" + list.get(position).getTotalClasses());
    String result = String.valueOf(Integer.valueOf(list.get(position).getClassesAttended()) * 100 / Integer.valueOf(list.get(position).getTotalClasses()));
    holder.attendancePercentage.setText(result + "%");

    holder.presentBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int cl_attended=0,t_classes=0;
            cl_attended = Integer.parseInt(String.valueOf(list.get(position).getClassesAttended()));
            t_classes = Integer.parseInt(String.valueOf(list.get(position).getTotalClasses()));
            cl_attended++;
            t_classes++;
            helper.updateData(list.get(position).getId(),String.valueOf(cl_attended),String.valueOf(t_classes));
            notifyDataSetChanged();
        }
    });

    holder.absentBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

}

@Override
public int getItemCount() {
    return list.size();
}

public class viewHolder extends RecyclerView.ViewHolder {

    private TextView subject, classesAttended, totalClasses, attendancePercentage;
    private ImageView presentBtn, absentBtn;

    public viewHolder(@NonNull final View itemView) {
        super(itemView);

        subject = itemView.findViewById(R.id.subject);
        classesAttended = itemView.findViewById(R.id.class_attended);
        totalClasses = itemView.findViewById(R.id.total_clases);
        attendancePercentage = itemView.findViewById(R.id.attendance_percentage);
        presentBtn = itemView.findViewById(R.id.present);
        absentBtn = itemView.findViewById(R.id.absent);

    }
}

}

Databasehelper

public class MyHelper extends SQLiteOpenHelper {

private static final String dbname = "mydb";
private static final int version = 1;
private Context context;

public  MyHelper(Context context){
    super(context,dbname,null,version);

}
@Override
public void onCreate(SQLiteDatabase db) {

    String query="CREATE TABLE IF NOT EXISTS STUDENTS_DETAILS (ID INTEGER PRIMARY KEY AUTOINCREMENT, SUB_NAME TEXT ,CLASS_ATTENDED INT ,TOTAL_CLASSES INT)";
    db.execSQL(query);

}

public boolean insertData(String subject, String  class_attended, String total_classes){
    SQLiteDatabase database=this.getWritableDatabase();
    ContentValues values =new ContentValues();
    values.put("SUB_NAME",subject);
    values.put("CLASS_ATTENDED",class_attended);
    values.put("TOTAL_CLASSES",total_classes);
    long result =database.insert("STUDENTS_DETAILS",null,values);
    if(result == -1) return  false;
    else return true;
}

public Cursor getData(){
    String query ="SELECT * FROM STUDENTS_DETAILS";
    SQLiteDatabase database =this.getReadableDatabase();
    Cursor cursor = null;
    if(database != null){
        cursor =database.rawQuery(query,null);
    }
    return cursor;
};

public void updateData(String id,String classAttended,String totalClasses){

    SQLiteDatabase database =this.getWritableDatabase();
    ContentValues values =new ContentValues();
    values.put("CLASS_ATTENDED",classAttended);
    values.put("TOTAL_CLASSES",totalClasses);
    long result =database.update("STUDENTS_DETAILS",values,"ID=?",new String[]{id} );
    if(result == -1){
        Toast.makeText(context, "Succesfully Updated", Toast.LENGTH_SHORT).show();
    }else {
        Toast.makeText(context, "failed in update data", Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

}

MY list item*image of my list item +/- is present/absent btn and 25/30 is classAttended/totalClasses

my app get crash when i click on present btn Error-- on click presentBtn then the data is not updated in database and updateData is not called why updateData of databaseHelper is not invoke pls tell that

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.attendancemanager, PID: 11059
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference
    at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:371)
    at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:317)
    at com.example.attendancemanager.MyHelper.updateData(MyHelper.java:74)
    at com.example.attendancemanager.recViewAdapter$viewHolder$1.onClick(recViewAdapter.java:92)
    at android.view.View.performClick(View.java:7256)
    at android.view.View.performClickInternal(View.java:7218)
    at android.view.View.access$3800(View.java:824)
    at android.view.View$PerformClick.run(View.java:27719)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:228)
    at android.app.ActivityThread.main(ActivityThread.java:7782)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:981)
  • Hi, if the app crashed, you should post the crash logs here for us to get a better idea of the problem. Use the logcat in Android Studio while opening the app on your device. When the app crashes, you will notice there are error logs in the logcat. Read through them and if they still don't solve your issue, paste the relevant portions here. – Yashovardhan99 Jun 08 '20 at 18:30

2 Answers2

0

You change like below

private Context mContext;
    MyHelper helper = new MyHelper(mContext);
    List<SubjectModel> list;

    public recViewAdapter(List<SubjectModel> list) {
        this.list = list;
        notifyDataSetChanged();
    }
...

Toast.makeText(v.getContext(), "absent clicked", Toast.LENGTH_SHORT).show();

to

private Context mContext;
    MyHelper helper;
    List<SubjectModel> list;

    public recViewAdapter(Context context, List<SubjectModel> list) {
        this.mContext = context;
        helper = new MyHelper(mContext);
        notifyDataSetChanged();
    }
...
Toast.makeText(mContext, "absent clicked", Toast.LENGTH_SHORT).show();

[java.lang.NullPointerException: Attempt to invoke virtual method ...] occurs when [method] is called on an object that is [null].

And please ask new questions in the new post.

won
  • 754
  • 6
  • 13
  • bro problem in my app with present btn when i click on that btn my app get crash and i know that my updateData in helperclass is not invoke when i press btn so pls help why this is happen pls help i am beghnear and i does not able to solve that problem – piyush meena Jun 09 '20 at 06:50
  • You need to understand the difference between'v.getContext()' and 'mContext'. and see a https://stackoverflow.com/questions/3572463/what-is-context-on-android. Toast need ApplicationContext or ActivityContext. – won Jun 09 '20 at 06:58
  • bro you didn't resolve my problem yet my problem with the database and you stop at toast bro toast can be changed after after my problem resolve it was not that big issue pls resolv why my database is not update pls read the whole question properly – piyush meena Jun 18 '20 at 05:09
  • Are you tried this code? `public recViewAdapter(Context context, List list) { this.mContext = context; helper = new MyHelper(mContext); notifyDataSetChanged(); }` – won Jun 19 '20 at 01:18
0

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.attendancemanager, PID: 11059 java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference

=> Your Context object is null Please check your Context object in MyHelper.java:74

EddyLee
  • 803
  • 2
  • 8
  • 26