Unable to replace in my android app - android

android version:4.2
my sample code is:
try {
//HttpResponse response = httpClient.execute(httpGet, localContext);
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
text=text.replaceAll("<", "<").replace(">", ">").replace(" ", " ");
int start=text.indexOf("<message>");
start=start+9;
int end=text.indexOf("</message>");
text=text.substring(start, end);
JSONArray ja = new JSONArray(text) ;
// ITERATE THROUGH AND RETRIEVE CLUB FIELDS
int n = ja.length();
for (int i = 0; i < 1; i++) {
// GET INDIVIDUAL JSON OBJECT FROM JSON ARRAY
JSONObject jo = ja.getJSONObject(i);
title+= jo.getString("Title")+",";
url= jo.getString("URL");
desc= jo.getString("Description");
}
} catch (Exception e) {
return e.getLocalizedMessage();
}
issue: Varible desc(i.e., description in my json)contains ** ** in its contents.I have converted HTML into string in android using following code:
Spanned marked_up = Html.fromHtml(results);
tv2.setText(marked_up.toString(),BufferType.SPANNABLE);
Still it is not replacing ** **.
Help me anyone plz.
ThankYou in advance.

marked_up.toString().replaceAll("&nbsp","");

Use tv2.setText(marked_up) instead of tv2.setText(marked_up.toString(),BufferType.SPANNABLE);

public static final String unescapeHTML(String s, int f){
String [][] escape = {{ " " , " " }};
int i, j, k;
i = s.indexOf("&", f);
if (i > -1) {
j = s.indexOf(";" ,i);
f = i + 1;
if (j > i) {
String temp = s.substring(i , j + 1);
k = 0;
while (k < escape.length) {
if (escape[k][0].equals(temp)) break;
else k++;
}
if (k < escape.length) {
s = s.substring(0 , i) + escape[k][1] + s.substring(j + 1);
return unescapeHTML(s, f);
}
}
}
return s;
}
Use this function as text = unescapeHTML(text,0);

Try to change following line desc= jo.getString("Description"); into this:
desc= Html.fromHtml(jo.getString("Description"));

Use this method,
Html.fromHtml(text);
title+= Html.fromHtml(jo.getString("Title"))+",";

i think you should have to remove &nbsp,<,> from server side because you have to check different node every time.... so change on server side code of webservice... it will be best for you...

Related

Getting an attribute from an object inside an arraymap

I'm creating a class called "partite", and this is the code
public class Partita {
String HT; //HomeTeam
String AT; //AwayTeam
String dataP; //dataPartita
int HG; //HomeGoal
int AG; //AwayGoal
String FTR; //Full time result
public Partita(){
this.HT = "";
this.AT = "";
this.dataP = "";
this.HG = 0;
this.AG = 0;
this.FTR = "";
}
public Partita(String HT, String AT, String dataP, int HG, int AG, String FTR) {
this.HT = HT;
this.AT = AT;
this.dataP = dataP;
this.HG = HG;
this.AG = AG;
this.FTR = FTR;
}
}
In the main activity I'm creating an ArrayList, putting a list of some "Partita" object, with attributes come from a json file, and then I create an ArrayMap and put the ArrayList inside, like this
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
partite.add(new Partita(jsonPart.getString("HomeTeam"),
jsonPart.getString("AwayTeam"),jsonPart.getString("Date"),
jsonPart.getInt("FTHG"), jsonPart.getInt("FTAG"),
jsonPart.getString("FTR")));
partitemap.put(i, partite.get(i));
Log.i("partita", partite.get(i).HT + " " + partite.get(i).HG + ":" + partite.get(i).AG + " " + partite.get(i).AT);
}
How can I use the ArrayMap instead of ArrayList to get the attributes of an object and use it?
Use this instead (edited):
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
partitemap.put(i, new Partita(jsonPart.getString("HomeTeam"),
jsonPart.getString("AwayTeam"),
jsonPart.getString("Date"),
jsonPart.getInt("FTHG"),
jsonPart.getInt("FTAG"),
jsonPart.getString("FTR")
)
);
Log.d("tag", partitemap.get(i).HT);
}

