1

I have been attempting to view the SQlite database associated with my app using the DDMS method and SQLite manager etc.

However, It is not possible to me to view the data using an emulator as my app requires bluetooth and it is not supported by an emulator

How do I view the database from my app, not using the emulator?

Edit, Current code for the creation of the Database:

package com.example.multapply;

public class DatabaseHelper extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 3;

    // Database Name
    private static final String DATABASE_NAME = "MultapplyDatabase";

    // Contacts table name
    private static final String TABLE_SCORE = "scores";

    // Contacts Table Columns names
    private static final String COL_NAME = "name";
    private static final String COL_SCORE = "score";
    private static final String COL_DATE = "date";



    /**
     * Constructor
     * @param context
     */
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }


    /**
     * Method that creates the database
     */
    @Override
    public void onCreate(SQLiteDatabase db) {

        //NOTE: may need to alter the below to take out everything after INTEGER
        String CREATE_TABLE_SCORE = "CREATE TABLE " + TABLE_SCORE + "("
                + COL_NAME + " STRING PRIMARY KEY," + COL_SCORE + " INTEGER," + COL_DATE + " LONG" + ")";
        db.execSQL(CREATE_TABLE_SCORE);


    }

Adding to the database:

/**
             * CRUD Operations
             * */
            // Inserting Contacts
            Log.d("Insert: ", "Inserting ..");


            db.addScore(new Score(UserName.getUserName(), score, System.currentTimeMillis() )); 

Edit (getting following errors):

   07-14 20:10:07.970: E/mypck(12270): /data/data/com.example.multapply/databases/MultapplyDatabase.db: open failed: ENOENT (No such file or directory)
07-14 20:10:07.970: E/mypck(12270): java.io.FileNotFoundException: /data/data/com.example.multapply/databases/MultapplyDatabase.db: open failed: ENOENT (No such file or directory)
07-14 20:10:07.970: E/mypck(12270):     at libcore.io.IoBridge.open(IoBridge.java:409)
07-14 20:10:07.970: E/mypck(12270):     at java.io.FileInputStream.<init>(FileInputStream.java:78)
07-14 20:10:07.970: E/mypck(12270):     at com.example.multapply.ExportDatabaseFileTask.copyFile(ExportDatabaseFileTask.java:71)
07-14 20:10:07.970: E/mypck(12270):     at com.example.multapply.ExportDatabaseFileTask.doInBackground(ExportDatabaseFileTask.java:49)

Error 2:

07-14 20:17:15.026: E/DatabaseUtils(814): Writing exception to parcel 07-14 20:17:15.026: E/DatabaseUtils(814): java.lang.SecurityException: Permission Denial: get/set setting for user asks to run as user -2 but is calling from user 0; this requires android.permission.INTERACT_ACROSS_USERS_FULL 07-14 20:17:15.026: E/DatabaseUtils(814): at com.android.server.am.ActivityManagerService.handleIncomingUser(ActivityManagerService.java:14608)

Note: I have already added android.permission.INTERACT_ACROSS_USERS_FULL to the manifest but am still getting the error.

Edit 3 (full class):

package com.example.multapply;

//Importing resources
import java.util.Date;
import java.util.List;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Class holding the activity that has the 10 random sums for the user to answer
 * @author Ross
 * 
 */
