How to retrieve multi-line text from Edittext? - android

I want to get a text(Multi-line) from Edittext same as given Screenshot.
I want below output when getText() from Edittext.
Output:
Lorem Ipsum is simply dummy
text of the printing and
typesetting industry. Lorem
Ipsum has been the industry
standard dummy text.
I have tried below solution but, it doesn't work
etMessage.getText().toString().replaceAll("\\n", "<br />")

By default all the EditText widgets in Android are multi-lined. And you can configure the number of lines and the characters types. By setting the input type to multiline do the trick.
<EditText
...
android:inputType="textMultiLine" <!-- Multiline input -->
...
android:lines="8" <!-- Total Lines prior display -->
android:minLines="6" <!-- Minimum lines -->
android:gravity="top|left" <!-- Cursor Position -->
android:maxLines="10" <!-- Maximum Lines -->
android:layout_height="wrap_content" <!-- Height determined by content -->
android:layout_width="match_parent" <!-- Fill entire width -->
android:scrollbars="vertical" <!-- Vertical Scroll Bar -->
/>

After too much searching and waiting for an answer to this question. I have resolved this issue.
Solution:
I have measured each and every line & words for preserve this as Multiline text, you can use below function for that.
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
float density = metrics.density;
String result = fitString(ipText, ipText.getText().toString());
private String fitString(EditText editText, String message) {
Log.i(TAG, "fitString: Default String : " + message);
StringBuilder finalMessage = new StringBuilder();
if (isTooLarge(editText, message)) {
Log.i(TAG, "fitString: isTooLarge 1 : " + true);
List<String> lineList = Arrays.asList(message.split("\n"));
Log.i(TAG, "fitString: stringList" + lineList);
if (lineList != null && lineList.size() > 0) {
for (int i = 0; i < lineList.size(); i++) {
if (lineList.get(i) != null && !lineList.get(i).isEmpty()) {
if (isTooLarge(editText, lineList.get(i))) {
Log.i(TAG, "fitString: isTooLarge 2 : " + lineList.get(i) + " == " + true);
List<String> wordList = Arrays.asList(lineList.get(i).split(" "));
Log.i(TAG, "fitString: wordList" + wordList);
if (wordList != null && wordList.size() > 0) {
Log.i(TAG, "fitString: wordList : " + wordList.size());
StringBuilder temp = new StringBuilder();
String lastWord = "";
for (int j = 0; j < wordList.size(); j++) {
if (wordList.get(j) != null && !wordList.get(j).isEmpty()) {
if (isTooLarge(editText, wordList.get(j))) {
Log.i(TAG, "fitString: isTooLarge 3 : " + wordList.get(j) + " == " + true);
String newString = fitCharacter(editText, wordList.get(j));
Log.i(TAG, "fitString: fitCharacter == " + newString);
if (j == (wordList.size() - 1) && i == (lineList.size() - 1)) {
finalMessage.append(newString);
} else {
finalMessage.append(newString + "\n");
}
} else {
if (j == 0) {
lastWord = wordList.get(j);
} else {
lastWord = " " + wordList.get(j);
}
temp.append(lastWord);
Log.i(TAG, "fitString: temp : " + temp);
Log.i(TAG, "fitString: lastWord : " + lastWord);
if (isTooLarge(editText, temp.toString())) {
temp.setLength(0); // clear String Builder, new StringBuilder()
temp.append(lastWord);
if (j == (wordList.size() - 1) && i != (lineList.size() - 1)) {
Log.i(TAG, "fitString: ###### 1");
finalMessage.append("\n" + lastWord.trim() + "\n");
} else {
Log.i(TAG, "fitString: ###### 2");
finalMessage.append("\n" + lastWord.trim());
}
} else {
if (j == (wordList.size() - 1) && i != (lineList.size() - 1)) {
Log.i(TAG, "fitString: ###### 3");
finalMessage.append(lastWord + "\n");
} else {
Log.i(TAG, "fitString: ###### 4");
finalMessage.append(lastWord);
}
}
Log.i(TAG, "fitString: finalMessage : " + finalMessage);
}
} else {
Log.e(TAG, "fitString: Word is Null or Empty.");
finalMessage.append(" ");
}
}
} else {
Log.e(TAG, "fitString: wordList is Null or Empty.");
}
} else {
Log.i(TAG, "fitString: isTooLarge 2 : " + lineList.get(i) + " == " + false);
if (i == (lineList.size() - 1)) {
finalMessage.append(lineList.get(i));
} else {
finalMessage.append(lineList.get(i) + "\n");
}
}
} else {
Log.e(TAG, "fitString: Line is Null or Empty.");
finalMessage.append(lineList.get(i) + "\n");
}
}
} else {
Log.e(TAG, "fitString: stringList is Null or Empty.");
finalMessage.append("");
}
return finalMessage.toString();
} else {
Log.i(TAG, "fitString: isTooLarge : " + false);
return message;
}
}
public String fitCharacter(EditText editText, String message) {
Log.i(TAG, "fitCharacter2: Default Word : " + message);
StringBuilder finalWord = new StringBuilder();
int startIndex = 0;
int endIndex = 1;
for (; ; ) {
String tempSplitWord = message.substring(startIndex, endIndex);
Log.i(TAG, "fitCharacter2: startIndex : " + startIndex + " endIndex : " + endIndex + " tempSplitWord : " + tempSplitWord);
if (!isTooLarge(editText, tempSplitWord)) { // isTooLarge
if (endIndex < message.length()) {
endIndex = endIndex + 1;
Log.i(TAG, "IF fitCharacter2: endIndex < message.length() " + endIndex + " < " + message.length());
} else {
String result = finalWord.append(tempSplitWord).toString();
Log.i(TAG, "IF RETURN RESULT : " + result);
return result;
}
} else {
endIndex = endIndex - 1;
String splitWord = message.substring(startIndex, endIndex);
Log.i(TAG, "ELSE fitCharacter2: startIndex : " + startIndex + " endIndex : " + endIndex + " splitWord : " + splitWord);
boolean isTooLarge = isTooLarge(editText, splitWord);
if (!isTooLarge) {
finalWord.append(splitWord + "\n");
}
startIndex = endIndex;
endIndex = endIndex + 1;
Log.i(TAG, "ELSE fitCharacter2: startIndex : " + startIndex + " endIndex : " + endIndex);
}
}
}
private boolean isTooLarge(EditText editText, String newText) {
if (editText != null && editText.getPaint() != null) {
float textWidth = editText.getPaint().measureText(newText);
return (textWidth >= (editText.getMeasuredWidth() - (12 * density))); // editText.getMeasuredWidth();
} else {
return false;
}
}

