Problema inserimento dati in sqlite

Minnozzi Corrado

Nuovo Utente
8 Ago 2012
13
0
1
Salve,
nella mia app ho bisogno che aggiunga i dati inseriti nelle edittext ecc. in un database sqlite;
non riesco a capire il motivo per cui non li aggiunga.
Potete aiutarmi? Grazie.
Questa è l'activity:
Codice:
package it.prova.database;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.Toast;

public class AddActivity extends Activity
{
        ImageButton backAdd, saveBook, openCover;
        EditText title, author, publisher, year, pages, genre, price, isbn, storyDescription;
        static final int RESULT_LOAD_IMAGE = 1;
        ImageView cover;
        RatingBar rating;
        String selectedImagePath;
        ManageDB db;
        
        //Identificatore delle preferenze dell'applicazione
    public static String MY_PREFERENCES = "MyPref";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) 
        {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.add_layout);
                
                //Creo un'istanza della classe ManageDB
                this.db = new ManageDB(this);
                
                //Ottiene il riferimento alle Image Button
                this.backAdd = (ImageButton)findViewById(R.id.back_add);
                this.saveBook = (ImageButton)findViewById(R.id.save_book);
                this.openCover = (ImageButton)findViewById(R.id.open_cover);
                
                //Ottiene il riferimento alle EditText
                this.title = (EditText)findViewById(R.id.title_edittext);
                this.author = (EditText)findViewById(R.id.author_edittext);
                this.publisher = (EditText)findViewById(R.id.publisher_edittext);
                this.year = (EditText)findViewById(R.id.year_edittext);
                this.pages = (EditText)findViewById(R.id.pages_edittext);
                this.genre = (EditText)findViewById(R.id.genre_edittext);
                this.price = (EditText)findViewById(R.id.price_edittext);
                this.storyDescription = (EditText)findViewById(R.id.story_description_edittext);
                this.isbn = (EditText)findViewById(R.id.isbn_edittext);
                
                //Ottiene il riferimento alle ImageView
                this.cover = (ImageView)findViewById(R.id.cover);
                
                //Ottiene il riferimento al RatingBar
                this.rating = (RatingBar)findViewById(R.id.rating);
                
                //Setta l'OnTouchListener per ritornare nella lista
                this.backAdd.setOnTouchListener(new OnTouchListener() 
                {                       
                        @Override
                        public boolean onTouch(View v, MotionEvent event) 
                        {
                                if(event.getAction() == MotionEvent.ACTION_DOWN)
                                {
                                        backAdd.setImageResource(R.drawable.back_click);
                                        return true;
                                }
                                else if(event.getAction() == MotionEvent.ACTION_UP)
                                {
                                        backAdd.setImageResource(R.drawable.back);
                                        Intent i = new Intent(AddActivity.this, ListLibraryActivity.class);
                                    startActivity(i);
                                        return true;
                                }
                                
                                // TODO Auto-generated method stub
                                return false;
                        }
                });
                
                //Setta l'OnClickListener per aprire una finestra di dialogo per scegliere un'immagine
                this.openCover.setOnTouchListener(new OnTouchListener() 
                {                       
                        @Override
                        public boolean onTouch(View v, MotionEvent event) 
                        {
                                if(event.getAction() == MotionEvent.ACTION_DOWN)
                                {
                                        openCover.setImageResource(R.drawable.open_click);
                                        return true;
                                }
                                else if(event.getAction() == MotionEvent.ACTION_UP)
                                {
                                        openCover.setImageResource(R.drawable.open);
                                        showCoverChooser();
                                        return true;
                                }
                                
                                // TODO Auto-generated method stub
                                return false;
                        }
                });
                
                //Setta l'OnTouchListener per salvare il nuovo libro aggiunto
                this.saveBook.setOnTouchListener(new OnTouchListener() 
                {                       
                        @Override
                        public boolean onTouch(View v, MotionEvent event) 
                        {
                                if(event.getAction() == MotionEvent.ACTION_DOWN)
                                {
                                        saveBook.setImageResource(R.drawable.save_click);
                                        return true;
                                }
                                else if(event.getAction() == MotionEvent.ACTION_UP)
                                {
                                        saveBook.setImageResource(R.drawable.save);
                                        
                                         db.open();
                                         db.addBook(selectedImagePath, title.getText().toString(), author.getText().toString(), publisher.getText().toString(),
                                                         year.getText().toString(), pages.getText().toString(), genre.getText().toString(), price.getText().toString(),
                                                         isbn.getText().toString(), storyDescription.getText().toString(), rating.getRating());
                                         
                                         Cursor c = db.getAllBooks();
                                            Toast.makeText(getApplicationContext(),
                                                        Integer.toString(c.getCount()),
                                                        Toast.LENGTH_LONG).show();
                                            
                                         db.close();
                                        
                                        return true;
                                }
                                
                                // TODO Auto-generated method stub
                                return false;
                        }
                });     
        }
        
        //Fà scegliere un'immagine
        private void showCoverChooser()
        {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
        intent.setType("image/jpeg"); 
        intent.setType("image/png");
        intent.setType("image/gif");
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.select_cover)), RESULT_LOAD_IMAGE);
    }
        
        //Apre un'immagine e la inserisce come sfondo dell'Image View cover
        @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
        {
        switch (requestCode) 
        {
            case RESULT_LOAD_IMAGE:
            if (resultCode == RESULT_OK) 
            {
                Uri selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);
                //cover.setVisibility(View.VISIBLE);
                cover.setImageURI(selectedImageUri);
            }
            break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
        
        //Ottiene il path dell'immagine scelta
        public String getPath(Uri uri) 
        {
                String[] projection = { MediaStore.Images.Media.DATA };
                Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
                int column_index = cursor
                        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
        }
}
Questa è la classe che gestisce il database:
Codice:
package it.prova.database;

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