How to parse this JSON in to string in android?

Can someone show me how to write this json into a code?
Is it correct if I get this json data as json object first and the loop the jsonarray in the try catch block in android?
{"charges":[{"Fhour":"0.3","Shour":"0.2","Rhours":"0.1"}]}
Kindly help me thanks in advance
Your String can be parsed like
String json = "{\"charges\":[{\"Fhour\":\"0.3\",\"Shour\":\"0.2\",\"Rhours\":\"0.1\"}]}";
JSONObject jsonObject = new JSONObject(json);
JSONArray charges = jsonObject.getJSONArray("charges");
for (int i = 0; i < charges.length(); i++) {
JSONObject c = charges.get(i);
String fHour = c.getString("Fhour");
String sHour = c.getString("Shour");
String rHours = c.getString("Rhours");
Log.d("(f,s,r)Hours : ", "(" + fHour + "," + sHour + "," + rHours + ")");
}
Use built-in JSON library.
JSONObject buddiesDoc = new JSONObject(result);
JSONArray buddies = buddiesDoc.getJSONArray("buddies");
for (int n = 0; n < buddies.length(); n++) {
JSONObject object = buddies.getJSONObject(n);
object.getString(BuddyManager.CACHED_BUDDY_KEY_CONTACTID);
...

cannot invoke getjsonobject(int) on the primitive type int

Can someone help me on this...
I'm just trying to make these lines of codes work. At menuitemArray.length().getJSONObject(i) it gives me the error, "cannot invoke getjsonobject(int) on the primitive type int"
Here's the code :
private void parse(TextView txtResult) throws Exception{
jObject = new JSONObject(xResult);
JSONArray menuitemArray = jObject.getJSONArray("message");
String sret = "";
for (int i = 0; i < menuitemArray.length(); i++){
sret +=menuitemArray.length().getJSONObject(i).getString("username") + " : ";
System.out.println(menuitemArray.getJSONObject(i)
.getString("username"));
System.out.println(menuitemArray.getJSONObject(i)
.getString("subject"));
sret +=menuitemArray.getJSONObject(i)
.getString("subject") + "\n";
}
txtResult.setText(sret);
}
And yeah, I'm kinda new to this. Any help would be greatly appreciated.
Change
sret +=menuitemArray.length().getJSONObject(i).getString("username") + " : ";
to
sret +=menuitemArray.getJSONObject(i).getString("username") + " : ";
Actually sret is an String variable. And you're trying to get username from the length of menuitemArray.
try this:
private void parse(TextView txtResult) throws Exception{
jObject = new JSONObject(xResult);
JSONArray menuitemArray = jObject.getJSONArray("message");
String sret = "";
for (int i = 0; i < menuitemArray.length(); i++){
sret +=menuitemArray.getJSONObject(i).getString("username").toString()+" : ";
System.out.println(menuitemArray.getJSONObject(i)
.getString("username"));
System.out.println(menuitemArray.getJSONObject(i)
.getString("subject"));
sret +=menuitemArray.getJSONObject(i)
.getString("subject")+"\n";
}
txtResult.setText(sret);
}

How to sort/order JSON output?

I have a JSON loop and I am able to get objects in the loop, but the problem is my output is not in order:
My expected output is:
Menu Id 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23
but I get results like:
Menu Id: 19,18,23,16,17,14,15,12,13,21,20,22,4,3,11,2,1.
How can I sort this the way I expect?
JSONArray values = menuObject.toJSONArray(names);
for (int i = 0; i< values.length(); i++) {
JSONObject json2 = (JSONObject) values.getJSONObject(i);
//int menu_id = json2.getInt("menu_id");
menu_id = json2.getString("menu_id");
int m_id = Integer.parseInt(menu_id);
if (json2.has("menu_parent")) {
menu_parent = json2.getString("menu_parent");
}
if (m_id < 0) {
//
} else {
id = id + menu_id + ",";
int menu_category = Integer.parseInt(menu_parent);
System.out.println("Menu Id" + id);
if (json2.has("menu_name")) {
menu_list = json2.getString(KEY_MENU).trim();
System.out.println("Menu List" +menu_title);
menu_title = menu_title + menu_list + ",";
}
}
}
I think you can get it sorted this way:
Collections.sort("your data", new Comparator<Item>() {
public int compare(Item i1, Item i2) {
return i1.getCaption().compareTo(i2.getCaption());
}
});
After this is done, it should be sorted out.
Try this:
String menuids = "19,18,23,16,17,14,15,12,13,21,20,22,4,3,11,2,1";
String[] ids = menuids.split(",");
Integer[] result = new Integer[ids.length];
for (int i = 0; i < ids.length; i++) {
result[i] = Integer.parseInt(ids[i].trim());
}
Collections.sort(Arrays.asList(result));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < result.length; i++) {
Integer intValue = result[i];
sb.append(intValue);
if (i < result.length - 1) {
sb.append(", ");
}
}
String finaldata = sb.toString();
System.out.println(finaldata);

