I created my database in my android application, but now I have to pre-populate it with some data. The problem is that it have a lot of data to put in the database. Is there some way to pre-populate the database from a file .txt or from a external file .db?
You can attach data to your application (or download it from www) just as scv files, then parse them and insert in OnCreate method of your db helper.
public void onCreate(SQLiteDatabase database) {
// create database file
database.execSQL(DB_CREATE);
// load data
AssetManager assetManager = context.getAssets();
try {
InputStream inputStream = assetManager.open("radars_test.csv");
InputStreamReader streamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(streamReader);
String line;
String[] values;
while ((line = bufferedReader.readLine()) != null) {
values = line.split(";");
String speedLimit = (line.length() == 3 ? values[2] : "0");
String insertCommand = String
.format("insert into geofences(longitude, latitude, speed_limit, type, radius, description) values(\"%s\", \"%s\", %s, 0, 200, \"%s\")",
values[0], values[1], speedLimit, values[3]);
database.execSQL(insertCommand);
}
} catch (IOException e) {
Log.e("TBCAE", "Failed to open data input file");
e.printStackTrace();
}
}
.csv file must be placed in assets directory
Great post here. I had it bookmarked for a long time.
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
I think it will answer all your problems.
You don't say what format you actually have but yes, very possible. Use a destkop SQLite editor and import a CSV file (for example). Most SQLite editors support this.
Then simply copy the .db3 file to your project.
I use this one:
http://sqlitebrowser.sourceforge.net/
Also, read this http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
The best way is to create the database on your own using a manager like SQLite Manager for Firefox. This manager lets you import Excel files (that are actually CSV) with the data to the database. After that you should store your database in the raw folder of your application. Then, you should create a DataAdapter to retrieve the data using cursors. If you want more details, don't hesitate to ask. Good luck.
Related
I don't know this is a duplicate question or not, but i tried to search similar question according to this.
I want to access the file that located outside /res folder programatically.
I already know if we want to access /res folder, then we just call it's id like getString(), getDrawable() etc.
But in my case, I want to access anim_empty.json programatically. How to do that?
Try following method for accessing JSON data:
public static String loadJSONFromAsset(Context mContext, String fileName) {
String json;
try {
InputStream is = mContext.getAssets().open(fileName);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
Modify the method according to your usage..
In the truth, i just wanted to call the Lottie animation files, i thought that i need to write script like the answer above but all i need is just these (Getting Started With Animations in Android Using Lottie — Kotlin and enter link description here):
lottieAnimationView = findViewById(R.id.empty_hstanim);
lottieAnimationView.setAnimation("anim_empty.json");
lottieAnimationView.playAnimation();
Thanks for the kind answer anyway!
Is it possible to load strings.xml from sd card instead of application res/values/... Search on the web but didn't find any tutorials. My thought is download the xml to sd card then save the strings element to an array.
public void stringsxml(){
File file = new File(Environment.getExternalStorageDirectory()
+ ".strings.xml");
StringBuilder contents = new StringBuilder();
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(file));
try {
String line = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
String data= contents.toString();
}
Well, actually it is semi-possible, but you have to create a derivate LayoutInflater which will replace string codes with thus read strings.
I have documented my attempts and failings together with initial implementation here.
Summary: simple strings work, string arrays do not
No, this is not possible. Check Android decoumentation about resources:
The Android SDK tools compile your application's resources into the application binary at build time. To use a resource, you must install it correctly in the source tree (inside your project's res/ directory) and build your application.
Resources are built-in into the application binary and you can't read them from a file.
I'm trying to access a file that I put into the res/raw folder in my Android project. I am using this .CSV file to use with the CsvJdbc jar which allows me to query it as if it where a database. I have seen many examples of grabbing it with an InputStream, for example...
InputStream raw;
raw = getResources().openRawResource(R.raw.vehicles);
But I need to grab the file by creating a connection. i.e.
Connection conn = DriverManager.getConnection("jdbc:relique:csv:PathToFolderWhereCsvFileIsGoesHere");
Here is the full code.
String[] holder = null;
try
{
// load the driver into memory
Class.forName("org.relique.jdbc.csv.CsvDriver");
// create a connection. The first command line parameter is assumed to
// be the directory in which the .csv files are held
Connection conn = DriverManager.getConnection("jdbc:relique:csv:PathToFolderWhereCsvFileIsGoesHere");
// create a Statement object to execute the query with
Statement stmt = conn.createStatement();
// Select the ID and NAME columns from sample.csv
ResultSet results = stmt.executeQuery("SELECT model FROM vehicles where id = 200");
// dump out the results
for(int i=0; i < results.getFetchSize(); i++){
holder[i] = results.getString("model");
}
// clean up
results.close();
stmt.close();
conn.close();
}
catch(Exception e)
{
e.printStackTrace();
}
One solution is to write a class implementing the CsvJdbc org.relique.io.TableReader interface that returns a java.io.Reader for each of your tables. CsvJdbc then reads from this Reader object instead of from a file.
There is an example of this on the CsvJdbc web page http://csvjdbc.sourceforge.net
I have couple of dozen pieces of data that I need to save and load on start of the application. They are int, String, long , array data types. I am confused that there seems to be so many ways to do this. It seems each variation has different methods. The some of the data gets modified while the app runs. Lets say I have the following
int WifiOn="1";
private long Lasttime="00/00/00";
private String UserId="12345678";
private String URLResource[]= {"A","B","C");
//I open file...
FileOutputStream fos = openFileOutput("userPref.dat", Context.MODE_PRIVATE);
what do I do next with my four data types to save them out to internal storage?
And then what is the method to load them?
Apart from the SharedPreferences and SQLite databases that Dheeresh Singh mentions you can also use Serialization since you only use simple datatypes.
How to write data to a file with serialization:
//create an ObjectOutputStream around your (file) OutputStream
ObjectOutputStream oos = new ObjectOutputStream(fos);
//The OOS has methods like writeFloat(), writeInt() etc.
oos.writeInt(myInt);
oos.writeInt(myOtherInt);
//You can also write objects that implements Serializable:
oos.writeObject(myIntArray);
//Finally close the stream:
oos.flush();
oos.close();
How to read data from a file with serialization:
//Create an ObjectInputStream around your (file) InputStream
ObjectInputStream ois = new ObjectInputStream(fis);
//This stream has read-methods corresponding to the write-methods in the OOS, the objects are read in the order they were written:
myInt = ois.readInt();
myOtherInt = ois.readInt();
//The readObject() returns an Object, but you know it is the same type that you wrote, so just cast it and ignore any warnings:
myIntArray = (int[]) ois.readObject();
//As always, close the stream:
ois.close();
On a side note, consider wrapping your In/OutStream in a BufferedInput/OutputStream to squeeze out some extra read/write performance.
id data is limited then can use shared preference and if data is much can use SQLite database
dozen pieces of data
Better to use SQLite database which is easy and efficient also for your need
see link for how to use that
as per http://developer.android.com/guide/topics/data/data-storage.html
Your data storage options are the following:
Shared Preferences
Store private primitive data in key-value pairs.
Internal Storage
Store private data on the device memory.
External Storage
Store public data on the shared external storage.
SQLite Databases
Store structured data in a private database.
Network Connection
Store data on the web with your own network server.
if all the data is formatted the exact same way, you should probably use JSON, in a function you can create the objects and then write them into your file.
public bool writeToFile(int wifiOn, long lastTime, String userId, String [] urlResources) {
JSONObject toStore = new JSONObject();
FileOutputStream fos = openFileOutput("userPref.dat", Context.MODE_PRIVATE);
toStore.put("wifiOn", wifiOn);
toStore.put("lastTime", lastTime);
toStore.put("userId", userId);
toStore.put("urlResources", urlResources);
try {
fos.write(toStore.toString().getBytes());
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
I'm trying to develop a small application, where I was given a JSON file, and I have to extract data from it. As I understood a JSON object takes a string argument, thus I'm trying to access a file and write the data from it to a string.
I've placed that file in a "JSON file" folder, and when I try to read the file, it throws me a file not found exception.
I've tried several ways to find a path to that file, but every attempt was for vain.
It might be that I'm extracting the path wrong, or might be something else, please help me.
Thanks in advance.
here is the code of finding the path:
try
{
path = Environment.getRootDirectory().getCanonicalPath();
}
catch (IOException e)
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
File jFile = new File(path + /"JSON file/gallery.json");
here is the code for reading from a file :
String str ="";
try
{
BufferedReader in = new BufferedReader(new FileReader(jFile));
while ((str += in.readLine()) != null)
{
}
in.close();
}
catch (IOException e)
{
e.getMessage();
}
return str;
Here more specification:
I want to take the data from the file in order to do that : JSONObject(jString).
when I extract the path of json file I create a file with the path and pass it to the function that reads from the file, and there it throws me a file not found exception, when I try to read from it.
The file does exists in the folder (even visually - I've tried to attach an image but the site won't let me, because I'm new user)
I've tried to open the file through the windows address bar by typing the path like that:
C:\Users\Marat\IdeaProjects\MyTask\JSON file\gallery.json and it opens it.
if you store it in the assets folder you can access it by using
InputStream is = context.getResources().getAssets().open("sample.json");
You can then convert it to a String
public static String inputStreamAsString(InputStream stream)
throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
}
EDIT
You need to put the file in the device, if it is on your computer, it is not accessible from your device. There are some ways to do that, and one of them is to put it in the res/ dir of your application. Please refer to the documentation to see how to do that.
Debug it. I'm pretty sure it will be very easy to find. To start with, look for the following:
Print the path before you create the file, e.g. Log.d("SomeTag", path + "/JSON file/gallery.json")
Observe the full exception details. Maybe there is another problem.
Explore the folders and see if the file exists (in eclipse: window -> show view -> other -> android -> file explorer.
You will probably observe the problem and be able to fix it. If not, post here a question with more details, including the results of those trials.
BTW, GetgetRootDirectory() returns the root directory of android, that's not what you want (you don't have RW permissions there) you probably want to get the applcation directory, you can see how to get it here, in the question I asked a few month ago. But since you didn't give us those details, it will be hard to help you more then that.