public class ManageDB 
{       
                //I dati della tabella books, accessibili ovunque
            static class BooksData
            {  
                static final String DATABASE_NAME = "provadb";
                static final int DATABASE_VERSION = 1;
                static final String TABLE_BOOKS = "books";
                static final String ID_BOOK = "id_book";
                static final String COVER = "cover";
                static final String TITLE = "title";
                static final String AUTHOR = "author";
                static final String PUBLISHER = "publisher";
                static final String YEAR = "year";
                static final String PAGES = "pages";
                static final String GENRE = "genre";
                static final String PRICE = "price";
                static final String ISBN = "isbn";
                static final String STORY_DESCRIPTION = "storyDescription";
                static final String RATING = "rating";
            }
          
          //Lo statement SQL di creazione della tabella books
          private static final String TABLE_BOOKS_CREATE = "create table books (id_book integer primary key autoincrement, cover text, title text,"
                        + "author text, publisher text, year text, pages text, genre text, price text,"
                        + "isbn text, story_description text, rating float);";
          
          final Context context;
          DatabaseHelper DBHelper;
          SQLiteDatabase db;

          //Costruttore
          public ManageDB(Context ctx)
          {
            this.context = ctx;
            this.DBHelper = new DatabaseHelper(context);
          }

          //Estendo la classe SQLiteOpenHelper che si occupa
          //della gestione delle connessioni e della creazione del DB
          private static class DatabaseHelper extends SQLiteOpenHelper
          {    
            DatabaseHelper(Context context)
            {
              //Invoco il costruttore della classe base
              super(context, BooksData.DATABASE_NAME, null, BooksData.DATABASE_VERSION);
            }
            
            @Override
            public void onCreate(SQLiteDatabase db)
            {
              try 
              {  
                db.execSQL(TABLE_BOOKS_CREATE);
              } 
              catch (SQLException e) 
              {
                e.printStackTrace();
              }
            }
            
                @Override
                public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
                {
                        // TODO Auto-generated method stub      
                }
          }

          //Apro la connessione al DB
          public ManageDB open() throws SQLException
          {
            //Ottengo accesso al DB anche in scrittura
            this.db = DBHelper.getWritableDatabase();
            return this;
          }

          //Chiudo la connessione al DB
          public void close()
          {
                  this.DBHelper.close();
          }