public class RandomTest extends Activity implements View.OnClickListener {
    // declare vars
    TextView text;
    EditText answer;
    Button submit;
    int random1;
    int random2;
    String[] question = new String[10];
    int correctAnswer[] = new int[10];
    int[] results = new int[10];
    int score = 0;
    int questionNumber = 1;
    MediaPlayer correctNoise;
    MediaPlayer incorrectNoise;
    ImageView imageRandom;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.test);

        // initialising variables
        initialiseVars();

        // set up random
        setUpRandom();

        // Set text view equal to question in array
        text.setText(question[questionNumber - 1]);

        // set on click listener for the submit button
        submit.setOnClickListener(this);

        // updateQuestion
        updateQuestion();

    }

    /**
     * Method that initialises variables
     */
    public void initialiseVars() {

        correctNoise = MediaPlayer.create(RandomTest.this, R.raw.correctnoise);
        incorrectNoise = MediaPlayer.create(RandomTest.this, R.raw.incorrectnoise);
        text = (TextView) findViewById(R.id.tvTopRandomTest);
        answer = (EditText) findViewById(R.id.etEnterAnswerRandomTest);
        submit = (Button) findViewById(R.id.btnSubmitRandomTest);
        imageRandom= (ImageView) findViewById(R.id.imageViewRandomTest);

    }

    /**
     * Method that creates the random sum for user to answer
     */
    public void setUpRandom() {

        // setting up new random
        Random random = new Random();

        // Generating random number between 1 and 12
        random1 = random.nextInt(12) + 1;
        // Generating another random number between 1 and 12
        random2 = random.nextInt(12) + 1;
        // Creating random question String
        question[questionNumber - 1] = random1 + " x " + random2 + " = ";
        // Creating correct answer to question
        correctAnswer[questionNumber - 1] = random1 * random2; 

    }

    /**
     * Method that updates question after each click
     */
    public void updateQuestion() {

        // updating question after each click
        setUpRandom();
        text.setText(question[questionNumber - 1]);
        answer.setText("");

    }

    public void onClick(View v) {

        // sets text view equal to what is entered in editText
        final String entry = answer.getText().toString();
        // convert from string value to int
        int a = Integer.parseInt(entry); //

        // setting the user answer equal to the correct part of results array
        results[questionNumber - 1] = a;

        // If user answer is equal to correct answer then increase score
        if (a == correctAnswer[questionNumber - 1]) {
            score++;
            correctNoise.start();
            imageRandom.setImageResource(R.drawable.thumbsup);
        }else{

            incorrectNoise.start();
            imageRandom.setImageResource(R.drawable.thumbsdown);

        }

        // if question number is under 10
        if (questionNumber < 10) {
            // updates question number
            questionNumber++;
            // called after an answer is given
            updateQuestion();

        } else {

            //Attempting to add the score to the database from here

            DatabaseHelper db = new DatabaseHelper(this);



            // Passing values to the results activity
            Intent intent = new Intent(this, RandomTestResults.class);
            intent.putExtra("results", results);
            intent.putExtra("Questions", question);
            intent.putExtra("CorrectAnswer", correctAnswer);
            intent.putExtra("score", score);
            // Start Activity
            this.startActivity(intent);

            /**
             * CRUD Operations
             * */
            // Inserting Contacts
            Log.d("Insert: ", "Inserting ..");

            db.addScore(new Score(UserName.getUserName(), score, System.currentTimeMillis() ));

            //attempting to export the file to the sd card
            ExportDatabaseFileTask task = new ExportDatabaseFileTask();
            task.execute();


            // Reading all contacts
            Log.d("Reading: ", "Reading all contacts..");
            List<Score> scores = db.getAllScores();

            for (Score s : scores) {
                String log = "Name: " + s.getName() + " ,Score: " + s.getScore() + "Date: " + s.getDate();
                // Writing Contacts to log
                Log.d("Name: ", log);
            }
        }



        }





    }
RYJava2014
  • 81
  • 3
  • 9

2 Answers2

0

I know two possible ways:

1 - Use your own app to make a copy of db file to the sdcard, where it is visible.

//Get your database file
File database = context.getDatabasePath("dbName.db");
//Get your sdcard location
File extStore = Environment.getExternalStorageDirectory();
//Copy sample
file = new File(extStore, "dbName.db");
file.createNewFile();
FileChannel inChannel = new FileInputStream(database).getChannel();
FileChannel outChannel = new FileOutputStream(file).getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);

2 - Root your device and give permission to the entire path to you database, in this way you can even pull it by Eclipse.

