Multi-dimensional array to JSON java / android gson - android

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
*/
}
}

Related

compare multiplication of JSONObjects

So, I have at this point a collections.sort of java values as you can see
and I have two keys that are integers (let's say for the sake of the example that the values of tipo are 1,2 and the values of id are 3 and 4) and I want to sort the result of theyr multiplication:
Something like this:
valA = a.get(KEY_ONE)*a.get(KEY_TWO);
valB = b.get(KEY_ONE)*b.get(KEY_TWO);
Then compare them.
How can I do it??
here is the code that I have at this point.
Collections.sort( jsonValues, new Comparator<JSONObject>() {
private static final String KEY_ONE = "tipo";
private static final String Key_TWO = "id";
#Override
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = (String) a.get(KEY_ONE.toString());
valB = (String) b.get(KEY_ONE.toString());
}
catch (JSONException e) {
//do something
}
return valA.compareTo(valB);
}
});
for (int i = 0; i < jsonArray.length(); i++) {
sortedJsonArray.put(jsonValues.get(i));
}
tvJson.setText(sortedJsonArray.toString());
}
}
Thanks in advance !

How to make Custom ArrayList<customeClass> using JsonObject values?

This is my codes :
JSONObject jsonObject = new JSONObject(response.toString());
JSONObject jsonOb=jsonObject.getJSONObject("LocationMatrix");
Log.e(TAG,"jsonOb :"+jsonOb.toString());
Then print out :
jsonOb :{"45":"NUMANCIA 39-41","44":"DEMESTRE 10","35":"ALIÓ 19","22":"ALFONSO X EL SABIO 8","36":"ROSARI 42","23":"PI I MARGALL 101","33":"MELCHOR DE PALAU 65","24":"ROBRENYO, ESC.A 55","34":"SARDENYA 545","25":"ROBRENYO, ESC.B 55","39":"L´ERAMPPRUNYA 41","26":"ROSSELLO 230","27":" ENRIQUE GIMENEZ 10","37":"CALATRAVA 1-7 E","28":"GRAN VIA CORTS CATALANES 489","38":"AUGUSTA 276","29":"AUTOVIA DE CASTELLDEFELS 135","43":"ROSARIO 37","30":"GANDUXER 72","42":"VALLDEMOSA 64","41":"VALLDEMOSA 62","32":"CONSELL DE CENT 97","40":"VALLDEMOSA 60","31":"SANTA AMELIA 22"}
How to make custom ArrayList using JsonObject values?
For Example :
for (int i = 0; i < jsonOb.length(); i++) {
int mId = intValue;
String mTitle = StringValue;
locationList.add(new Location(mId, mTitle));
}
Where LocationList is one kind of custome ArrayList<Location>.
and Location is one kind of class which parameters id, title.
use gson library
How To Convert Java Object To / From JSON (Gson)
POJO
package com.mkyong.core;
import java.util.ArrayList;
import java.util.List;
public class DataObject {
private int data1 = 100;
private String data2 = "hello";
private List<String> list = new ArrayList<String>() {
{
add("String 1");
add("String 2");
add("String 3");
}
};
//getter and setter methods
#Override
public String toString() {
return "DataObject [data1=" + data1 + ", data2=" + data2 + ", list="
+ list + "]";
}
}
JSON STRING
{"data1":100,"data2":"hello","list":["String 1","String 2","String 3"]}
DataObject obj = gson.fromJson(str, DataObject.class);
link
Try this..
JSONObject jsonObject = new JSONObject(response.toString());
JSONObject jsonOb=jsonObject.getJSONObject("LocationMatrix");
Log.e(TAG,"jsonOb :"+jsonOb.toString());
Iterator i = jsonOb.keys();
while (i.hasNext()) {
try {
String key = i.next().toString();
String j = jsonOb.getString(key);
locationList.add(new Location(Integer.parseInt(key), j));
} catch (JSONException e) {
e.printStackTrace();
}
}

Not getting values from json in android

I am trying to parse my json with:
for(int i = 0; i < json.getJSONArray("JSON").length(); i++) {
String taste = json.getJSONArray("JSON").getJSONObject(i).getString("taste");
String rate = json.getJSONArray("JSON").getJSONObject(i).getString("rate");
int foo = Integer.parseInt(rate);
count = count + foo;
//create object
BeerTastes tempTaste = new BeerTastes(taste, rate);
//add to arraylist
tasteList.add(tempTaste);
Log.d("taste",tempTaste.taste);
Log.d("number",tempTaste.percent);
}
But my logs at the end are not outputting anything at all so I assume I am not parsing my json correctly. The json I am looking at is:
[{"taste":"Bitter","rate":"13"},{"taste":"Malty","rate":"3"},{"taste":"Smooth","rate":"3"},{"taste":"Dry","rate":"1"}]
I think I may be wrong with:
json.getJSONArray("JSON")
because my array doesnt have a name but I it has to take a string...
I find no 'JSON' in your JSON String.So i think you should write like this:
JSONArray jsonArray = new JSONArray(json);
then:
for(int i = 0; i < jsonArray.length(); i++) {
String taste = jsonArray.getJSONObject(i).getString("taste");
String rate = jsonArray.getJSONObject(i).getString("rate");
int foo = Integer.parseInt(rate);
count = count + foo;
//create object
BeerTastes tempTaste = new BeerTastes(taste, rate);
//add to arraylist
tasteList.add(tempTaste);
Log.d("taste",tempTaste.taste);
Log.d("number",tempTaste.percent);
}

Weird Android program error