          //Estrae tutti i libri
          public Cursor getAllBooks()
          {
            //Applico il metodo query senza applicare nessuna clausola WHERE
            return this.db.query(BooksData.TABLE_BOOKS, null, null, null, null, null, null);
          }

          //Estraggo un sigolo libro specificandone l'ID
          public Cursor getBook(long id_book) throws SQLException
          {
            //Applico il metodo query filtrando per ID
            Cursor mCursore = this.db.query(true, BooksData.TABLE_BOOKS, new String[] {BooksData.ID_BOOK, BooksData.TITLE, BooksData.AUTHOR}, BooksData.ID_BOOK + "=" + id_book, 
                        null, null, null, null, null);
            
            if (mCursore != null) 
            {
              mCursore.moveToFirst();
            }
            
            return mCursore;
          }

          //Aggiunge un libro nel database
          public long addBook(String cover, String title, String author, String publisher, String year, String pages, String genre, String price,
                          String isbn, String storyDescription, float rating)
          {
            //Creo una mappa di valori
            ContentValues cv = new ContentValues();
            cv.put(BooksData.COVER, cover);
        cv.put(BooksData.TITLE, title);
        cv.put(BooksData.AUTHOR, author);
        cv.put(BooksData.PUBLISHER, publisher);
        cv.put(BooksData.YEAR, year);
        cv.put(BooksData.PAGES, pages);
        cv.put(BooksData.GENRE, genre);
        cv.put(BooksData.PRICE, price);
        cv.put(BooksData.ISBN, isbn);
        cv.put(BooksData.STORY_DESCRIPTION, storyDescription);
        cv.put(BooksData.RATING, rating);
            
            //Applico il metodo insert
            return this.db.insert(BooksData.TABLE_BOOKS, null, cv);
          }
        }
Questo è il layout dell'activity:
Codice:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/frame_layout_info"
   android:layout_width="match_parent"
   android:layout_height="match_parent">

<ScrollView
   android:id="@+id/scrollView_info"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:background="@color/bg" >
    
