Where to put own properties file in an android project created with Android Studio?
By default assets folder is placed in src/main/assets
, if it does not exists create it.
Then you can access the file using something like this:
getBaseContext().getAssets().open("app.properties")
You can find more info about Gradle Android project structure here.
Create a subfolder in your main folder and name it assets. Place all your .properties files in this(assets) folder.
src->main->assets->mydetails.properties
You can access it using AssetManager class
public class MainActivity extends ActionBarActivity {
TextView textView;
private PropertyReader propertyReader;
private Context context;
private Properties properties;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
propertyReader = new PropertyReader(context);
properties = propertyReader.getMyProperties("mydetails.properties");
textView = (TextView)findViewById(R.id.text);
textView.setText(properties.getProperty("Name"));
Toast.makeText(context, properties.getProperty("Designation"), Toast.LENGTH_LONG).show();
}
}
public class PropertyReader {
private Context context;
private Properties properties;
public PropertyReader(Context context){
this.context=context;
properties = new Properties();
}
public Properties getMyProperties(String file){
try{
AssetManager assetManager = context.getAssets();
InputStream inputStream = assetManager.open(file);
properties.load(inputStream);
}catch (Exception e){
System.out.print(e.getMessage());
}
return properties;
}
}
You can create your asset subfolder in your main folder and then insert the .properties file in it.
Then, create a class to open and read the file, for example:
public class PropertiesReader {
private Context context;
private Properties properties;
public PropertiesReader(Context context) {
this.context = context;
//creates a new object ‘Properties’
properties = new Properties();
public Properties getProperties(String FileName) {
try {
//access to the folder ‘assets’
AssetManager am = context.getAssets();
//opening the file
InputStream inputStream = am.open(FileName);
//loading of the properties
properties.load(inputStream);
}
catch (IOException e) {
Log.e("PropertiesReader",e.toString());
}
}
return properties;
}
}
For more information, see http://pillsfromtheweb.blogspot.it/2014/09/properties-file-in-android.html