This code is giving an error saying "error receiving broadcast intent in activity"
I cant find any eroors though...........any ideas ?
i've added the loop condition as seven as i only want the first seven scan results
class WifiReceiver extends BroadcastReceiver {
public void onReceive(Context con, Intent intent) {
sb = new StringBuilder();
wifiList = mainWifi.getScanResults();
for(int i = 0; i < wifiList.size(); i++)
{
sb.append((wifiList.get(i)).SSID.toString());
sb.append(' ');
sb.append('!');
sb.append("\n\n");
}
String net = sb.toString();
if(wifiList.size() > 0)
{
char excl = '!';
int excl1 = excl;
String[] aray = null;
for(int j = 0; j<7; j++)
{
int index = net.indexOf(excl1);
String a = net.substring(0, index);
aray[j] = a;
String temp = net.substring(index+1);
net = temp;
}
String one = aray[0];
String two = aray[1];
String three = aray[2];
String four = aray[3];
String five = aray[4];
String six = aray[5];
String seven = aray[7];
tv1.setText(one);
}
else
{
tv1.setText("No Networks Detected");
}
}
}
PS : I've only added into one TextView as this is a test module
The "aray" array is not being intialized correctly. You need to initialize "aray" before accessing it:
String[] aray = new String[7];
You are also going outside the dimensions of the array. this:
String seven = aray[7];
should be:
String seven = aray[6];
An even better solution would be to use an ArrayList.
ArrayList al = new ArrayList();
al.add(yourString);

Android update sqlite table

I have written Update table using dbAdapter.
public void loadDownloadData() {
SoapPrimitive responsePrimitiveData;
//Loop Table list
for (int i = 0; i < tablesName.size(); i++) {
try {
responsePrimitiveData = soapPrimitiveData(tablesName.get(i));
if (responsePrimitiveData != null) {
try {
String result = responsePrimitiveData.toString();
JSONObject jsonobject = new JSONObject(result);
JSONArray array = jsonobject.getJSONArray("Table1");
int max = array.length();
// Loop each table data
for (int j = 0; j < max; j++) {
JSONObject obj = array.getJSONObject(j);
JSONArray names = obj.names();
StringBuilder strFields = new StringBuilder();
StringBuilder strValues = new StringBuilder();
String[] strToFields = new String[names.length()];
String[] strToFieldsVal = new String[names.length()];
//getting the Json name, values in separate string array
for (int k = 0; k < names.length(); k++) {
String name = names.getString(k);
strToFields[k] = names.getString(k);
String strVal;
if(obj.getString(name)== null){
strVal="";
strToFieldsVal[k]="";
}else{
if(obj.getString(name).equals(" ")){
strVal="";
strToFieldsVal[k]="";
}else{
String tmp1 = obj.getString(name).replaceAll("\\s+", " ");
String tmp = tmp1.replaceAll("\\s+", " ");
strVal =tmp.replaceAll("\\s+", " ");
strToFieldsVal[k]=strVal;
}
}
strFields.append(name + ",");
strValues.append(strVal+",");
} //end of json for loop
strFields.deleteCharAt(strFields.length() - 1);
strValues.deleteCharAt(strValues.length() - 1);
if(getTableUpdateType(tablesName.get(i)).equals("1")){
String actualtable = getAndroidTablename(tablesName.get(i));
if(isTableRecords(tablesName.get(i))){
String[] strWhereField = getTablePrimaryKey(tablesName.get(i),strBusinessUnit);
String[] strWhereFieldVal = new String[strWhereField.length];
StringBuilder whereFields = new StringBuilder();
for (int a = 0; a < strWhereField.length; a++) {
strWhereFieldVal[a] = obj.getString(strWhereField[a]);
whereFields.append(strWhereField[a] + "= ? and ");
}
whereFields.delete(whereFields.length() - 4, whereFields.length());
updateTableRecords(actualtable, strToFields, strToFieldsVal,whereFields.toString() ,strWhereFieldVal);
}else{
insertTableRecords(actualtable, strToFields, strToFieldsVal);
}
}else if(getTableUpdateType(tablesName.get(i)).equals("2")){
}else if(getTableUpdateType(tablesName.get(i)).equals("3")){
}else{
}
}//end of each table data
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}
and I called like update method:
public void updateTableRecords(String strTableName, String[] strToFields, String[] strValues,String strWhereField ,String[] strWhereFieldVal){
DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(DownlaodTableActivity.this);
dbAdapter.openDataBase();
ContentValues initialValues = new ContentValues();
for(int i=0 ;i<strToFields.length;i++){
initialValues.put(strToFields[i],strValues[i]);
}
long n = dbAdapter.updateRecordsInDB(strTableName, initialValues, strWhereField, strWhereFieldVal);
System.out.println( " -- n--- " + n);
Toast.makeText(DownlaodTableActivity.this, n+" rows updated", Toast.LENGTH_SHORT).show();
}
I want to generate update statement dynamic way. From These code I put Where part also.But I did not generate where clause.
see :
UPDATE strTableName SET ExecutiveCode=?, FreeIssuePrefix=?, DisPaySchedulePrefix=?, NextFreeIssueNo=?, NextReturnNo=?, UploadedType=?, DisNextFOCNo=?, DisNextFreeIssueNo=?
Please help me How to give the Where clase(Here I gave String & arguments as string array)
Thanks in advance...
try like this
dbAdapter.updateRecordsInDB(strTableName, initialValues,""+whereField+"='"+whereFieldValue+"'",null);
if your whereField field's type is number then don't use ''
If you have to compare with multiple values use
String where="";
for(int i=0;i<strWhereField.length();i++)
{
where=where+whereField[i]+"='"+strWhereFieldValue[i]+"'"
if(i<(strWhereField.length()-1)) where=where+" and"
}
dbAdapter.updateRecordsInDB(strTableName, initialValues,where,null);

Categories

Resources