<RelativeLayout
   android:layout_width="match_parent"
   android:layout_height="1250dp"
   android:background="@color/normal">

    <TextView
       android:id="@+id/title_textview"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_marginTop="10dp"
       android:layout_marginLeft="5dp"
       android:layout_below="@+id/cover"
       android:text="@string/title"
       android:textColor="@color/text"
       android:textSize="@dimen/text_size" />
    
    <EditText
       android:id="@+id/title_edittext"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_below="@+id/title_textview"
       android:hint="@string/title"
       android:inputType="text" />
    
    <TextView
       android:id="@+id/author_textview"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/title_textview"
       android:layout_below="@+id/title_edittext"
       android:layout_marginTop="10dp"
       android:text="@string/author" 
       android:textColor="@color/text"
       android:textSize="@dimen/text_size" />
    
    <EditText
       android:id="@+id/author_edittext"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_below="@+id/author_textview"
       android:hint="@string/author"
       android:inputType="text" />
    
    <TextView
       android:id="@+id/publisher_textview"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/author_textview"
       android:layout_below="@+id/author_edittext"
       android:layout_marginTop="10dp"
       android:text="@string/publisher" 
       android:textColor="@color/text"
       android:textSize="@dimen/text_size" />
    
    <EditText
       android:id="@+id/publisher_edittext"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_below="@+id/publisher_textview"
       android:hint="@string/publisher"
       android:inputType="text" />
    
    <TextView
       android:id="@+id/year_textview"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/publisher_textview"
       android:layout_below="@+id/publisher_edittext"
       android:layout_marginTop="10dp"
       android:text="@string/year"
       android:textColor="@color/text"
       android:textSize="@dimen/text_size" />
    
    <EditText
       android:id="@+id/year_edittext"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_below="@+id/year_textview"
       android:hint="@string/year"
       android:inputType="number" />
    
    <TextView
       android:id="@+id/pages_textview"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/year_textview"
       android:layout_below="@+id/year_edittext"
       android:layout_marginTop="10dp"
       android:text="@string/pages"
       android:textColor="@color/text"
       android:textSize="@dimen/text_size" />
    
    <EditText
       android:id="@+id/pages_edittext"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_below="@+id/pages_textview"
       android:hint="@string/pages"
       android:inputType="number" />
    
    <TextView
       android:id="@+id/genre_textview"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/year_textview"
       android:layout_below="@+id/pages_edittext"
       android:layout_marginTop="10dp"
       android:text="@string/genre"
       android:textColor="@color/text"
       android:textSize="@dimen/text_size" />
    
    <EditText
       android:id="@+id/genre_edittext"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_below="@+id/genre_textview"
       android:hint="@string/genre"
       android:inputType="text" />
    
    <TextView
       android:id="@+id/price_textview"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/genre_textview"
       android:layout_below="@+id/genre_edittext"
       android:layout_marginTop="10dp"
       android:text="@string/price"
       android:textColor="@color/text"
       android:textSize="@dimen/text_size" />
    
    <EditText
       android:id="@+id/price_edittext"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_below="@+id/price_textview"
       android:hint="@string/price"
       android:inputType="number" />
    
    <TextView
       android:id="@+id/isbn_textview"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/price_textview"
       android:layout_below="@+id/price_edittext"
       android:layout_marginTop="10dp"
       android:text="@string/isbn"
       android:textColor="@color/text"
       android:textSize="@dimen/text_size" />
    
    <EditText
       android:id="@+id/isbn_edittext"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_below="@+id/isbn_textview"
       android:hint="@string/isbn"
       android:inputType="number" />
    
    <TextView
       android:id="@+id/story_description_textview"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/isbn_textview"
       android:layout_below="@+id/isbn_edittext"
       android:layout_marginTop="10dp"
       android:text="@string/story_description"
       android:textColor="@color/text"
       android:textSize="@dimen/text_size" />
    
    <EditText
       android:id="@+id/story_description_edittext"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_below="@+id/story_description_textview"
       android:hint="@string/story_description"
       android:inputType="textMultiLine"
       android:singleLine="false"
        android:lines="5" />
    
    <TextView
       android:id="@+id/rating_textview"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/story_description_textview"
       android:layout_below="@+id/story_description_edittext"
       android:layout_marginTop="10dp"
       android:text="@string/rating"
       android:textColor="@color/text"
       android:textSize="@dimen/text_size" />
    
    <RatingBar
       android:id="@+id/rating"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignParentLeft="true"
       android:layout_below="@+id/rating_textview"
       android:layout_marginTop="10dp"
       android:numStars="5"
       android:stepSize="1.0"
       android:rating="2.0" />

    <ImageButton
       android:id="@+id/save_book"
       android:layout_width="60dp"
       android:layout_height="60dp"
       android:layout_alignParentRight="true"
       android:layout_below="@+id/rating"
       android:layout_marginRight="20dp"
       android:layout_marginTop="20dp"
       android:background="@color/normal"
       android:contentDescription="@string/save"
       android:scaleType="fitCenter"
       android:src="@drawable/save" />

    <ImageView
       android:id="@+id/cover"
       android:layout_width="200dp"
       android:layout_height="150dp"
       android:layout_alignParentLeft="true"
       android:layout_marginTop="80dp"
       android:layout_marginLeft="-45dp"
       android:contentDescription="@string/cover"
       android:scaleType="fitCenter"
       android:src="@drawable/no_cover" />

    <ImageButton
       android:id="@+id/open_cover"
       android:layout_width="40dp"
       android:layout_height="40dp"
       android:layout_alignBottom="@+id/cover"
       android:layout_marginLeft="47dp"
       android:layout_toRightOf="@+id/publisher_textview"
       android:background="@color/normal"
       android:contentDescription="@string/cover"
       android:scaleType="fitCenter"
       android:src="@drawable/open" />
    
</RelativeLayout>
        </ScrollView>
        
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:background="@color/click">

    <ImageButton
       android:id="@+id/back_add"
       android:layout_width="40dp"
       android:layout_height="40dp"
       android:scaleType="fitCenter"
       android:contentDescription="@string/back"
       android:background="@color/normal"
       android:layout_marginTop="5dp"
       android:layout_marginLeft="14dp"
       android:src="@drawable/back" />

</LinearLayout>
</FrameLayout>
 
