Search code examples
androidlibgdxsharedpreferencespreferencesfile-handling

LibGDX - Cannot find Preferences location in Android Device


I am learning preferences using LibGDX. I can run the following code sucessfully both in Windows and Android Device. The file "MyDemo" is stored in my C: drive user directory. It is prefect. I can run the code in Android device sucessfully as well. However, I can't find the file "MyDemo". There is nothing in Android/data/...

package com.hkprogram.mydemo;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class MyDemo implements ApplicationListener {

    private SpriteBatch batch;
    private BitmapFont font1;
    int screenWidth, screenHeight;

    public Preferences prefs;
    String name;

    @Override
    public void create() {

        batch = new SpriteBatch();    
        font1 = new BitmapFont();
        font1.setColor(Color.BLACK);
        font1.setScale(5);
        screenWidth=Gdx.graphics.getWidth();
        screenHeight=Gdx.graphics.getHeight();

        Preferences prefs = Gdx.app.getPreferences("MyDemo");
        prefs.putString("Name", "Peter");
        prefs.flush();

        prefs = Gdx.app.getPreferences("MyDemo");
        name=prefs.getString("Name","no name stored");
        System.out.println("Name="+name);       
    }   

    @Override
    public void dispose() {
    }
    @Override
    public void pause() {       
    }
    @Override
    public void render() {
         Gdx.gl.glClearColor(159/255.0f,220/255.0f,235/255.0f,0xff/255.0f);
         Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);       
         batch.begin();
         font1.draw(batch, name, screenWidth/2, screenHeight/2);
         batch.end();
    }
    @Override
    public void resize(int arg0, int arg1) {        
    }
    @Override
    public void resume() {      
    }
}

Solution

  • You can get the path where you have MyDemo doing this :

    File MyDemoFile = getDatabasePath("MyDemo.txt"); //choose your extension
    if (MyDemoFile != null){
    Log.d("Absolute path : ", MyDemoFile.getAbsolutePath());
    }