I got an error when I try to load two files.
My question is how to load two json file into realm.
The following is loading json file:
private void loadJsonFromStream() throws IOException {
InputStream stream = getAssets().open("school.json");
realm.beginTransaction();
try {
realm.createAllFromJson(School.class, stream);
realm.commitTransaction();
} catch (IOException e) {
// Remember to cancel the transaction if anything goes wrong.
realm.cancelTransaction();
} finally {
if (stream != null) {
stream.close();
}
}
}
The following is loading the setting Setting file.
private void loadJsonSettingFromStream() throws IOException {
InputStream streamSetting = getAssets().open("setting.json");
realm.beginTransaction();
try {
realm.createAllFromJson(Setting.class, streamSetting);
realm.commitTransaction();
} catch (IOException e) {
// Remember to cancel the transaction if anything goes wrong.
realm.cancelTransaction();
} finally {
if (streamSetting != null) {
streamSetting.close();
}
}
"Expected a boolean but was NUMBER"
I guess you use 0 and 1 to express boolean value instead of "true" and "false" strings in the json files.
Change the stucture of the pojo or the json. If those aren't options, you can easily write a custom parser to map integers to boolean.
Related
How can I list all files, recursively in DropBox folder?
I tried code below but returns no result:
result = dbxClient.files().search("", "*");
And this returns files in path, not subfolders:
result = dbxClient.files().listFolder(path);
You can get a ListFolderBuilder from listFolderBuilder and use the withRecursive option to list out sub-items as well.
Be sure to check ListFolderResult.hasMore to see if you should call back to listFolderContinue to get more results though.
You can check this link, navigate to inner class 'FolderScanTask'. It contains working code for Android:
https://github.com/ControlX/Android-Dropbox-UploadImage-To-SpecificFolder-By-FolderSelection/blob/master/app/src/main/java/io/github/controlx/dbxdemo/MainActivity.java
This is work in progress, here I'm just making an ArrayList for parent folders, has more logic as suggested by Greg is already there you just need to fill in that.
Code Snippet for the same:
String path = "";
DbxClientV2 dbxClient = DropboxClient.getClient(ACCESS_TOKEN);
TreeMap<String, Metadata> children = new TreeMap<String, Metadata>();
try {
try {
result = dbxClient.files()
.listFolder(path);
} catch (ListFolderErrorException ex) {
ex.printStackTrace();
}
List<Metadata> list = result.getEntries();
cs = new CharSequence[list.size()];
arrayList = new ArrayList<>();
arrayList.add("/");
while (true) {
int i = 0;
for (Metadata md : result.getEntries()) {
if (md instanceof DeletedMetadata) {
children.remove(md.getPathLower());
} else {
String fileOrFolder = md.getPathLower();
children.put(fileOrFolder, md);
if(!fileOrFolder.contains("."))
arrayList.add(fileOrFolder);
}
i++;
}
if (!result.getHasMore()) break;
try {
result = dbxClient.files()
.listFolderContinue(result.getCursor());
} catch (ListFolderContinueErrorException ex) {
ex.printStackTrace();
}
}
} catch (DbxException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Here ArrayList is just for my use wherein I'm just making a list of only folders.
So, modify accordingly.
Is it possible to write a whole shared_preferences.xml at once?
I want to realize a kind of settings import/export, so i need to read and write the whole file without loosing the xml-tags.
Reading the file is easy, but when i write my values (using PrintWriter) the old values stored in memory overwrite them seconds later.
what can i do to prevent that without writing single values using preference editor.
Now I read it from a file designed like Android's own preferences.xml and write it successively in my own function like this:
public static void preferencesImport(String PreferenceFilepath) {
preferencesImportPreferenceFilepath = PreferenceFilepath;
try {
// Parsing
// see http://theopentutorials.com/tutorials/android/xml/android-simple-xml-dom-parser/
XMLParserHelper parser = new XMLParserHelper(); // reference to described XMLDOMParser helper class
BufferedInputStream stream;
try {
stream = new BufferedInputStream(new FileInputStream(preferencesImportPreferenceFilepath));
org.w3c.dom.Document doc = parser.getDocument(stream);
// string value
NodeList nodeListString = doc.getElementsByTagName("string");
for (int i = 0; i < nodeListString.getLength(); i++) {
Element eString = (Element) nodeListString.item(i);
Pref.setString(eString.getAttribute("name"), eString.getTextContent()); // Own getter/setter -> use Android's preference manager instead in similar way
}
// repeat code above for boolean, long, int, float values
stream.close();
} catch (IOException e1) {
// output IOException
} catch (Throwable t1) {
// output Throwable1
}
writer.close();
} catch (Throwable t2) {
// output Throwable2
}
}
In my app I have a facility to download reference data updates. The user can modify base url in a PreferenceActivity - and then I append the actual file name to the base URL. When I attempt to download the file, an exception may be thrown if something went wrong. I'd like to present the user with the most appropriate error message rather than simply "error occurred". To do this, I want to catch individual exception and format messages accordingly. So, what exceptions can be thrown when downloading a file? For the reference, here's my downloading code (simplified):
int msgId;
try {
String url = props.getProperty(Constants.SETTINGS_REFDATA_SOURCE);
if(!url.endsWith("/")) {
url += "/";
}
url += Constants.UPDATE_CUSTOMER_FILE;
CSVReader in = new CSVReader(new InputStreamReader(url.openStream()));
...//read and parse file here
}
catch(MalformedURLException e) {
msgId = R.string.error_invalid_base_url;
}
catch(UnknownHostException e) {
msgId = R.string.error_unknown_host;
}
catch(FileNotFoundException e) {
msgId = R.string.error_file_not_found;
}
catch(IOException e) {
msgId = R.string.error_reading_data;
}
catch(MyParseException e) {
msgId = R.string.error_invalid_file_format;
}
catch(Exception e) {
msgId = R.string.error_other_error;
}
finally {
try { in.close(); } catch(Exception e2) {}
}
// then I display AlertDialog using msgId as the message
As you can see, I'm already catching several exception - some that I know can be thrown, some that I encountered in testing. What other exceptions do I need to cater for? Note that the amount of data being download is quite small (at most 15-20 Kb) so things like OutOfMemoryError shouldn't be applicable.
There is the ConnectException due to connection timeout or connection refused (HTTP 403)
//edit: I just read, that "Most applications should not catch the ConnectException; it is more robust to catch the superclass SocketException."
Furthermore you could test if there is an active Internet connection:
private boolean checkCon() {
ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if ( conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED
&& conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {
return false;
}
return true;
}
My question is regarding this post
Is it possible to set an animated gif file as live wallpaper in android?
The method given in this post does not seem to work. When i put my animated .gif file in /res/raw folder, there is an error which says that my file cannot be resolved or is not a field. Is there something that i should know about the resources in raw folder or there is some other problem. Following is the code.
BelleEngine() throws IOException {
InputStream is = getResources().openRawResource(R.raw.ballerina);
if (is != null) {
try {
mBelle = Movie.decodeStream(is);
mBelleDuration = mBelle.duration();
} finally {
is.close();
}
} else {
throw new IOException("Unable to open R.raw.belle");
}
Thanks for the help in advance!
I have tried the example it works for me. Also i have tried this with different .gif images and it doesn't seems that their is any problem. My code for that is .
{
/**
* Method to init suitable wallpaper according to time.
*/
private void initWallpaperAccordingtoTime(InputStream inputStream) {
if (inputStream != null) {
try {
wallpaperGifStream = Movie.decodeStream(inputStream);
if (wallpaperGifStream != null) {
duration = wallpaperGifStream.duration();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Call to this method will be as follows.
initWallpaperAccordingtoTime(getResources().openRawResource(
R.raw.android_apple));
}
I'm aware of the performance differences between Parcelable (fast) and Serializable (slow). However, I need to store certain application information persistently, not just within one lifecycle, thus onSaveInstanceState and associated methods utilising Parcelable objects aren't appropriate.
So I turned my attention to Serializable. Primarily I have AbstractList types to store - which is fine, since they implement Serializable. However, many of the types I store inside these are Parcelable but not Serializable, e.g. RectF.
I thought "no problem", since I can easily generate a Parcel via Parcelable.writeToParcel(parcel, flags) then call marshall() on it to create a byte[] which I can serialize and deserialize. I figured I'd use generics; create a SerializableParcelable<Parcelable> implements Serializable class, allowing a one-fit solution for all Parcelable types I wish to serialize. Then I would e.g. store each RectF inside this wrapper within ArrayList, and lo-and-behold the list and its Parcelable contents are serializable.
However, the API docs state that marshall() mustn't be used for persistent storage:
public final byte[] marshall ()
Returns the raw bytes of the parcel.
The data you retrieve here must not be placed in any kind of persistent storage (on local disk, across a network, etc). For that, you should use standard serialization or another kind of general serialization mechanism. The Parcel marshalled representation is highly optimized for local IPC, and as such does not attempt to maintain compatibility with data created in different versions of the platform.
So now I'm stuck. I can either ignore this warning and follow the route I've outlined above, or else circumvent the issue by extending each individual Parcelable I want to serialize and creating bespoke serialization methods, which seems extremely wasteful of time and effort.
Does anyone know of a 'correct' shortcut to serialize a Parcelable object without using marshall()? Or should I plough on without heeding the warning specified? Perhaps an SQLite database is the way to go, but I'm unsure and would like your advice.
Many thanks.
For any object you need to serialize you can use objectOutPutStream .By using this you can write objects into the file system of the device.So this can used to save Parcelable objects also.
Below is the code to save object to File System.
public static void witeObjectToFile(Context context, Object object, String filename) {
ObjectOutputStream objectOut = null;
FileOutputStream fileOut = null;
try {
File file = new File(filename);
if(!file.exists()){
file.createNewFile();
}
fileOut = new FileOutputStream(file,false);
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(object);
fileOut.getFD().sync();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}finally {
if (objectOut != null) {
try {
objectOut.close();
} catch (IOException e) {
// do nowt
}
}
if (fileOut != null) {
try {
fileOut.close();
} catch (IOException e) {
// do nowt
}
}
}
}`
Inorder to read the Object use ObjectInputStream . Find the below code.
public static Object readObjectFromFile(Context context, String filename) {
ObjectInputStream objectIn = null;
Object object = null;
FileInputStream fileIn = null;
try {
File file = new File(filename);
fileIn = new FileInputStream(file);//context.getApplicationContext().openFileInput(filename);
objectIn = new ObjectInputStream(fileIn);
object = objectIn.readObject();
} catch (FileNotFoundException e) {
// Do nothing
}catch (NullPointerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
if (objectIn != null) {
try {
objectIn.close();
} catch (IOException e) {
// do nowt
}
}
if(fileIn != null){
try {
fileIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return object;
}`
Regards,
Sha