Hai provato a fare un pò di debug???
Sono riportati errori? Quali?

Salve,
nella mia app ho bisogno che aggiunga i dati inseriti nelle edittext ecc. in un database sqlite;
non riesco a capire il motivo per cui non li aggiunga.
Potete aiutarmi? Grazie.
Questa è l'activity:
Codice:
package it.prova.database;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.Toast;

public class AddActivity extends Activity
{
        ImageButton backAdd, saveBook, openCover;
        EditText title, author, publisher, year, pages, genre, price, isbn, storyDescription;
        static final int RESULT_LOAD_IMAGE = 1;
        ImageView cover;
        RatingBar rating;
        String selectedImagePath;
        ManageDB db;
        
        //Identificatore delle preferenze dell'applicazione
    public static String MY_PREFERENCES = "MyPref";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) 
        {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.add_layout);
                
                //Creo un'istanza della classe ManageDB
                this.db = new ManageDB(this);
                
                //Ottiene il riferimento alle Image Button
                this.backAdd = (ImageButton)findViewById(R.id.back_add);
                this.saveBook = (ImageButton)findViewById(R.id.save_book);
                this.openCover = (ImageButton)findViewById(R.id.open_cover);
                
                //Ottiene il riferimento alle EditText
                this.title = (EditText)findViewById(R.id.title_edittext);
                this.author = (EditText)findViewById(R.id.author_edittext);
                this.publisher = (EditText)findViewById(R.id.publisher_edittext);
                this.year = (EditText)findViewById(R.id.year_edittext);
                this.pages = (EditText)findViewById(R.id.pages_edittext);
                this.genre = (EditText)findViewById(R.id.genre_edittext);
                this.price = (EditText)findViewById(R.id.price_edittext);
                this.storyDescription = (EditText)findViewById(R.id.story_description_edittext);
                this.isbn = (EditText)findViewById(R.id.isbn_edittext);
                
                //Ottiene il riferimento alle ImageView
                this.cover = (ImageView)findViewById(R.id.cover);
                
                //Ottiene il riferimento al RatingBar
                this.rating = (RatingBar)findViewById(R.id.rating);
                
                //Setta l'OnTouchListener per ritornare nella lista
                this.backAdd.setOnTouchListener(new OnTouchListener() 
                {                       
                        @Override
                        public boolean onTouch(View v, MotionEvent event) 
                        {
                                if(event.getAction() == MotionEvent.ACTION_DOWN)
                                {
                                        backAdd.setImageResource(R.drawable.back_click);
                                        return true;
                                }
                                else if(event.getAction() == MotionEvent.ACTION_UP)
                                {
                                        backAdd.setImageResource(R.drawable.back);
                                        Intent i = new Intent(AddActivity.this, ListLibraryActivity.class);
                                    startActivity(i);
                                        return true;
                                }
                                
                                // TODO Auto-generated method stub
                                return false;
                        }
                });
                
                //Setta l'OnClickListener per aprire una finestra di dialogo per scegliere un'immagine
                this.openCover.setOnTouchListener(new OnTouchListener() 
                {                       
                        @Override
                        public boolean onTouch(View v, MotionEvent event) 
                        {
                                if(event.getAction() == MotionEvent.ACTION_DOWN)
                                {
                                        openCover.setImageResource(R.drawable.open_click);
                                        return true;
                                }
                                else if(event.getAction() == MotionEvent.ACTION_UP)
                                {
                                        openCover.setImageResource(R.drawable.open);
                                        showCoverChooser();
                                        return true;
                                }
                                
                                // TODO Auto-generated method stub
                                return false;
                        }
                });
                
                //Setta l'OnTouchListener per salvare il nuovo libro aggiunto
                this.saveBook.setOnTouchListener(new OnTouchListener() 
                {                       
                        @Override
                        public boolean onTouch(View v, MotionEvent event) 
                        {
                                if(event.getAction() == MotionEvent.ACTION_DOWN)
                                {
                                        saveBook.setImageResource(R.drawable.save_click);
                                        return true;
                                }
                                else if(event.getAction() == MotionEvent.ACTION_UP)
                                {
                                        saveBook.setImageResource(R.drawable.save);
                                        
                                         db.open();
                                         db.addBook(selectedImagePath, title.getText().toString(), author.getText().toString(), publisher.getText().toString(),
                                                         year.getText().toString(), pages.getText().toString(), genre.getText().toString(), price.getText().toString(),
                                                         isbn.getText().toString(), storyDescription.getText().toString(), rating.getRating());
                                         
                                         Cursor c = db.getAllBooks();
                                            Toast.makeText(getApplicationContext(),
                                                        Integer.toString(c.getCount()),
                                                        Toast.LENGTH_LONG).show();
                                            
                                         db.close();
                                        
                                        return true;
                                }
                                
                                // TODO Auto-generated method stub
                                return false;
                        }
                });     
        }
        
        //Fà scegliere un'immagine
        private void showCoverChooser()
        {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
        intent.setType("image/jpeg"); 
        intent.setType("image/png");
        intent.setType("image/gif");
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.select_cover)), RESULT_LOAD_IMAGE);
    }
        
        //Apre un'immagine e la inserisce come sfondo dell'Image View cover
        @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
        {
        switch (requestCode) 
        {
            case RESULT_LOAD_IMAGE:
            if (resultCode == RESULT_OK) 
            {
                Uri selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);
                //cover.setVisibility(View.VISIBLE);
                cover.setImageURI(selectedImageUri);
            }
            break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
        
        //Ottiene il path dell'immagine scelta
        public String getPath(Uri uri) 
        {
                String[] projection = { MediaStore.Images.Media.DATA };
                Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
                int column_index = cursor
                        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
        }
}
Questa è la classe che gestisce il database:
Codice:
package it.prova.database;

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

