dimanche 7 juin 2015

java.lang.NullPointerException Android SQLite

I have created a database, and I want to access it by ID. But, I got an error "java.lang.NullPointerException". There are two files, HadisDetails.java and DBHelperHadis.java. I got an error when I want to access the data at HadisDetails.java.

HadisDetails.java

public class HadisDetails extends AppCompatActivity{

TextView noDanTajukHadis, hadisContent, tajukAudio, terjemahan;
Toolbar toolbar;
MediaPlayer mp;
private Button buttonPlayStop;
private SeekBar seekBar;
private int _Hadis_Id=0;

private final Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_notes_detail);

    toolbar = (Toolbar) findViewById(R.id.tool_bar);
    setSupportActionBar(toolbar);

    noDanTajukHadis = (TextView) findViewById(R.id.tajukHadis);
    hadisContent = (TextView) findViewById(R.id.hadisView);
    tajukAudio = (TextView) findViewById(R.id.audioHadis);
    terjemahan = (TextView) findViewById(R.id.terjemahan);

    _Hadis_Id =0;
    Intent intent = getIntent();
    _Hadis_Id =intent.getIntExtra("hadis_ID", 0);
    DBHelperHadis repo = new DBHelperHadis(this);
    Hadis hadis= new Hadis();
    hadis = repo.getHadisById(_Hadis_Id);

    noDanTajukHadis.setText(hadis.no_hadis + hadis.tajuk_hadis); //error at this line
    hadisContent.setText(hadis.hadis_content);
    tajukAudio.setText(hadis.tajuk_audio_hadis);
    terjemahan.setText(hadis.terjemahan);

    initViews();

    ImageButton kongsiHadis = (ImageButton) findViewById(R.id.kongsiHadis);

    kongsiHadis.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //your code here that you want to run
            Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
            whatsappIntent.putExtra(Intent.EXTRA_TEXT, hadisContent + "\n\n" + terjemahan);
            whatsappIntent.setType("text/plain");
            try {
                startActivity(Intent.createChooser(whatsappIntent, "Share"));
            } catch (android.content.ActivityNotFoundException ex) {
                Toast.makeText(HadisDetails.this, "Aplikasi yang diminta tidak dipasang.", Toast.LENGTH_LONG).show();
            }
        }
    });


    android.support.v7.app.ActionBar actionBar = getSupportActionBar();
    actionBar.setHomeButtonEnabled(true);
    actionBar.setDisplayHomeAsUpEnabled(true);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    switch (item.getItemId()) {
        case android.R.id.home:
            // app icon in action bar clicked; goto parent activity.
            this.finish();
            mp.stop();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

private void initViews() {
    buttonPlayStop = (Button) findViewById(R.id.button);
    buttonPlayStop.setOnClickListener(new View.OnClickListener() {@Override public void onClick(View v) {buttonClick();}});

    _Hadis_Id =0;
    Intent intent = getIntent();
    _Hadis_Id =intent.getIntExtra("hadis_ID", 0);
    HadisRepo repo = new HadisRepo(this);
    Hadis hadis= new Hadis();
    hadis = repo.getHadisById(_Hadis_Id);

    int resID = getResources().getIdentifier(hadis.audio_hadis,"String", "com.psm.app.hadis40_07");

    mp = MediaPlayer.create(this, resID);
    seekBar = (SeekBar) findViewById(R.id.SeekBar01);
    seekBar.setEnabled(false);
    seekBar.setMax(mp.getDuration());
    seekBar.setOnTouchListener(new View.OnTouchListener()
    {
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
            seekChange(v);
            return false;
        }
    });
}

//semak kemajuan audio
public void startPlayProgressUpdater() {
    seekBar.setProgress(mp.getCurrentPosition());

    if (mp.isPlaying()) {
        seekBar.setEnabled(true);
        Runnable notification = new Runnable() {
            public void run() {
                startPlayProgressUpdater();
            }
        };
        handler.postDelayed(notification,1000);
    }else{
        mp.pause();
        buttonPlayStop.setText(getString(R.string.play_str));
        seekBar.setEnabled(false);
        //seekBar.setProgress(0);
    }
}

// This is event handler thumb moving event
private void seekChange(View v){
    if(mp.isPlaying()){
        SeekBar sb = (SeekBar)v;
        mp.seekTo(sb.getProgress());
    }

}

private void buttonClick(){
    if (buttonPlayStop.getText() == getString(R.string.play_str)) {
        buttonPlayStop.setText(getString(R.string.pause_str));
        try{
            mp.start();
            startPlayProgressUpdater();
        }catch (IllegalStateException e) {
            mp.pause();
        }
    }else {
        buttonPlayStop.setText(getString(R.string.play_str));
        mp.pause();
    }
}

@Override
public void onBackPressed ()
{
    if (mp != null)
        mp.stop();


    super.onBackPressed();
}

@Override
protected void onPause() {
    super.onPause(); // Don't forget this line
    mp.pause(); // Or whatever the function is to pause it
}
}