For next comers, I find the accepted answer overcomplicated for the task. Here is a nice extension code in Kotlin that uses Paint.breakText(). That said, it can probably be simplified further...
fun EditText.getMultilineText(): String {
val maxWidth = (width - paddingLeft - paddingRight).toFloat()
val original = text.toString().trim()
val len = original.length
val multiline = mutableListOf<String>()
var p = 0
var count = -1
while (count != 0) {
count = paint.breakText(original, p, len, true, maxWidth, null)
if (p + count < len) {
var tmp = count
while (tmp > 0 && original[p + tmp - 1] != ' ') {
tmp -= 1
}
if (tmp > 0) {
count = tmp
}
}
val tmp = original.substring(p, p + count).trim()
if (tmp.isNotBlank()) {
multiline.add(tmp)
}
p += count
}
return multiline.joinToString("\r\n")
}

did you try this one
message = etMessage.getText().toString().replaceAll("\\n", "<br />")
please see this also How can I preserve line breaks from EditText?

Related

Android ArrayList of int

I'm new with android and java, so I apologize if what I say is not entirely correct.
In my application I'd like to convert an ArrayList to integer
to increase each value with a +1. Please note the commented out part to understand where is my problem. I can't find the right way..
This is what I do for now:
public String mRequest(String mUrl, String mAuth, String mParam, String customerId, ArrayList filter) {
InputStream mStreamResponse;
String mString = null;
try {
URL obj = new URL(mUrl);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Authorization", mAuth);
con.setRequestProperty("X-Limit", String.valueOf(xLimit));
con.setRequestProperty("X-Skip", String.valueOf(xSkip));
con.setRequestProperty("X-Sort", "{\"created\":-1}");
String parameters = null;
System.out.println("Value of mParam -> " + mParam);
if (mParam != null && customerId != null) {
Log.e("ERROR", "Ricerca per parametro e customerId");
} else if (mParam != null) {
parameters = "\"number\":{\"$regex\":" + mParam + "}";
} else if (customerId != null) {
parameters = "\"customer.id\":{\"$eq\":" + "\"" + customerId + "\"" + "}";
} else {
parameters = "\"number\":{\"$regex\":\"\"}";
}
System.out.println("parameters");
System.out.println(parameters);
if (filter != null) {
//convert ArrayList to Array
Object[] mArray = filter.toArray();
String filterGroup = mArray[0].toString() + ".id";
System.out.println("Group selected -> " + filterGroup);
for (int i = 1; i < mArray.length; i++) {
System.out.println("Value -> " + mArray[i]);
}
String pFilter = null;
for (int i = 1; i < mArray.length; i++) {
/*
*
* This is where I need to change value in
* pos i with i + 1
*
*/
switch (mArray[i].toString()) {
case "0":
mArray[i] = "1";
break;
case "1":
mArray[i] = "2";
break;
case "2":
mArray[i] = "3";
break;
case "3":
mArray[i] = "4";
break;
case "4":
mArray[i] = "5";
break;
case "5":
mArray[i] = "6";
break;
case "6":
mArray[i] = "7";
break;
case "7":
mArray[i] = "8";
break;
case "8":
mArray[i] = "9";
break;
case "9":
mArray[i] = "10";
break;
case "10":
mArray[i] = "11";
break;
case "11":
mArray[i] = "12";
break;
case "12":
mArray[i] = "13";
break;
}
if (mArray.length == 2){
pFilter = mArray[i].toString();
} else {
if (mArray[i] != mArray[mArray.length - 1]) {
if (pFilter != null) {
pFilter = pFilter + mArray[i].toString() + ",";
} else {
pFilter = mArray[i].toString() + ",";
}
} else {
pFilter = pFilter + mArray[i].toString();
}
}
}
String mFilter = "[" + pFilter + "]";
System.out.println("Insert value in a string -> " + mFilter);
String tempParam = null;
if (filterGroup.equals("assignee")) {
tempParam = "{\"$eq\":" + mFilter + "}";
} else {
tempParam = "{\"$in\":" + mFilter + "}";
}
//Override the value with the same filterGroup
if (filterMap.containsKey(filterGroup)) {
String toOverride = filterGroup;
filterMap.remove(filterGroup);
filterMap.put(toOverride, tempParam);
} else {
filterMap.put(filterGroup, tempParam);
}
//iterate
for (Map.Entry<String, String> entry : filterMap.entrySet()) {
switch (entry.getKey()) {
case "status.id":
status = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
case "queue.id":
queues = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
case "type.id":
types = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
case "severity.id":
severities = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
case "assignee.id":
mytickets = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
}
}
filterMapValues = parameters ;
if (status != null) {
filterMapValues += ", " + status;
}
if (queues != null) {
filterMapValues += ", " + queues;
}
if (types != null) {
filterMapValues += ", " + types;
}
if (severities != null) {
filterMapValues += ", " + severities;
}
if (mytickets != null) {
filterMapValues += ", " + mytickets;
}
String myFilter = "{" + filterMapValues + "}";
System.out.println("myFilter -> " + myFilter);
//setup request header
con.setRequestProperty("X-Filter", myFilter);
} else {
String xFilter = "{\"status.id\":" + statusAll + ", \"queue.id\":" + queueAll + ", \"type.id\":" + typeAll + ", \"severity.id\":" + severityAll + "," + parameters + "}";
con.setRequestProperty("X-Filter", xFilter);
System.out.println("Reset all -> " + xFilter);
}
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + mUrl);
System.out.println("Response Code : " + responseCode);
mStreamResponse = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(mStreamResponse));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
mStreamResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
mString = sb.toString();
} catch (Exception e) {
}
return mString;
}
How can I do?
Thanks in advance.
Edit
I started the for loop in pos #1 because in pos #0 I save filterGroup value, and that's a String, I need to menage as int only values in pos > 0
First off:
I'd like to convert an ArrayList to integer [...]
ArrayList<E> is a collection object with type E that can be any object or primitive. What you are really asking for is how to convert an ArrayList<String> (see that it is an ArrayList of type String) into an integer array. I can see you have already converted the ArrayList<String> into an Object[] (Object array that can hold both integers and Strings) using the following line in the example code given above:
Object[] mArray = filter.toArray();
Getting back to the original answer, this would do it:
int[] mArray = new int[filter.size()];
for (int i = 0; i < filter.size(); i++) {
int value = Integer.parseInt(filter.get(i));
mArray[i] = value++;
}
Your code is correct just change the for loop initial value to start from 0 rather than 1 like this:
int tempValue = 0;
for (int i = 0; i < mArray.length; i++) {
{
// increasing your mArray value
tempValue = (Integer) mArray[i] + 1;
mArray[i] = tempValue;
//Rest of your code
}
Can you try this please.
Remove your switch case inside for and replace it with below. Hope you want something like this.
for(int i=0; i<mArray.length(); i++){
mArray[i] = i+1;
}
let me know..
Do follwoing
Step 1: Create a method
private List<Integer> stringToIncrementedString(ArrayList<String> stringArrayList){
List<Integer> arrayInt;
arrayInt = new ArrayList<Integer>();
for(int i=1 ;i<stringArrayList.size();i++)
arrayInt.add(Integer.parseInt(stringArrayList.get(i))+1);
return arrayInt;
}
Step 2 :Call this method from where you want.It will return the Arraylist with incremented value.

PhoneUtils equivalent code for edit text

Do you have a piece of code to manually format a given phone number in Android? I don't want use PhoneUtils. I need this for a project for my course.
I had a similar issue, please check my code below:
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count)
{
String str;
/*Log.i("ED",
"LengthBefore before (lengthBefore = lengthAfter;): "
+ String.valueOf(lengthBefore));*/
lengthBefore = lengthAfter;
lengthAfter = s.length();
/*Log.i("ED",
"LengthBefore after (lengthBefore = lengthAfter;): "
+ String.valueOf(lengthBefore));*/
if ((lengthBefore < lengthAfter) || lengthBefore == 0)
{
if (!isResetClicked)
{
if (s.length() == 0)
{
editPhoneNumber.setText("(");
}
if (s.length() == 1)
{
str = editPhoneNumber.getText().toString();
editPhoneNumber.setText("(" + str);
editPhoneNumber.setSelection(editPhoneNumber
.getText().length());
}
if (s.length() == 4)
{
str = editPhoneNumber.getText().toString();
editPhoneNumber.setText(str + ") ");
editPhoneNumber.setSelection(editPhoneNumber
.getText().length());
}
if (s.length() == 9)
{
str = editPhoneNumber.getText().toString();
editPhoneNumber.setText(str + " ");
editPhoneNumber.setSelection(editPhoneNumber
.getText().length());
}
if (s.length() == 12)
{
str = editPhoneNumber.getText().toString();
editPhoneNumber.setText(str + " ");
editPhoneNumber.setSelection(editPhoneNumber
.getText().length());
}
}
}
lengthAfter = s.length();
/*Log.i("ED", "LengthAfter after (lengthAfter = s.length();): "
+ String.valueOf(lengthAfter));
Log.i("ED", "LengthBefore: " + String.valueOf(lengthBefore));
Log.i("ED", "LengthAfter: " + String.valueOf(lengthAfter));*/
}

