I have an problem understanding how I am supposed to deal with emojis posted from users. I can see that the emoji is arriving to the SQLite database as an image (or font, or what?), but when selected from the database again, I get a question mark of course due to the database not understanding how it should deal with it.
Any enlightenment will do.
UPDATE
Well, utf-8 encoding/decoding was the answer just as the skilfull commenters have pointed.
My encoding:
String notes = mNotes.getText().toString();
try {
// Try to encode due to possible emojis in text
notes = URLEncoder.encode(mNotes.getText().toString(), "utf-8");
} catch (UnsupportedEncodingException ex) {
}
arguments.putString(WorkoutDataInputFragment.TEXT_EXTRA, notes);
My decoding:
try {
// Try to decode due to possible emojis in text
mMessage.setText(URLDecoder.decode(workout.message, "utf-8"));
} catch (UnsupportedEncodingException ex) {
mMessage.setText(workout.message);
}
Related
In the app that I'm making, my goal for it is to be a quick and easy notes/documents app. However, a problem that I have is that when the user saves the text they enter into an EditText, if there are extra lines that they put in, for basic formatting, those lines don't get saved into the text file. How could I remedy this? Here's the code for the saving process. Thanks!
String itemName = fileSaveListView.getItemAtPosition(position).toString();
File myExistingFile = new File(savedFilesDir, itemName);
if (myExistingFile.exists()){
myExistingFile.mkdirs();
}
try {
FileOutputStream fosForExistingFiles = new FileOutputStream(myExistingFile);
OutputStreamWriter myOutWriterExistingFiles = new OutputStreamWriter(fosForExistingFiles);
myOutWriterExistingFiles.append(textEntryEditText.getEditableText().toString());
myOutWriterExistingFiles.close();
fosForExistingFiles.close();
Toast.makeText(getBaseContext(), "Finished writing " + itemName + " to the folder", Toast.LENGTH_SHORT).show();
final AlertDialog thefileSaver = fileSaver.create();
thefileSaver.dismiss();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
OK, I finally figured it out, and got it working. For anyone else that is having this problem, here's what you need to do. When grabbing the text from your EditText, convert it to Html with the Html.toHtml function, like below.
myOutWriter.append(Html.toHtml(textEntryEditText.getText()));
Now, your text file will be saved WITH any linebreaks you have entered. The next thing to do, if you wish to display your saved file in the EditText, you just need to convert back from Html. Like so.
textEntryEditText.setText(Html.fromHtml(String.valueOf(<your file reader>)));
I have been trying to fix this problem for a VERY long time, so if anyone else was suffering like I was, I hope this helps you! :D
I'm new to Android development and I will appreciate any help I can get.
I'm designing an app that at some point needs to ask user for his Friends' names in order to work with those names later on, i.e those names will be used in drop-down lists and will be displayed at a separate View.
My question is: what is the best way to efficiently store those names and then be able to get access to them for reading, editing and deleting? The amount of names will not be big (at most 20 items).
In response to the comment about adding more info:
I need a user to specify list of names (strings) that will be used in 2 different Android Activities:
1) This list of names will be used in a Spinner that is a part of an application form
2) This list of names will be used on a separate Activity designed for Manipulating (Editing and Deleting) of existing items and adding new ones.
I also need that after manipulations (editing, deleting and creating new items) with this list changes took place in Both Activities. This list should be available after user exits the app, so as I understand it should be stored somewhere in Internal Storage.
I hate when people answer a question by just posting the link to the docs, so I won't do that.
I will post the link to the docs AND provide an answer:
DOCS: http://developer.android.com/guide/topics/data/data-storage.html
(it is actually a good read, not too long, and good to know what your options are).
It looks to me you need to save an ArrayList or something, and you are saying 20 names would be the maximum amount, so I would say you have 3 viable options, which I present here, ordered in ascending order of simplicity using my humble opinion as a comparator:
1- InternalStorage
2- SharedPreferences
3- Very interesting way I just found while researching one of the options to help you, and I will definatelly use this when I need to save a small array of data...
So the steps I would recomend are: put the names in your favourite collection object (ArrayList, HashSet, etc), then refer to those examples for the methods cited above, respectivelly:
1- https://stackoverflow.com/a/22234324/367342 (YES, this a link to a answer given on this thread, I voted it up, I feel better for cheating now).
2- Save ArrayList to SharedPreferences
3- https://stackoverflow.com/a/5703738/367342 <- this
- Convert your data to a JSONObject
- Convert it to a string
- Save this string using shared preferences
- Read it later as a jsonobject
Example on 3 (untested, sorry):
//Convert the ArrayList to json:
JSONObject json = new JSONObject();
json.put("uniqueArrays", new JSONArray(items));
//Make it into a string
String myLittleJason = json.toString();
//save it to the shared preferences
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("KEY_TO_THE_NAMES_OF_MY_DEAR_FRIENDS", myLittleJason).commit();
//Loading it back from the preferences
String loadedJsonString = PreferenceManager.getDefaultSharedPreferences(context).getString("KEY_TO_THE_NAMES_OF_MY_DEAR_FRIENDS", "I have no friends, this is the default string returned if the key was not found, so, jokes aside, better make this a empty JSON string");
//making it into a JSON again
JSONObject loadedJson = new JSONObject(loadedJsonString);
//Converting the Json back into a ArrayList
ArrayList items = loadedJson.optJSONArray("uniqueArrays");
I loved that JSON approach, if you like it too, upvote the original (too ;) ) https://stackoverflow.com/a/5703738/367342
If you are going to store only 20 items, maybe the best way is to write and read a file.
public void writeItems(String fileName) {
final String ls = System.getProperty("line.separator");
BufferedWriter writer = null;
try {
writer =
new BufferedWriter(new OutputStreamWriter(openFileOutput(fileName,
Context.MODE_PRIVATE)));
writer.write("Item 1" + ls);
writer.write("Item 2" + ls);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void readItems(String fileName) {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(openFileInput(fileName)));
String line;
while ((line = input.readLine()) != null) {
//do something
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
openFileInput and openFileOutput reference : http://developer.android.com/reference/android/content/Context.html#openFileInput(java.lang.String)
You have many options but I will give you two options:
SharedPreferences
SQLLite
If it's temporary and doesn't require intense data manipulation, I would go with SharedPreferences as it's easier to setup and easy to use and recycle.
I have a database which is encoded with Base64. I am getting data from that DB and i use it in my android layouts, also i send data to the DB. When there is Cyrillic text, it seems that it is not encrypting it properly, because i already fixed the decoding, but it cannot recognise the cyrillic encrypted text. I am using standard function to encode it is working properly with Latin characters:
public String encrypt(String text){
String result;
result = Base64.encodeToString( text.getBytes(), Base64.NO_WRAP );
return result;}
I tried a few variations but nothing worked out. Do you know how to encrypt it correctly?
I found the answer myself:
String result = null;
try {
result = Base64.encodeToString( text.getBytes("Windows-1251"), Base64.NO_WRAP );
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thanks anyway :)
I have a big problem with parsing some json data which I get as response from a web server. The thing that I'm doing is I get the response via POST and than convert the response as string and parse it. But in some devices I get OutOfMemoryError , which I'm trying to fix. Here is how I'm converting the response to string :
public static String convertStreamToString(InputStream is) throws Exception {
ByteArrayOutputStream into = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
for (int n; 0 < (n = is.read(buf));) {
into.write(buf, 0, n);
}
into.close();
return new String(into.toByteArray(), "UTF-8");
}
and here is how I'm using this piece of code :
InputStream response = new BufferedInputStream(connection.getInputStream());
try {
String responsee = convertStreamToString(response);
jsonParser(responsee);
} catch (Exception e) {
e.printStackTrace();
cancelDialog("Error occurred! Please try again later.");
}
Any suggestions how can I fix that problem so don't happen in all devices?
Thanks in advance for any kind of help or advices.
The mobile has limited internal memory.
I have also face same issue. The solution that we found is that download only the necessary information. So you please confirm your requirement how much data you want to inside the mobile. If you filter the unnecessary data then the problem will get resolved.
Before testing the program on extreme condition first check whether simple download happening if it is happening then check the limit of your data means up to how extent it will not give out of memory error. and accordingly that rework your requirement.
I am having a hard time figuring out how to write to and read from files on an Android device. The file will be formatted as XML and I already have parsers and data structures built that can format the XML into objects and objects into XML, but the last hurdle is reading the XML from a non-resource file (I know the data structures work because I it works when reading from a resource file) and also writing to a non-resource file. I am terrible at using tools to debug (not sure how to print a stack trace) but I know for a fact the problem is that I cannot read from or write to this files. I have no experience writing to files in Java which may be why I am having a rough time with this.
Write code:
File scoresFile = new File(getExternalFilesDir(null), "scores.xml");
if (!scoresFile.exists())
{
scoresFile.createNewFile();
}
OutputStream os = new FileOutputStream(scoresFile);
os.write(writer.toString().getBytes());
os.flush();
os.close();
Read Code:
XmlPullParserFactory xmlFac = XmlPullParserFactory.newInstance();
XmlPullParser qXML = xmlFac.newPullParser();
InputStream is = null;
File scoresFile = new File(c.getExternalFilesDir(null), "scores.xml");
if (!scoresFile.exists())
{
try {
scoresFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
is = new FileInputStream(scoresFile);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (is != null)
qXML.setInput(is,null);
else
qXML = c.getResources().getXml(R.xml.scores);
UPDATE: The last if clause in the read section always evaluates to false. So, the InputStream is null... that appears to be the root of my problem.
I would take a look at these two links: Using Internal Storage and Using External Storage
Both link to the same page, just different portions. Really, it depends on whether or not you want to save this file to the devices memory, or to an external medium (such as an SDcard).
Internal - Sandboxed, so that only your app can access it.
External - Anyone can access it.