How to handle special characters in json string - android

I have an app where I store user entered text into a json string. I then store that json string into a file. And then later on display it back by reading the file, extracting the json string from it and finally getting the string to display into a textview. I am however noticing that any special characters(rather symbols) like £, ÷, € etc are not displayed back. For example the symbol € gets displayed as â□¬.
Some sample code below for reference
First the code for capturing user entered text and putting it into a file
//get user entered text
QuestionEditText = (EditText)this.findViewById(R.id.editTextQuestion);
//put that into json object
JSONObject jObjOneQuestionDetails=new JSONObject();
jObjOneQuestionDetails.put("Question", QuestionEditText.getText());
//write json object into file
FileOutputStream output = openFileOutput("MyFileName",MODE_PRIVATE);
OutputStreamWriter writer = new OutputStreamWriter(output);
writer.writejObjOneQuestionDetails.put());
writer.flush();
writer.close();
Now below the code for getting the string back from file and displaying it to user
//define and initialize variables
QuestionEditText = (EditText)this.findViewById(R.id.editTextQuestion);
private JSONArray jArrayQuizQuestions=new JSONArray();
private JSONObject jObjQuizTitle=new JSONObject();
//load JSONObject with the File
int ch;
StringBuffer fileContent = new StringBuffer("");
FileInputStream fis;
String fileString;
fis = this.getBaseContext().openFileInput("MyFileName");
while( (ch = fis.read()) != -1)
fileContent.append((char)ch);
fileString = new String(fileContent);
jObjQuizTitle = new JSONObject(fileString);
jArrayQuizQuestions = jObjQuizTitle.getJSONArray("MyFileName");
//display json object into textview
JSONObject aQues = jArrayQuizQuestions.getJSONObject(pageNumber-1);
String quesValue = aQues.getString("Question");
QuestionEditText.setText(quesValue.toCharArray(), 0, quesValue.length());
The code above is just a sample, I have ignored any try/catch blocks here. This should give an idea about how I am capturing and displaying the user entered text.

You have to use "UTF-8" for using this kind of special character. For details read http://developer.android.com/reference/java/nio/charset/Charset.html
You have to encode for your expected character like this way :
URLEncoder.encode("Your Special Character", "UTF8");
You can check similar question about this issue from here :
Android: Parsing special characters (ä,ö,ü) in JSON

Related

Parsing json object from google api returning null

I am making a simple application where i scan the barcode of a book and fetch its title and author from Google APIs,
Now, this is the url for json(for a particular book i am scanning)
https://www.googleapis.com/books/v1/volumes?q=isbn:9788120305960
using this code to get json in a string
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String line = "";
while ((line=bufferedReader.readLine())!=null)
{
response+=line;
}
bufferedReader.close();
inputStream.close();
urlConnection.disconnect();
Log.d("Info",response);
return response;
I store the result in a string and use this code to parse through
(json_response is a string)
JSONObject rootObject = new JSONObject(json_response);
JSONArray items = rootObject.getJSONArray("items");
JSONObject items_object = items.getJSONObject(0);
JSONObject volume_info = items_object.getJSONObject("volumeInfo");
book.setTitle(volume_info.getString("title"));
JSONArray authors = volume_info.getJSONArray("authors");
Log.d("Info","authors array length: "+authors.length());
String author="";
for (int i =0;i<authors.length();i++)
{
author+=authors.getString(i)+", ";
}
book.setAuthor(author);
The exception is:
Value null of type org.json.JSONObject$1 cannot be converted to JSONObject
also I used logcat to see what is contained in json_response it looks something like this
null{ "kind": "books#volumes", "totalItems": 1, "items":...
The null here is probably causing the problem, so... any insights how to deal with this???
PS: I am a student , dealing first time with json and android, code is unprofessional, please pardon :)
Having
null{ "kind": "books#volumes", "totalItems": 1, "items":...
means that the response value has not been initialised.
You should therefore initialise it to empty string.

Show data for 4 edittext when read data from 1 file

I have 4 EditTExt, i write data to 1 file. But I don't know solution read data to load again for 4 EditTExtagain?
public void onClickLoad(View view) {
try
{
FileInputStream fIn =
openFileInput("textfile.txt");
InputStreamReader isr = new
InputStreamReader(fIn);
char[] inputBuffer = new char[READ_BLOCK_SIZE];
String s = "";
int charRead;
while ((charRead = isr.read(inputBuffer))>0)
{
//---convert the chars to a String---
String readString =
String.copyValueOf(inputBuffer, 0,
charRead);
s += readString;
inputBuffer = new char[READ_BLOCK_SIZE];
}
//---set the EditText to the text that has been
//Can I load data for some textbox in here
//textBox1.setText(s);
textBox.setText(s);
Toast.makeText(getBaseContext(),
"File loaded successfully!",
Toast.LENGTH_SHORT).show();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
You can try for writing the data into the JSON format.
Which is light weight and provide you ease to read data according to the EditText and if in future your EditTexts are increased/decreased it will be easy for you to add/remove data from file.
lets take sample:
JSONObject dataToFile = new JSONObject();
dataToFile.put("EditText1","My Data1");
dataToFile.put("EditText2","My Data2");
dataToFile.put("EditText3","My Data3");
dataToFile.put("EditText4","My Data4");
//Convert JSON to String
String dataToBeWritten = dataToFile.toString();
//Code to Write data to file.
When you are reading data from file. Read it as a String.
String dataReadFromFile = //Code to Read data from file.
JSONObject dataFromFile = new JSONObject(dataReadFromFile);
String editText1Text = dataFromFile.get("EditText1");
editText1.setText(editText1Text);
.
.
.
//Till you read all the data

Make String Array from Scanner InputStream

I have a sql file and I reading that with this codes
String text ="";
InputStream is = mContext.getAssets().open("sample.sql");
text = new Scanner( is,"UTF-8" ).useDelimiter("\\A").next();
I works perfect. it gives all string togetger but I want to make a Array devided by each next();

Download video inside a JSON with android

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);

JSON Parsing without using URL to read json file in android

I am using url to take the file for parsing. Now i want read the file which is in sdcard for parsing.How can i do this?
here my code
reading file from url
private static String url = "http://10.0.2.2/device1.json";
JSONObject json = jParser.getJSONFromUrl(url);
devices = json.getJSONArray(TAG_DEVICES);
now i want do this from reading the file in sdcard
java.io.File device = new java.io.File("/mnt/sdcard/device1.json");
FileReader device_Fr = new FileReader(device);
next how to pass this file for parsing?
Use this code
read data from file into string & pass that to JSONObject.
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line, results = "";
while( ( line = reader.readLine() ) != null)
{
results += line;
}
reader.close();
JSONObject obj = new JSONObject(results);
One way to do it is to read the json and store it in a string. Then parse it like this:
String jsonStr = // read from file
JSONObject json = new JSONObject( jsonStr);
// parse
 
  devices = json.getJSONArray(TAG_DEVICES);

Categories

Resources