I just started to use Android Studio. I don't know where to put my own properties file since there is no assets folder in the project structure.
The posted snippet works fine in eclipse, but it doesn't in Android Studio.
Code:
Properties prop = new Properties();
try {
//load a properties file
prop.load(new FileInputStream("app.properties"));
//get the property value and print it out
System.out.println(prop.getProperty("server_address"));
} catch (IOException ex) {
ex.printStackTrace();
}
Question 1: Where to put my own properties files in Android Studio (v0.5.8)?
Question 2: How can I access them?
You can create this file manually in project root directory, near other ". properties" files.
The Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string.
Android Studio stores the projects by default in the home folder of the user under AndroidStudioProjects. The main directory contains configuration files for Android Studio and the Gradle build files.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With