mardi 29 mars 2016

Onclick of item Sending position of the gridview to the listview to fetch data from sqlite database in android

I'm developing music related Android App. I have sqlite database having data about album,tracks,release year,lyrics etc... I have a Gridview,fetched album names from sqlite and displayed in the gridview succesfully. On clicking an item in gridview a new activity with listview displaying tracks of that album must be created. On clicking an item in the listview a new activity displaying the remaining datas of that track must be created. I'm new to android and i need help with this. Thanks in advance.

My Cursor adapter

public class CursorTrackAdapter extends CursorAdapter {
public CursorTrackAdapter(Context context, Cursor cursor) {
    super(context, cursor, 0);
}


@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    return LayoutInflater.from(context).inflate(R.layout.list_song, parent, false);
}
public static Bitmap getImageFromBLOB(byte[] mBlob)
{
    byte[] bb = mBlob;
    return BitmapFactory.decodeByteArray(bb, 0, bb.length);
}
// The bindView method is used to bind all data to a given view
// such as setting the text on a TextView.
@TargetApi(Build.VERSION_CODES.KITKAT)
@SuppressLint("NewApi")
@Override
public void bindView(View view, Context context, Cursor cursor) {

    // Find fields to populate in inflated template
    TextView tvBody = (TextView) view.findViewById(R.id.textView1);
    String body = cursor.getString(cursor.getColumnIndexOrThrow("Label"));
    tvBody.setText(body);

    ImageView mImageView = (ImageView) view.findViewById(R.id.imageView1);
    mImageView.setImageBitmap(getImageFromBLOB(cursor.getBlob(cursor.getColumnIndex("Cover"))));



}

My Album fragment Class

public static class AlbumsFragment extends Fragment {


    public static AlbumsFragment newInstance() {
        AlbumsFragment f = new AlbumsFragment();
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout resource that'll be returned
        View rootView = inflater.inflate(R.layout.fragment_album, container, false);

        DatabaseOpenHelper handler = new DatabaseOpenHelper(getContext());

        SQLiteDatabase db = handler.getWritableDatabase();

        Cursor todoCursor = db.rawQuery("SELECT  * FROM album", null);

        GridView gv = (GridView) rootView.findViewById(R.id.gridView);

        CursorAlbumAdapter todoAdapter = new CursorAlbumAdapter(getContext(), todoCursor);

        gv.setAdapter(todoAdapter);
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                for (position=0;position>=0;position++) {
                    Intent toActivity = new Intent(getActivity(), PlaySong.class);
                    startActivity(toActivity);

                }
            }
        });





        return rootView;
    }

Need help in this SongList Activity class

public class SongsList extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_songs_list);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

Here is my Database Opener class

public class DatabaseOpenHelper extends SQLiteOpenHelper{
private SQLiteDatabase myDataBase;
private final Context myContext;
private static final String DATABASE_NAME = "db.sqlite";
@SuppressLint("SdCardPath")
public final static String DATABASE_PATH="/data/data/PACKAGE_NAME/databases/";
public static final int DATABASE_VERSION = 1;
//public static final int DATABASE_VERSION_old = 1;

//Constructor
public DatabaseOpenHelper(Context context)
{
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    this.myContext = context;
}

//Create a empty database on the system
public void createDatabase() throws IOException
{
    boolean dbExist = checkDataBase();

    if(dbExist)
    {
        Log.v("DB Exists", "db exists");
        // By calling this method here onUpgrade will be called on a
        // writeable database, but only if the version number has been
        // bumped
        //onUpgrade(myDataBase, DATABASE_VERSION_old, DATABASE_VERSION);
    }

    boolean dbExist1 = checkDataBase();
    if(!dbExist1)
    {
        this.getReadableDatabase();
        try
        {
            this.close();
            copyDataBase();
        }
        catch (IOException e)
        {
            throw new Error("Error copying database");
        }
    }
}

//Check database already exist or not
private boolean checkDataBase()
{
    boolean checkDB = false;
    try
    {
        String myPath = DATABASE_PATH + DATABASE_NAME;
        File dbfile = new File(myPath);
        checkDB = dbfile.exists();
    }
    catch(SQLiteException ignored)
    {
    }
    return checkDB;
}


private void copyDataBase() throws IOException
{
    String outFileName = DATABASE_PATH + DATABASE_NAME;
    OutputStream myOutput = new FileOutputStream(outFileName);
    InputStream myInput = myContext.getAssets().open(DATABASE_NAME);

    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0)
    {
        myOutput.write(buffer, 0, length);
    }
    myInput.close();
    myOutput.flush();
    myOutput.close();
}

//delete database
public void db_delete()
{
    File file = new File(DATABASE_PATH + DATABASE_NAME);
    if(file.exists())
    {
        file.delete();
        System.out.println("delete database file.");
    }
}

//Open database
public void openDatabase() throws SQLException
{
    String myPath = DATABASE_PATH + DATABASE_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);


}

public synchronized void closeDataBase()throws SQLException
{
    if(myDataBase != null)
        myDataBase.close();
    super.close();
}

@Override
public void onCreate(SQLiteDatabase db) {}

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
    if (newVersion > oldVersion)
    {
        Log.v("Database Upgrade", "Database version higher than old.");
        db_delete();
    }
}

For your reference I include screenshot of my database designDatabaseTrack

DatabaseAlbum

Aucun commentaire:

Enregistrer un commentaire