jeudi 31 décembre 2015

App crashes when clicking on a button in fragment (when selecting data from SQLite) [duplicate]

This question already has an answer here:

I am building an application that save data in SQLite and has one main fragment and 2 others fragments with corresponding activities. I created a table and save the data the user enters in one fragment, it works. In the second fragment, I created a button, when the user clicks on it will make a select query on the db and show the data in an alert dialog. But when running the application, it crashes and gives the following error 12-31 14:53:48.569: E/AndroidRuntime(1288): FATAL EXCEPTION: main 12-31 14:53:48.569: E/AndroidRuntime(1288): Process: com.example.appointapp, PID: 1288 12-31 14:53:48.569: E/AndroidRuntime(1288): java.lang.NullPointerException 12-31 14:53:48.569: E/AndroidRuntime(1288): at com.example.appointapp.AppointFragment$3.onClick(AppointFragment.java:110) 12-31 14:53:48.569: E/AndroidRuntime(1288): at android.view.View.performClick(View.java:4438) 12-31 14:53:48.569: E/AndroidRuntime(1288): at android.view.View$PerformClick.run(View.java:18422) 12-31 14:53:48.569: E/AndroidRuntime(1288): at android.os.Handler.handleCallback(Handler.java:733) 12-31 14:53:48.569: E/AndroidRuntime(1288): at android.os.Handler.dispatchMessage(Handler.java:95) 12-31 14:53:48.569: E/AndroidRuntime(1288): at android.os.Looper.loop(Looper.java:136) 12-31 14:53:48.569: E/AndroidRuntime(1288): at android.app.ActivityThread.main(ActivityThread.java:5017) 12-31 14:53:48.569: E/AndroidRuntime(1288): at java.lang.reflect.Method.invokeNative(Native Method) 12-31 14:53:48.569: E/AndroidRuntime(1288): at java.lang.reflect.Method.invoke(Method.java:515) 12-31 14:53:48.569: E/AndroidRuntime(1288): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 12-31 14:53:48.569: E/AndroidRuntime(1288): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 12-31 14:53:48.569: E/AndroidRuntime(1288): at dalvik.system.NativeStart.main(Native Method)

Here is the code: AppointFragment.java

package com.example.appointapp;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;

public class AppointFragment extends Fragment{
    DatabaseHelper myDB;
    private static final String TAG = "AppoinFragment";
    EditText idap, chosdate , chostime;
    Button showp, saveap;
    private Appointment mappointment;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mappointment= new Appointment();


}



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
    View v = inflater.inflate(R.layout.fragment_appoint, parent, false);

    chosdate = (EditText)v.findViewById(R.id.datea_text);
    idap = (EditText)v.findViewById(R.id.idd_text);
    showp = (Button)v.findViewById(R.id.showp_button);
    saveap = (Button)v.findViewById(R.id.savea_button);
    chostime = (EditText)v.findViewById(R.id.timea_text);

    chostime.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Calendar mcurrentTime = Calendar.getInstance();
            int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
            int minute = mcurrentTime.get(Calendar.MINUTE);
            TimePickerDialog mTimePicker;
            mTimePicker = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                    chostime.setText( selectedHour + ":" + selectedMinute);
                }
            }, hour, minute, true);//Yes 24 hour time
            mTimePicker.setTitle("Select Time");
            mTimePicker.show();

        }
    });


    chosdate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                DialogFragment datePickerFragment = new DatePickerFragment() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int day) {
                        Log.d(TAG, "onDateSet");
                        Calendar c = Calendar.getInstance();
                        c.set(year, month, day);

                        String myFormat = "dd/MM/yy"; 
                        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

                        chosdate.setText(sdf.format(c.getTime()));

                        chosdate.requestFocus(); 
                    }
                };
                datePickerFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
            }
        }
    });

    viewAllP();
    return v;


}

    public void viewAllP()   {

        showp.setOnClickListener(

                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Cursor res = myDB.getAllPdata();
                        if (res.getCount() == 0){
                    //show message
                            showMessage("Error", "No data found");
                            return;

                    }


                        StringBuffer buffer = new StringBuffer();
                        while (res.moveToNext()){
                            buffer.append("Id:"+res.getString(0)+"\n");
                            buffer.append("Name:"+res.getString(1)+"\n");
                            buffer.append("Familyname:"+res.getString(2)+"\n");
                            buffer.append("DOB:"+res.getString(3)+"\n");
                            buffer.append("Address:"+res.getString(4)+"\n");
                            buffer.append("PhoneNumber:"+res.getString(5)+"\n");
                            buffer.append("Email:"+res.getString(6)+"\n");
                            buffer.append("Gender:"+res.getString(7)+"\n\n");


                        }
                        //show all data
                        showMessage("Patients", buffer.toString());
                    }


                }
                );
                }





        public void showMessage(String title, String Message){

            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setCancelable(true);
            builder.setTitle(title);
            builder.setMessage(Message);
            builder.show();

        }
        }

Databasehelper.java

package com.example.appointapp;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME="appo.db";
    public static final String TABLE_NAME = "patients_table";
    public static final String COL_1 = "ID";
    public static final String COL_2 = "NAME";
    public static final String COL_3 = "FAMILYNAME";
    public static final String COL_4 = "DOB";
    public static final String COL_5 = "ADDRESS";
    public static final String COL_6 = "PHONENUMBER";
    public static final String COL_7 = "EMAIL";
    public static final String COL_8 = "GENDER";

    public DatabaseHelper(Context context){
        super(context, DATABASE_NAME, null, 2);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL( "create table "+ TABLE_NAME + "( ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, FAMILYNAME TEXT, DOB TEXT, ADDRESS TEXT, PHONENUMBER TEXT, EMAIL TEXT, GENDER TEXT )" );

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);

    }

    public boolean insertData(String name, String familyname, String dob, String address, String phonenumber, String email, String gender) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2,name);
        contentValues.put(COL_3,familyname);
        contentValues.put(COL_4,dob);
        contentValues.put(COL_5,address);
        contentValues.put(COL_6,phonenumber);
        contentValues.put(COL_7,email);
        contentValues.put(COL_8,gender);
        long result = db.insert(TABLE_NAME, null , contentValues);
        if(result == -1)
            return false;
        else 
            return true;
}

    public Cursor getAllPdata ( ) {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery(" select * from " +TABLE_NAME, null);
        return res;
    }

}   

Please help

Aucun commentaire:

Enregistrer un commentaire