Multi-dimensional array to JSON java / android gson

In my web service I'm making a query to a database, and I would like to return 2 columns of the database and put these columns in a 2d array.
Also I would like to convert the array to JSON and send it to the client. The client using gson parses the message from the server in a 2d array. Is it possible?
I have tried a lot but no luck till now. Thank you in advance.
The last version i've tried is this:
private static String[][] db_load_mes (String u){
ArrayList<String> array1 = new ArrayList<String>();
ArrayList<String> array2 = new ArrayList<String>();
JSONObject messages = new JSONObject();
Connection c = null;
try{
// Load the driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
c = DriverManager.getConnection("jdbc:odbc:dsn1","mymsg","mymsg");
Statement s = c.createStatement();
// SQL code:
ResultSet r;
r = s.executeQuery("select * from accounts ");
int i = 0, j = 0;
int k = 0;
String x,y;
while(r.next()) {
x = r.getString("username");
array1.add(x);
y = r.getString("password");
array2.add(y);
k = k + 1;
}
int count = array1.size();
String[][] row = new String[count][2];
Iterator<String> iter = array1.iterator();
while (iter.hasNext()) {
row[i][0]=iter.next();
i++;
}
Iterator<String> iter2 = array2.iterator();
while (iter2.hasNext()) {
row[j][1]=iter2.next();
j++;
}
for(int z=0;z<count;z++)
System.out.println(row[z][0] + "\t" + row[z][1] + "\n");
if (k == 0)
System.err.println("no accounts!");
c.close();
s.close();
}
catch(SQLException se)
{
System.err.println(se);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return ...;
}
With the above code I can create the 2d array but how can I send this array to the client.
Here is how I made it using Gson from google...
Download gson from here
include it in your project.
package javaapplication1;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JavaApplication1 {
public static void main(String[] args) {
int rows = 3;
String records[][] = new String[][]{{"bob", "123-pass"},
{"erika", "abc123"},
{"richard", "123123123"}
};
Gson gson = new Gson();
String recordsSerialized = gson.toJson(records);
System.out.println(recordsSerialized);
/* prints this
[["bob","123-pass"],["erika","abc123"],["richard","123123123"]]
*/
// if you want a better output import com.google.gson.GsonBuilder;
Gson gsonPretty = new GsonBuilder().setPrettyPrinting().create();
String recordsSerializedPretty = gsonPretty.toJson(records);
System.out.println(recordsSerializedPretty);
/* PRINTS IN different lines.. I can't paste it here */
// for retrieval
String retrievedArray[][] = gsonPretty.fromJson(recordsSerializedPretty, String[][].class);
for (int i = 0; i < retrievedArray.length; i++) {
for (int j = 0; j < retrievedArray[0].length; j++) {
System.out.print(retrievedArray[i][j]+" ");
}
System.out.println("");
}
// PRINTS THIS
/*
bob 123-pass
erika abc123
richard 123123123
*/
}
}

Categories

Resources