public class ManageDB 
{       
                //I dati della tabella books, accessibili ovunque
            static class BooksData
            {  
                static final String DATABASE_NAME = "provadb";
                static final int DATABASE_VERSION = 1;
                static final String TABLE_BOOKS = "books";
                static final String ID_BOOK = "id_book";
                static final String COVER = "cover";
                static final String TITLE = "title";
                static final String AUTHOR = "author";
                static final String PUBLISHER = "publisher";
                static final String YEAR = "year";
                static final String PAGES = "pages";
                static final String GENRE = "genre";
                static final String PRICE = "price";
                static final String ISBN = "isbn";
                static final String STORY_DESCRIPTION = "storyDescription";
                static final String RATING = "rating";
            }
          
          //Lo statement SQL di creazione della tabella books
          private static final String TABLE_BOOKS_CREATE = "create table books (id_book integer primary key autoincrement, cover text, title text,"
                        + "author text, publisher text, year text, pages text, genre text, price text,"
                        + "isbn text, story_description text, rating float);";
          
          final Context context;
          DatabaseHelper DBHelper;
          SQLiteDatabase db;

          //Costruttore
          public ManageDB(Context ctx)
          {
            this.context = ctx;
            this.DBHelper = new DatabaseHelper(context);
          }

          //Estendo la classe SQLiteOpenHelper che si occupa
          //della gestione delle connessioni e della creazione del DB
          private static class DatabaseHelper extends SQLiteOpenHelper
          {    
            DatabaseHelper(Context context)
            {
              //Invoco il costruttore della classe base
              super(context, BooksData.DATABASE_NAME, null, BooksData.DATABASE_VERSION);
            }
            
            @Override
            public void onCreate(SQLiteDatabase db)
            {
              try 
              {  
                db.execSQL(TABLE_BOOKS_CREATE);
              } 
              catch (SQLException e) 
              {
                e.printStackTrace();
              }
            }
            
                @Override
                public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
                {
                        // TODO Auto-generated method stub      
                }
          }

          //Apro la connessione al DB
          public ManageDB open() throws SQLException
          {
            //Ottengo accesso al DB anche in scrittura
            this.db = DBHelper.getWritableDatabase();
            return this;
          }

          //Chiudo la connessione al DB
          public void close()
          {
                  this.DBHelper.close();
          }