Variable delay before updating an android textview

I have been trying to solve this problem for 9 hours straight, but nothing seems to work. I am building an app that captures values for all the available sensors in an Android phone over a certain time period, and stores these values in a remote database.
Two things should be kept in mind:
Each sensor has its own capture frequency (i.e. accelerometer each 10 seconds, gyroscope each 5 seconds, proximity each 60 seconds etc...).
This process doesn't go indefinitely, so there is a variable called duration, that specifies the total time spent capturing values. For example, if acctime = 10 and duration = 60, then we'll end up with 7 values captured at the 0s, 10s, 20s, 30s, 40s, 50s and 60s marks.
OK now for the code:
public void onSensorChanged(SensorEvent event) {
Sensor s = event.sensor;
if (s.getType() == Sensor.TYPE_ACCELEROMETER)
{
acc1 = event.values[0];
acc2 = event.values[1];
acc3 = event.values[2];
accm = (float) Math.sqrt(acc1 * acc1 + acc2 * acc2 + acc3 * acc3);
}
}
In the code above, the values are stored into their respective variables successfully.
Next, I want to display these variables in a textview, and update the textview as specified before (according to the frequency and total duration):
public void capture(View view) {
DecimalFormat df = new DecimalFormat("#.###");
for (i = 0; i < duration; i++) {
if ((i+1) % acctime == 0) {
acc1 = Float.valueOf(df.format(acc1));
acc2 = Float.valueOf(df.format(acc2));
acc3 = Float.valueOf(df.format(acc3));
accm = Float.valueOf(df.format(accm));
acctext.setText("i: " + i + "\nAccelerometer:\n\nX: " + acc1
+ "\nY: " + acc2 + "\nZ: " + acc3 + "\nMagnitude: "
+ accm);
}
}
}
Here, the test if (i % acctime == 0) guarantees that the textview is updated whenever i is a multiple of acctime, which is precisely what we want: so for example if acctime = 10, the textview is updated when i = 0, 10, 20, 30, 40, 50 and 60.
However, for the life of me, I couldn't figure out how pause the loop for 1 second before proceeding (assign to i a time value of 1 second means that the loop makes sense, going from 0 to duration), so all that's left is pause the loop for 1 second.
I tried Thread.Sleep(1000) between a try/catch block, but it didn't work (it crashed).
The same happened for android.os.SystemClock.sleep(1000); .
I also found some code that looks like
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//insert code here
}
}, 1000);
Either it didn't work, or I am implementing something incorrectly.
Please, any help would be greatly appreciated.
Below is the full version of the function, and it's the version that makes sense the most to me. Please point out any errors that you can find:
public void capture(View view) {
DecimalFormat df = new DecimalFormat("#.###");
int i = 1;
while (i <= duration) {
if (acctime != -1 && (i % acctime == 0 || i == 1)) {
acc1 = Float.valueOf(df.format(acc1));
acc2 = Float.valueOf(df.format(acc2));
acc3 = Float.valueOf(df.format(acc3));
accm = Float.valueOf(df.format(accm));
acctext.setText("Accelerometer:\n\nX: " + acc1 + "\nY: " + acc2
+ "\nZ: " + acc3 + "\nMagnitude: " + accm);
}
if (magtime != -1 && (i % magtime == 0 || i == 1)) {
mag1 = Float.valueOf(df.format(mag1));
mag2 = Float.valueOf(df.format(mag2));
mag3 = Float.valueOf(df.format(mag3));
magm = Float.valueOf(df.format(magm));
magtext.setText("Magnetometer\n\nX: " + mag1 + "\nY: " + mag2
+ "\nZ: " + mag3 + "\nMagnitude: " + magm);
}
if (proxtime != -1 && (i % proxtime == 0 || i == 1)) {
prox = Float.valueOf(df.format(prox));
proxtext.setText("Proximity\n\nMagnitude: " + prox);
}
if (lighttime != -1 && (i % lighttime == 0 || i == 1)) {
light = Float.valueOf(df.format(light));
lighttext.setText("Light:\n\nMagnitude: " + light);
}
if (presstime != -1 && (i % presstime == 0 || i == 1)) {
pressure = Float.valueOf(df.format(pressure));
presstext.setText("Pressure:\n\nMagnitude: " + pressure);
}
if (gyrotime != -1 && (i % gyrotime == 0 || i == 1)) {
gyro1 = Float.valueOf(df.format(gyro1));
gyro2 = Float.valueOf(df.format(gyro2));
gyro3 = Float.valueOf(df.format(gyro3));
gyrom = Float.valueOf(df.format(gyrom));
gyrotext.setText("Gyroscope:\n\nX: " + gyro1 + "\nY: " + gyro2
+ "\nZ: " + gyro3 + "\nMagnitude: " + gyrom);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i++;
}
}
Apply Handler as follows to delay for 1sec.
int i = 1;
public void capture(View view) {
final DecimalFormat df = new DecimalFormat("#.###");
Handler handler = new Handler();
while (i <= duration) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (acctime != -1 && (i % acctime == 0 || i == 1)) {
acc1 = Float.valueOf(df.format(acc1));
acc2 = Float.valueOf(df.format(acc2));
acc3 = Float.valueOf(df.format(acc3));
accm = Float.valueOf(df.format(accm));
acctext.setText("Accelerometer:\n\nX: " + acc1
+ "\nY: " + acc2 + "\nZ: " + acc3
+ "\nMagnitude: " + accm);
}
if (magtime != -1 && (i % magtime == 0 || i == 1)) {
mag1 = Float.valueOf(df.format(mag1));
mag2 = Float.valueOf(df.format(mag2));
mag3 = Float.valueOf(df.format(mag3));
magm = Float.valueOf(df.format(magm));
magtext.setText("Magnetometer\n\nX: " + mag1 + "\nY: "
+ mag2 + "\nZ: " + mag3 + "\nMagnitude: "
+ magm);
}
if (proxtime != -1 && (i % proxtime == 0 || i == 1)) {
prox = Float.valueOf(df.format(prox));
proxtext.setText("Proximity\n\nMagnitude: " + prox);
}
if (lighttime != -1 && (i % lighttime == 0 || i == 1)) {
light = Float.valueOf(df.format(light));
lighttext.setText("Light:\n\nMagnitude: " + light);
}
if (presstime != -1 && (i % presstime == 0 || i == 1)) {
pressure = Float.valueOf(df.format(pressure));
presstext
.setText("Pressure:\n\nMagnitude: " + pressure);
}
if (gyrotime != -1 && (i % gyrotime == 0 || i == 1)) {
gyro1 = Float.valueOf(df.format(gyro1));
gyro2 = Float.valueOf(df.format(gyro2));
gyro3 = Float.valueOf(df.format(gyro3));
gyrom = Float.valueOf(df.format(gyrom));
gyrotext.setText("Gyroscope:\n\nX: " + gyro1 + "\nY: "
+ gyro2 + "\nZ: " + gyro3 + "\nMagnitude: "
+ gyrom);
}
i++;
}
}, 1000);
}
}