DBHelperHadis.java

 public class DBHelperHadis extends SQLiteOpenHelper {

//The Android's default system path of your application database.
public static String DB_PATH            = "data/data/com.psm.app.hadis40_07/databases/";
public static String DB_NAME            = "hadis40_db";
public static String TABLE_LOCATION     = "hadis";

private DBHelperHadis dbHelperHadis;
private final Context context;
private SQLiteDatabase db;


// constructor
public DBHelperHadis(Context context) {

    super(context , DB_NAME ,null , 1);
    this.context = context;
}

// Creates a empty database on the system and rewrites it with your own database.
public void create() throws IOException {

    boolean dbExist = checkDataBase();

    if(dbExist){
        //do nothing - database already exist
    }else{

        // By calling this method and empty database will be created into the default system path
        // of your application so we are gonna be able to overwrite that database with our database.
        this.getReadableDatabase();

        try {

            copyDataBase();

        } catch (IOException e) {

            throw new Error("Error copying database");

        }
    }

}

// Check if the database exist to avoid re-copy the data
private boolean checkDataBase(){

    SQLiteDatabase checkDB = null;

    try{


        String path = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);

    }catch(SQLiteException e){

        // database don't exist yet.
        e.printStackTrace();

    }

    if(checkDB != null){

        checkDB.close();

    }

    return checkDB != null ? true : false;
}

// copy your assets db to the new system DB
private void copyDataBase() throws IOException{

    //Open your local db as the input stream
    InputStream myInput = context.getAssets().open(DB_NAME);

    // Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;

    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    //transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
        myOutput.write(buffer, 0, length);
    }

    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

}

//Open the database
public boolean open() {

    try {
        String myPath = DB_PATH + DB_NAME;
        db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
        return true;

    } catch(SQLException sqle) {
        db = null;
        return false;
    }

}

@Override
public synchronized void close() {

    if(db != null)
        db.close();

    super.close();

}

@Override
public void onCreate(SQLiteDatabase db) {

}

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

}

// PUBLIC METHODS TO ACCESS DB CONTENT
// -----------------------------------------------------------------------------------------------------------------

public ArrayList<HashMap<String, String>> getHadisList() {
    //Open connection to read only
    //SQLiteDatabase db = dbHelperHadis.getReadableDatabase();
    String selectQuery =  "SELECT  " +
            Hadis.KEY_hadisID + "," +
            Hadis.KEY_noHadis + "," +
            Hadis.KEY_tajukHadis +
            " FROM " + TABLE_LOCATION;

    SQLiteDatabase  db = SQLiteDatabase.openDatabase( DB_PATH + DB_NAME , null, SQLiteDatabase.OPEN_READWRITE);

    //Student student = new Student();
    ArrayList<HashMap<String, String>> hadisList = new ArrayList<HashMap<String, String>>();

    Cursor cursor = db.rawQuery(selectQuery, null);
    // looping through all rows and adding to list

    if (cursor.moveToFirst()) {
        do {
            HashMap<String, String> hadis = new HashMap<String, String>();
            hadis.put("id", cursor.getString(cursor.getColumnIndex(Hadis.KEY_hadisID)));
            hadis.put("name", cursor.getString(cursor.getColumnIndex(Hadis.KEY_noHadis)));
            hadis.put("tajuk", cursor.getString(cursor.getColumnIndex(Hadis.KEY_tajukHadis)));
            hadisList.add(hadis);

        } while (cursor.moveToNext());
    }

    cursor.close();
    db.close();
    return hadisList;

}

public Hadis getHadisById(int Id){

    String selectQuery =  "SELECT  " +
            Hadis.KEY_hadisID + "," +
            Hadis.KEY_noHadis + "," +
            Hadis.KEY_tajukHadis + "," +
            Hadis.KEY_hadis + "," +
            Hadis.KEY_terjemahan + "," +
            Hadis.KEY_tajukAudio + "," +
            Hadis.KEY_audioHadis + "," +
            Hadis.KEY_pengajaranHadis + "," +
            Hadis.KEY_sebabWurud +
            " FROM " + TABLE_LOCATION
            + " WHERE " +
            Hadis.KEY_hadisID + "=?";// It's a good practice to use parameter ?, instead of concatenate string

    int iCount =0;
    Hadis hadis40 = new Hadis();

    SQLiteDatabase  db      = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);

    Cursor cursor = db.rawQuery(selectQuery, new String[]{String.valueOf(Id)});
    //Cursor cursor = db.rawQuery(selectQuery, null);

    if (cursor.moveToFirst()) {
        do {
            hadis40.hadis_ID =cursor.getInt(cursor.getColumnIndex(Hadis.KEY_hadisID));
            hadis40.no_hadis =cursor.getString(cursor.getColumnIndex(Hadis.KEY_noHadis));
            hadis40.tajuk_hadis  =cursor.getString(cursor.getColumnIndex(Hadis.KEY_tajukHadis));
            hadis40.hadis_content =cursor.getString(cursor.getColumnIndex(Hadis.KEY_hadis));
            hadis40.terjemahan  =cursor.getString(cursor.getColumnIndex(Hadis.KEY_terjemahan));
            hadis40.tajuk_audio_hadis =cursor.getString(cursor.getColumnIndex(Hadis.KEY_tajukAudio));
            hadis40.audio_hadis  =cursor.getString(cursor.getColumnIndex(Hadis.KEY_audioHadis));
            hadis40.pengajaran_hadis =cursor.getString(cursor.getColumnIndex(Hadis.KEY_pengajaranHadis));
            hadis40.sebab_wurud_hadis  =cursor.getString(cursor.getColumnIndex(Hadis.KEY_sebabWurud));

        } while (cursor.moveToNext());
    }

    cursor.close();
    db.close();
    return hadis40;
}
}

I hope anyone here can help me. Thanks

Aucun commentaire:

Enregistrer un commentaire