          //Estrae tutti i libri
          public Cursor getAllBooks()
          {
            //Applico il metodo query senza applicare nessuna clausola WHERE
            return this.db.query(BooksData.TABLE_BOOKS, null, null, null, null, null, null);
          }

          //Estraggo un sigolo libro specificandone l'ID
          public Cursor getBook(long id_book) throws SQLException
          {
            //Applico il metodo query filtrando per ID
            Cursor mCursore = this.db.query(true, BooksData.TABLE_BOOKS, new String[] {BooksData.ID_BOOK, BooksData.TITLE, BooksData.AUTHOR}, BooksData.ID_BOOK + "=" + id_book, 
                        null, null, null, null, null);
            
            if (mCursore != null) 
            {
              mCursore.moveToFirst();
            }
            
            return mCursore;
          }

          //Aggiunge un libro nel database
          public long addBook(String cover, String title, String author, String publisher, String year, String pages, String genre, String price,
                          String isbn, String storyDescription, float rating)
          {
            //Creo una mappa di valori
            ContentValues cv = new ContentValues();
            cv.put(BooksData.COVER, cover);
        cv.put(BooksData.TITLE, title);
        cv.put(BooksData.AUTHOR, author);
        cv.put(BooksData.PUBLISHER, publisher);
        cv.put(BooksData.YEAR, year);
        cv.put(BooksData.PAGES, pages);
        cv.put(BooksData.GENRE, genre);
        cv.put(BooksData.PRICE, price);
        cv.put(BooksData.ISBN, isbn);
        cv.put(BooksData.STORY_DESCRIPTION, storyDescription);
        cv.put(BooksData.RATING, rating);
            
            //Applico il metodo insert
            return this.db.insert(BooksData.TABLE_BOOKS, null, cv);
          }
        }
Questo è il layout dell'activity:
Codice:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/frame_layout_info"
   android:layout_width="match_parent"
   android:layout_height="match_parent">

<ScrollView
   android:id="@+id/scrollView_info"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:background="@color/bg" >
    