chmod 777 {all paths your need, ussualy /data/data/your.package/database recusivally}
Pozzo Apps
  • 1,859
  • 2
  • 22
  • 32
  • Can you please see my edit to the question. I am unsure how to implement what you are suggesting with my current code. thanks – RYJava2014 Jul 14 '14 at 17:10
  • This code actually is not related with helper class.. but something like an "export" event. – Pozzo Apps Jul 14 '14 at 17:20
  • is the solution i am looking for similar to this? http://stackoverflow.com/questions/2814213/making-a-database-backup-to-sdcard-on-android – RYJava2014 Jul 14 '14 at 17:54
  • Yeah, that's exactly the first option I gave, but a little more dirt, are your getting trouble to build it? – Pozzo Apps Jul 14 '14 at 17:56
  • Yes a little bit, Do i need to create an instance of the class in order to use it? I am a bit confused – RYJava2014 Jul 14 '14 at 18:05
  • This implementation is completely separated from anything you did for you Database, the only thing you need is the database name, once you have the database name you will copy the file as a common copy in Java, as you are manipulating an usual file and not the database (because SQLite database is single file). Needs to be clear that you are not changing the database, only making a copy of it to have access out of your app. – Pozzo Apps Jul 14 '14 at 18:09
  • Thank you! But how do i actually call the class, i.e. where do I instantiate ExportDatabaseFileTask within my application? – RYJava2014 Jul 14 '14 at 18:12
  • It should be as simple as a button, like "export" or "backup". – Pozzo Apps Jul 14 '14 at 18:15
  • Thanks, please see my edit at the bottom, could i call the class here? As, within my application, this is where I add the data into my database – RYJava2014 Jul 14 '14 at 18:20
  • You can do wherever you prefer, but doing this way may be very expensive depending on how much time it runs. – Pozzo Apps Jul 14 '14 at 18:39
  • where would the file then be saved? I.e. where would i find it in DDMS? Im just realising I dont think I have an SD card lol – RYJava2014 Jul 14 '14 at 18:48
  • Hehe, dont worry, even if you dont have an SdCard your device will fake one, it not always the same location, but usually it will put a shortcut on "/sdcard", it is the same place where shows to you when you access by an explorer app like "windows explorer". – Pozzo Apps Jul 14 '14 at 18:51
  • Thank you, I really appreciate you help. I implemented the code where I said I would but cannot see the file in teh SDcard folder in DDMS. I have added the error i am recieveing in my edit. Can you please have a look at it as I do not know how to solve – RYJava2014 Jul 14 '14 at 19:08
  • It is saying your database is not created yet... make sure your db name is correct and that you have already used it (to pass in onCreate). – Pozzo Apps Jul 14 '14 at 19:22
  • Thanks, I have sorted this error i think but am now getting another (error 2 in edit). This is really fustrating as I need this to work asap lol – RYJava2014 Jul 14 '14 at 19:32
  • never seen that error before, do you have WRITE_EXTERNAL_STORAGE permission? – Pozzo Apps Jul 14 '14 at 19:53
  • Maybe this? http://stackoverflow.com/questions/20578474/permission-denial-this-requires-android-permission-interact-across-users-full – Pozzo Apps Jul 14 '14 at 20:23
  • Yeah i found this also but it doesnt provide a solution, maybe the error is due to how I am instantiating the class etc? – RYJava2014 Jul 14 '14 at 20:26
  • I had never seen this error, so it is hard to say to you what it may be, it was not suppose to be any complex code, try posting your full code in a new question. – Pozzo Apps Jul 14 '14 at 20:28
  • I will add my full code of the class im invoking in as an edit! :) The other class will be the same! – RYJava2014 Jul 14 '14 at 20:34
0

Rename the database of your SQLiteOpenHelper to something like /mnt/sdcard/myapp.db. Then you will be creating a db there, that's also accessible from somewhere else

dumazy
  • 13,857
  • 12
  • 66
  • 113