setSpan() will only produce one image

SpannableStringBuilder authorText = new SpannableStringBuilder("");
ImageSpan is = new ImageSpan(getActivity(), R.drawable.ic_birdhead);
for (Author a : mStory.authors) {
if (!TextUtils.isEmpty(a.authorName)) {
String prefix = "";
if (count == 0) {
prefix = "By: ";
} else if (count > 0 && count < mStory.authors.size()-1) {
prefix = ", ";
} else {
prefix = " and ";
}
authorText.append(prefix + a.authorName + " ");
authorText.setSpan(is, authorText.length()-1, authorText.length(), 0);
//authorText.setSpan(is, authorText.length()-2, authorText.length()-1, 0);
//^ I put a second one there just to check is two will populate
count++;
}
So.. It goes through a for loop anyway, but I put 2 setSpan()'s to see if the last iteration would populate 2 images. It only populates an image at the very end of the string. Maybe there is a certain flag i have to put in for setspan to produce multiple?
Try this:
SpannableStringBuilder authorText = new SpannableStringBuilder("");
ImageSpan is = new ImageSpan(getActivity(), R.drawable.ic_birdhead);
for (Author a : mStory.authors) {
if (!TextUtils.isEmpty(a.authorName)) {
String prefix = "";
if (count == 0) {
prefix = "By: ";
} else if (count > 0 && count < mStory.authors.size()-1) {
prefix = ", ";
} else {
prefix = " and ";
}
authorText.append(prefix + a.authorName + " ");
authorText.setSpan(is, authorText.length()-1, authorText.length(), 0);
is = new ImageSpan(getActivity(), R.drawable.ic_birdhead);
authorText.setSpan(is, authorText.length()-2, authorText.length()-1, 0);
//^ I put a second one there just to check is two will populate
count++;
}

JSON remove special characters

I want to do the replication between Android sqlite & MS SQL server.That Time i want to take Tables values from Databse.
This is my JSON
{
"Table1":[
{
"BusinessUnit":"MASS",
"ProductCode":"SLD0201",
"Description":"Lou Difan C.Blue 12"3- Commode",
"Description2":"301 0201"
},
{
"BusinessUnit":"MASS",
"ProductCode":"SLN0502",
"Description":"Lou Napoli I"vory- Cistern",
"Description2":"2011 0502"
},
{
"BusinessUnit":"MASS",
"ProductCode":"LDMBL6H",
"Description":"Dortek Taper Bullet Handle 6"5 serr ",
"Description2":"Taper Bullet Ha"
}
],
"Table2":[
{
"chk":6,
"currentchk":1
}
]
}
In Here JSON Description column value contain "(double quotation) .If we check http://jsonformatter.curiousconcept.com/ , it show error.Its a Invalid JSON.
WCF service I have converted DataSet to JSON. Some table column contain special charters.
I converted like this :
public String ConverTableToJson(DataSet dsDownloadJson,int currentSplit)
{
StringBuilder Sb = new StringBuilder();
String result = "";
int start = 0;
int end =500;
int chk = 0;
int currentChk = currentSplit;
if (dsDownloadJson.Tables.Count > 0)
{
Sb.Append("{");
foreach (DataTable dt in dsDownloadJson.Tables)
{
DataTable dtDownloadJson = dt;
string[] StrDc = new string[dtDownloadJson.Columns.Count];
string HeadStr = string.Empty;
double total = dtDownloadJson.Rows.Count;
Console.WriteLine("--1--" + dtDownloadJson.Rows.Count);
if (dtDownloadJson.Rows.Count < 500)
{
end = dtDownloadJson.Rows.Count;
}
if (chk == 0)
{
if (dtDownloadJson.Rows.Count > 500)
{
if ((dtDownloadJson.Rows.Count / 500) == 0)
{
chk = dtDownloadJson.Rows.Count / 500;
}
else
{
chk = dtDownloadJson.Rows.Count / 500 + 1;
}
}
else
{
chk = 1;
}
currentChk = 1;
}
else
{
currentChk = currentChk + 1;
start = currentChk * 500;
end = start + 500;
currentChk = chk;
}
Sb.Append("\"" + dtDownloadJson.TableName + "1\" : [");
if (dtDownloadJson.Rows.Count > 0)
{
for (int i = 0; i < dtDownloadJson.Columns.Count; i++)
{
StrDc[i] = dtDownloadJson.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
}
if (HeadStr.Length > 0)
{
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
Console.WriteLine("--2--" + start);
Console.WriteLine("--3--" + end);
for (int i = start; i < end; i++)
{
string TempStr = HeadStr;
Sb.Append("{");
for (int j = 0; j < dtDownloadJson.Columns.Count; j++)
{
TempStr = TempStr.Replace(dtDownloadJson.Columns[j] + j.ToString() + "¾", dtDownloadJson.Rows[i][j].ToString());
TempStr = TempStr.Replace(""", '\"');
}
Sb.Append(TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
}
}
else
{
}
Sb.Append("],");
if (chk > 1)
{
Sb.Append("\"Table2\": [{\"chk\": " + chk + ", \"currentchk\": " + currentChk + " }]");
}
else
{
Sb.Append("\"Table2\": [{\"chk\": " + chk + ", \"currentchk\": " + currentChk + " }]");
}
}
// Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
Sb.Append("}");
return Sb.ToString();
}
else
{
return "0";
}
}
My problem is removing special charters OR How to allow special characters.?
Please help me anybody...
You shouldn't use a StringBuilder to convert an object to a JSON string. Use the JsonConverter class in JayRock JSON library and it takes care of Serialising/Deserialising Json for you (including escaping)
try to use inbuilt json serialization
public static string Serialize<T>(T obj)
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new
System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string retVal = Encoding.Default.GetString(ms.ToArray());
ms.Dispose();
return retVal;
}

Categories

Resources