<RelativeLayout
   android:layout_width="match_parent"
   android:layout_height="1250dp"
   android:background="@color/normal">

    <TextView
       android:id="@+id/title_textview"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_marginTop="10dp"
       android:layout_marginLeft="5dp"
       android:layout_below="@+id/cover"
       android:text="@string/title"
       android:textColor="@color/text"
       android:textSize="@dimen/text_size" />
    
    <EditText
       android:id="@+id/title_edittext"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_below="@+id/title_textview"
       android:hint="@string/title"
       android:inputType="text" />
    
    <TextView
       android:id="@+id/author_textview"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/title_textview"
       android:layout_below="@+id/title_edittext"
       android:layout_marginTop="10dp"
       android:text="@string/author" 
       android:textColor="@color/text"
       android:textSize="@dimen/text_size" />
    
    <EditText
       android:id="@+id/author_edittext"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_below="@+id/author_textview"
       android:hint="@string/author"
       android:inputType="text" />
    
    <TextView
       android:id="@+id/publisher_textview"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/author_textview"
       android:layout_below="@+id/author_edittext"
       android:layout_marginTop="10dp"
       android:text="@string/publisher" 
       android:textColor="@color/text"
       android:textSize="@dimen/text_size" />
    
    <EditText
       android:id="@+id/publisher_edittext"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_below="@+id/publisher_textview"
       android:hint="@string/publisher"
       android:inputType="text" />
    
    <TextView
       android:id="@+id/year_textview"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/publisher_textview"
       android:layout_below="@+id/publisher_edittext"
       android:layout_marginTop="10dp"
       android:text="@string/year"
       android:textColor="@color/text"
       android:textSize="@dimen/text_size" />
    
    <EditText
       android:id="@+id/year_edittext"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_below="@+id/year_textview"
       android:hint="@string/year"
       android:inputType="number" />
    
    <TextView
       android:id="@+id/pages_textview"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/year_textview"
       android:layout_below="@+id/year_edittext"
       android:layout_marginTop="10dp"
       android:text="@string/pages"
       android:textColor="@color/text"
       android:textSize="@dimen/text_size" />
    
    <EditText
       android:id="@+id/pages_edittext"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_below="@+id/pages_textview"
       android:hint="@string/pages"
       android:inputType="number" />
    
    <TextView
       android:id="@+id/genre_textview"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/year_textview"
       android:layout_below="@+id/pages_edittext"
       android:layout_marginTop="10dp"
       android:text="@string/genre"
       android:textColor="@color/text"
       android:textSize="@dimen/text_size" />
    
    <EditText
       android:id="@+id/genre_edittext"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_below="@+id/genre_textview"
       android:hint="@string/genre"
       android:inputType="text" />
    
    <TextView
       android:id="@+id/price_textview"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/genre_textview"
       android:layout_below="@+id/genre_edittext"
       android:layout_marginTop="10dp"
       android:text="@string/price"
       android:textColor="@color/text"
       android:textSize="@dimen/text_size" />
    
    <EditText
       android:id="@+id/price_edittext"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_below="@+id/price_textview"
       android:hint="@string/price"
       android:inputType="number" />
    
    <TextView
       android:id="@+id/isbn_textview"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/price_textview"
       android:layout_below="@+id/price_edittext"
       android:layout_marginTop="10dp"
       android:text="@string/isbn"
       android:textColor="@color/text"
       android:textSize="@dimen/text_size" />
    
    <EditText
       android:id="@+id/isbn_edittext"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_below="@+id/isbn_textview"
       android:hint="@string/isbn"
       android:inputType="number" />
    
    <TextView
       android:id="@+id/story_description_textview"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/isbn_textview"
       android:layout_below="@+id/isbn_edittext"
       android:layout_marginTop="10dp"
       android:text="@string/story_description"
       android:textColor="@color/text"
       android:textSize="@dimen/text_size" />
    
    <EditText
       android:id="@+id/story_description_edittext"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_below="@+id/story_description_textview"
       android:hint="@string/story_description"
       android:inputType="textMultiLine"
       android:singleLine="false"
        android:lines="5" />
    
    <TextView
       android:id="@+id/rating_textview"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/story_description_textview"
       android:layout_below="@+id/story_description_edittext"
       android:layout_marginTop="10dp"
       android:text="@string/rating"
       android:textColor="@color/text"
       android:textSize="@dimen/text_size" />
    
    <RatingBar
       android:id="@+id/rating"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignParentLeft="true"
       android:layout_below="@+id/rating_textview"
       android:layout_marginTop="10dp"
       android:numStars="5"
       android:stepSize="1.0"
       android:rating="2.0" />

    <ImageButton
       android:id="@+id/save_book"
       android:layout_width="60dp"
       android:layout_height="60dp"
       android:layout_alignParentRight="true"
       android:layout_below="@+id/rating"
       android:layout_marginRight="20dp"
       android:layout_marginTop="20dp"
       android:background="@color/normal"
       android:contentDescription="@string/save"
       android:scaleType="fitCenter"
       android:src="@drawable/save" />

    <ImageView
       android:id="@+id/cover"
       android:layout_width="200dp"
       android:layout_height="150dp"
       android:layout_alignParentLeft="true"
       android:layout_marginTop="80dp"
       android:layout_marginLeft="-45dp"
       android:contentDescription="@string/cover"
       android:scaleType="fitCenter"
       android:src="@drawable/no_cover" />

    <ImageButton
       android:id="@+id/open_cover"
       android:layout_width="40dp"
       android:layout_height="40dp"
       android:layout_alignBottom="@+id/cover"
       android:layout_marginLeft="47dp"
       android:layout_toRightOf="@+id/publisher_textview"
       android:background="@color/normal"
       android:contentDescription="@string/cover"
       android:scaleType="fitCenter"
       android:src="@drawable/open" />
    
</RelativeLayout>
        </ScrollView>
        
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:background="@color/click">

    <ImageButton
       android:id="@+id/back_add"
       android:layout_width="40dp"
       android:layout_height="40dp"
       android:scaleType="fitCenter"
       android:contentDescription="@string/back"
       android:background="@color/normal"
       android:layout_marginTop="5dp"
       android:layout_marginLeft="14dp"
       android:src="@drawable/back" />

</LinearLayout>
</FrameLayout>
 

Discussioni simili