How to show the letters like ø æ å in android Application, I want to show these characters in Full Project, Please Help How i Do it ?
When the strings are read from a JSON document make sure to decode the JSON file correctly. That is, know the character encoding that was used for creating the JSON files and use that same encoding when decoding the files.
Assuming you already have an InputStream for reading your JSON document you can use something like this:
private static final Charset JSON_CHARSET = Charset.forName("UTF-8");
private JSONObject loadJsonObject(InputStream in) throws JSONException, IOException {
InputStreamReader reader = new InputStreamReader(in, JSON_CHARSET);
StringWriter writer = new StringWriter();
copy(reader, writer);
return new JSONObject(writer.toString());
}
private static void copy(Reader reader, Writer writer) throws IOException {
try {
char[] buffer = new char[512];
while (true) {
int nChars = reader.read(buffer);
if (nChars < 0) {
break;
}
writer.write(buffer, 0, nChars);
}
} finally {
reader.close();
writer.close();
}
}
Use a charset other than UTF-8 if necessary.
How about using Charset.forName("UTF-8").encode(myString) ? Naturally, strings should be stored in external resources string.xml, so mystring should be eg.
String mystring = getString(R.string.myStringResource);
I found I had to change the XML attribute of my layout file to UTF16 to get certain extended characters to display correctly.
<?xml version="1.0" encoding="UTF-16"?>
put the special strings.xml under the res/value-xxx/
Related
I'm currently learning android with a books called "Android Programming - The Big Nerd Ranch Guide".
As a part of a learning project we create Json serializer for saving and loading data. Writing the file appearently works fine, and I get no error messages on the Logcat. After I terminate the app and recreate it, the data loader is called and raises the following exception:
org.json.JSONException: End of input at character 0
I've looked for this issue online and figured it's probably because the BufferedReader returns an empty response. I've checked and indeed it is the case.
For simplicity sake, I've temporarily put a BufferedReader into the saving function and tried reading the info I've just saved into the file, and still the BufferedReader returns only null.
public void saveCrimes(ArrayList<Crime>crimes)
throws JSONException, IOException {
JSONArray array = new JSONArray();
for(Crime c: crimes)
array.put(c.toJSON());
Writer writer = null;
try {
OutputStream out = mContext.openFileOutput(mFileName, Context.MODE_PRIVATE);
writer = new OutputStreamWriter(out);
writer.write(array.toString());
Log.d(TAG, array.toString());
} finally {
if(writer == null)
writer.close();
}
// Extracting the data
BufferedReader bufferedReader = null;
try {
InputStream inputStream = mContext.openFileInput(mFileName);
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
if (bufferedReader.readLine() == null)
Log.d(TAG, "WHY GOD WHYYYYYYY");
}catch (IOException e){
}
}
(The two log messages from the code, the first one displays the data that is in the JsonArray I'm using)
D/CriminalIntentJSONSerializer: [{"date":"Mon May 14 17:33:08 GMT+00:00 2018","id":"97fe9532-991f-4352-9de1-602fa8dfa93e","isSolved":true,"title":""}]
D/CriminalIntentJSONSerializer: WHY GOD WHYYYYYYY
Would love to hear your insight.
BufferedReader bufferedReader = null;
try {
InputStream inputStream = mContext.openFileInput(mFileName);
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
if (bufferedReader.readLine() == null)
Log.d(TAG, "WHY GOD WHYYYYYYY");
}catch (IOException e){
}
Ok. you've created your BufferedReader bufferedReader = null;
What happens when yuou say bufferedReader = new BufferedReader(anything)...Well...it can't call a new instance the same thing that's already been declared...in fact, it's already been instantiated as null. So you can't create a new instance of the same name.
Try deleting the line where you point it at null. Then, substitute
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
for the original declaration in your try block
Try to check if mFilename is empty on second try-catch, usually in Android instance disappear easily.
PD: I advise you choice another JSON library to manipulte JSON files, they are lightweight and easy-to-use.
== Edit ==
Have you added writing and reading permissions on AndroidManifest?
If answer is "there it is" try to debug app step-by-step looking for variables and in-variables for checking existence of values.
Could be file isn't writing itself or it's writing empty.
Error basically is empty string or non-format JSON-like:
""
"[{"a": "abdc", "b": "jef2","
Paying attention to BufferedReader because it read lines each and you need all file and then join into string variable.
Also, try to use android file explorer that come in AndroidStudio. There you can explore files, logs and database files and export them to your specific folders (Documents, Downloads, etc). Generally files written by app are stored in data -> <com.your.app.package>.
This is related to a situation I find myself in working with saving text files in Unity on Android, then reading them in native Android.
One of the files we read is a HMACMD5 signature, created with the code,
byte[] bData = System.Text.Encoding.UTF8.GetBytes (data);
byte[] bKey = System.Text.Encoding.UTF8.GetBytes (key);
using (HMACMD5 hmac = new HMACMD5(bKey)) {
byte[] signature = hmac.ComputeHash (bData);
return System.Convert.ToBase64String (signature);
}
And then written to the phone with,
public static void SaveText (string path, string data) {
using (FileStream fs = new FileStream(path, FileMode.Create)) {
using (StreamWriter sw = new StreamWriter(fs)) {
sw.Write (data);
}
}
}
The other string we're saving is a JSON string dump. The signature has a newline character at the end of the string, but the JSON string doesn't. I know I can manually add one, but this question is about reading the accurate file contents.
On Android, based on previous SO answers, I read the file with,
String readFile(File file) {
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append("\n");
}
br.close();
}
catch (IOException e) {
MyLogger.e(LOG_TAG, "Error opening file " + file.getPath(), e);
}
return text.toString();
}
I'm manually adding the newline character after every line, but if I do this, I don't accurately read the JSON file, which doesn't have a newline character at the end. If I don't add the newline, I don't accurately read the signature file, which does.
You better then do not use readLine() but read().
I'd like to add static JSON to an Android Studio project which can then be referenced throughout the project. Does anyone know the best method of doing this?
In more detail what I'm trying to do is this:
1) Pull data out of the Google Places API
2) Find Google places that match with places in a static JSON object
3) Place markers on a map based on the matches
I have numbers 1 and 3 working, but would like to know the best way of creating a static (constant) JSON object in my project and using it for step 2.
The answer posted above is indeed what I'm looking for, but I thought I'd add some of the code I implemented to help others take this problem further:
1) Define JSON object in a txt file in the assets folder
2) Implement a method to extract that object in string form:
private String getJSONString(Context context)
{
String str = "";
try
{
AssetManager assetManager = context.getAssets();
InputStream in = assetManager.open("json.txt");
InputStreamReader isr = new InputStreamReader(in);
char [] inputBuffer = new char[100];
int charRead;
while((charRead = isr.read(inputBuffer))>0)
{
String readString = String.copyValueOf(inputBuffer,0,charRead);
str += readString;
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
return str;
}
3) Parse the object in any way you see fit. My method was similar to this:
public void parseJSON(View view)
{
JSONObject json = new JSONObject();
try {
json = new JSONObject(getJSONString(getApplicationContext()));
} catch (JSONException e) {
e.printStackTrace();
}
//implement logic with JSON here
}
You can just place your JSON file into assets folder. Later on you'll be able to read the file, parse it and use values.
You should replace the String datatype to StringBuilder in the while loop for the properly optimized solution.
So in the while loop instead of concatenating you would append the readString to the str StringBuilder.
str.append(readString);
How to download video inside JSON with android
I need to download a video encode in base 64 in android from a JSON
The JSON is something like this:
{
"status"=0
"result"="AAAAAHGZ0eXBtcDqyAAAAAG1wN...."
}
The video in the attribute result (it's more longer). I need to download the video and save it in a file.
When converting stream to string I have this error:
E/dalvikvm-heap(4964): Out of memory on a 53109242-byte allocation.
Because the file it's to big.
How I can do this? Because I can't save it in a string.
I tried this but It didn't work:
JsonReader readerJ = new JsonReader(new InputStreamReader(is, "UTF-8"));
Gson gson = new Gson();
CapraboFileRequest file = null;
readerJ.beginObject();
int id=0;
String text="";
while (readerJ.hasNext()) {
String name = readerJ.nextName();
if (name.equals("status")) {
id = readerJ.nextInt();
} else if (name.equals("result")) {
text = readerJ.nextString().substring(0, 100);}
Log.d("result", text);
file=new CapraboFileRequest(id, text);
setFile(file);
I want to read a txt file that contains a lot of different chunks of text separated by a string. In xcode this is pretty easy and i just use.
self.Array = [text componentsSeparatedByString: #"NEWSTRING"];
I don't seem to get this to work in android though, I can read in the whole text and put it into an array but it doesn't get separated so its just one long text.
I am using this code
AssetManager mngr;
String line = null;
boolean skillcheck = false;
StringBuffer sb = new StringBuffer(0);
String[] bb = null;
tester = new ArrayList <String>();
try {
mngr = getAssets();
InputStream is = mngr.open("mytext.txt");
InputStreamReader sir = new InputStreamReader(is);
BufferedReader br = new BufferedReader(sir);
while((line=br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
tester.add(sb);
br.close();
} catch (IOException e1) {
}
Any good ways to do this?
You can use String.split method
String[] result = text.split("sometext");
For your acknowledgement
String.split returns the array of strings computed by splitting this
string around matches of the given regular expression
You should use StringTokenizer.
StringTokenizer sTok=new StringTokenizer(stringVariable, "newString");
while(sTok.hasMoreTokens())
System.out.println(sTok.nextToken());
stringVariable is the file contents and newString is the delimiter string.
EDIT
The second parameter of the StringTokenizer's constructor is the delimiter. It can be a new line \n or comma , or whatever you want.