I'm begginer develop android.
I'm confuse. Because I didn't know to convert JSON to be view at Edit View (for example).
many totorial just view at Log.
this, my JSON file
EditText txt1 = (EditText) findViewById(R.id.Text1);
RestClient client = new RestClient("http://192.168.2.79/restserver/index.php/api/example/users");
//client.AddParam("id", "1"); //parameter
client.AddParam("format", "json"); //parameter format
client.AddHeader("GData-Version", "2"); //header
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String response = client.getResponse();
Log.i("respon",response);
//Toast.makeText(this, "json : "+ response, 1).show();
//create json creation
try {
JSONObject json = new JSONObject(response);
Log.i("respon","<jsonobject>\n"+json.toString()+"\n</json>");
//Log.i("respon","<jsonobject>\n"+json.t
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
//try 1
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
String[] id = new String[valArray.length()];
String[] name = new String[valArray.length()];
String Id,Name;
for(int i=0;i<valArray.length();i++) {
Log.i("respon","<jsonname"+i+">\n"+nameArray.getString(i)+"\n</jsonname"+i+">\n"
+"<jsonvalue"+i+"\n"+valArray.getString(i)+"\n</jsonvalue"+i+">");
//coba
JSONObject obj = valArray.getJSONObject(i);
id[i] = obj.getString("id");
name[i] = obj.getString("name");
//wanna show at EditView, ect (but I can't)
Toast.makeText(this, "id : " + " ,name : ", 1).show();
txt1.setText("id : " + id + " ,name : "+name);
}
how can to solve json to view not only at log. but also at object (widget android).
thanx alot guys....
I think your not able to get data from JSON go through with the following code.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("LINK");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
int statuscode = statusLine.getStatusCode();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(is, "UTF8"), 16);
stringBuilder = new StringBuilder();
stringBuilder.append(bufferedReader.readLine() + "\n");
String line = "0";
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
is.close();
Strign result = stringBuilder.toString();
JSONArray jArrayTemp = new JSONArray(result);
JSONObject json_data = null;
userID[i] = json_data.getString("UserID");
userName[i] = json_data.getString("UserName");
userLoginID[i] = json_data.getString("UserLoginID");
userPassword[i] = json_data.getString("UserPassword");
Try the above code.
If can take the help of below link also::
http://www.vogella.de/articles/AndroidJSON/article.html
Related
I have a json response as shown below
[
{
"id": "1",
"name": "b day",
"date": "2015-12-08",
"start_time": "00:50:02",
"end_time": "05:00:00"
},
{
"id": "2",
"name": "game",
"date": "2015-11-18",
"start_time": "00:00:02",
"end_time": "09:10:00"
}
]
My android code to retrieve json is given below
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
//success
BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
}
You can get JSONArray like below.
JSONArray jsonArray = new JSONArray(responseString);
From array you can get JSONObject like below.
for(int i = 0 ; i< jsonArray.length() ; i++){
// This will get first JSONObject from JSONArray.
JSONObject jObject = jsonArray.getJSONObject(i);
// Get all key from array using JSONObject.
String id = jObject.getString("id");
String name = jObject.getString("name");
String date = jObject.getString("date");
String startTime = jObject.getString("start_time");
String endTime = jObject.getString("end_time");
}
Try this:
try
{
JSONObject issueObj = new JSONObject(JSONString);
Iterator iterator = issueObj.keys();
while (iterator.hasNext())
{
String key = (String) iterator.next();
JSONObject issue = issueObj.getJSONObject(key);
int pubKey = Integer.valueOf(issue.optString("id"));
mylist.add(pubKey);
JSONObject json = new JSONObject(JSONString);
JSONObject jArray = json.getJSONObject(String.valueOf(pubKey));
nameString = jArray.getString("name");
dateString = jArray.getString("date");
start_timeString = jArray.getString("start_time");
end_timeString = jArray.getString("end_time");
}
} catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Use this code
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
}
json = response.toString();
JSONArray jsonArray = new JSONArray(json);
ArrayList<String> al_ids=new ArrayList<String>();
Arraylist<String> al_name=new ArrayList<String>();
Arraylist<String> al_date=new ArrayList<String>();
Arraylist<String> al_start_time=new ArrayList<String>();
Arraylist<String> al_end_time=new ArrayList<String>();
for(int i = 0 ; i< jsonArray.length() ; i++){
// This will get first JSONObject from JSONArray.
JSONObject jObject = jsonArray.getJSONObject(i);
// Get all key from array using JSONObject.
String id = jObject.getString("id");
String name = jObject.getString("name");
String date = jObject.getString("date");
String startTime = jObject.getString("start_time");
String endTime = jObject.getString("end_time");
al_ids.add(id);
al_name.add(name);
al_date.add(date);
al_start_time.add(startTime);
al_end_time.add(endTime);
}
//here you can set text to Your TextView by getting position of arraylist
I'trying to Parsing JSOn object but sometime it runs properly sometime getting followoing error:
org.json.JSONException: Value null at VesselList of type
org.json.JSONObject$1 cannot be converted to JSONArray
public void getCompanyDeatails()
{
String strUrl_companyDeatls = "http://103.24.4.60/CLASSNK1/MobileService.svc/Get_Company/Sync_Time/"+strSync_Time+"/Authentication_Token/"+str_Authentication_Token;
Log.e("strUrl_companyDeatls ", " = " + strUrl_companyDeatls);
InputStream inputStream = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(strUrl_companyDeatls));
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null)
strResult = convertInputStreamToString(inputStream);
else
strResult = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
String jsonStr = strResult;
Log.e("jsonStr ", " = " + jsonStr);
if (jsonStr != null)
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String jsonResult = jsonObj.toString().trim();
Log.e("jsonResult ", " = " + jsonResult);
JSONObject companyList = jsonObj.getJSONObject("Get_CompanyResult");
Log.e("companyList ", " = " + companyList.toString());
JSONArray jarr = jsonObj.getJSONArray("CompanylList");
Log.e("jarr ", " = " + jarr.toString());
for (int i = 0; i < jarr.length(); i++) {
JSONObject jobCompanyDetails = jarr.getJSONObject(i);
str_CompanyId = jobCompanyDetails.getString("Company_ID");
str_CompanyName = jobCompanyDetails.getString("Company_Name");
Log.e("str_CompanyId ", " = " + str_CompanyId);
Log.e("str_CompanyName ", " = " + str_CompanyName);
if (dbhelper.isTitleExist(str_CompanyId)) {
//Upadte
dbhelper.updatedetails(str_CompanyId, str_CompanyName);
Log.e("Data updated in ", "Company Table !!");
} else {
//insert
dbhelper.insertCompany(str_CompanyId, str_CompanyName);
Log.e("Data inserted in ", "Company Table !!");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
this is my JSON String
{"Get_CompanyResult":{"CompanylList":[{"Company_ID":93,"Company_Name":"SeaChange"},{"Company_ID":97,"Company_Name":"VM 2"}],"Sync_Time":"2015-09-11 12:44:17.533"}}
Is this code is right?
Here:
JSONArray jarr = jsonObj.getJSONArray("CompanylList");
line causing issue because CompanylList JSONArray is inside Get_CompanyResult JSONObject instead of main which is jsonObj.
Get CompanylList JSONArray from companyList JSONObject:
JSONArray jarr = companyList.getJSONArray("CompanylList");
Change your code according to here :
public void getCompanyDeatails() {
String strUrl_companyDeatls = "http://103.24.4.60/CLASSNK1/MobileService.svc/Get_Company/Sync_Time/" + strSync_Time + "/Authentication_Token/" + str_Authentication_Token;
Log.e("strUrl_companyDeatls ", " = " + strUrl_companyDeatls);
InputStream inputStream = null;
String strResult = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet("strUrl_companyDeatls"));
inputStream = httpResponse.getEntity().getContent();
// strResult = "{\\\"Get_CompanyResult\\\":{\\\"CompanylList\\\":[{\\\"Company_ID\\\":93,\\\"Company_Name\\\":\\\"SeaChange\\\"},{\\\"Company_ID\\\":97,\\\"Company_Name\\\":\\\"VM 2\\\"}],\\\"Sync_Time\\\":\\\"2015-09-11 12:44:17.533\\\"}}";
String jsonStr=null;
if (inputStream != null) {
strResult = convertInputStreamToString(inputStream);
jsonStr = strResult;
}
Log.e("jsonStr ", " = " + jsonStr);
if (jsonStr != null) {
JSONObject jsonObj = new JSONObject(jsonStr);
String jsonResult = jsonObj.toString().trim();
Log.e("jsonResult ", " = " + jsonResult);
JSONObject companyList = jsonObj.getJSONObject("Get_CompanyResult");
Log.e("companyList ", " = " + companyList.toString());
JSONArray jarr = companyList.getJSONArray("CompanylList");
Log.e("jarr ", " = " + jarr.toString()); // error was here. You need to use companyList json object because it contains company list.
for (int i = 0; i < jarr.length(); i++) {
JSONObject jobCompanyDetails = jarr.getJSONObject(i);
String str_CompanyId = jobCompanyDetails.getString("Company_ID");
String str_CompanyName = jobCompanyDetails.getString("Company_Name");
Log.e("str_CompanyId ", " = " + str_CompanyId);
Log.e("str_CompanyName ", " = " + str_CompanyName);
// if (dbhelper.isTitleExist(str_CompanyId)) {
// //Upadte
// dbhelper.updatedetails(str_CompanyId, str_CompanyName);
// Log.e("Data updated in ", "Company Table !!");
// } else {
//
// //insert
// dbhelper.insertCompany(str_CompanyId, str_CompanyName);
// Log.e("Data inserted in ", "Company Table !!");
// }
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
}
Note :
There is no need to use nested try and catch.
For 'strResult = "Did not work!";', always make sure that every
exception handled well (at checkpoint of jsonstr is null or not you
can not identify error occurred at parsing input stream can lead to
serious bugs).
HttpClient is deprecated so make sure you use latest version of any
third party library like Volley or Retrofit for network
operation and GSON for parsing response. It will minimize your
efforts.
Thanks.
When I click on a button within my listview, I call a function where I send a value clearly depending on which button is clicked. When I get a positive response function of the item field changes value, in the first instance is to validado = 0 and if you click on the button changes to validado = 1. If validated this to 1, the button should have a background image as warning that this item is already validated. All this works well for me at first, but if I click on any button, regardless of how many items are on my list, always changes the item to which it is clicked and also the first item on my list. Pretty funny when my data base both locally and in my server, the validated value of the first item remains 0
getView in my adapter
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.lista_validacion_multiple, null);
holder = new ViewHolder();
holder.txtNombre = (TextView)convertView.findViewById(R.id.txtNombre);
holder.txtAsiento = (TextView)convertView.findViewById(R.id.txtAsiento);
holder.txtTicket = (TextView)convertView.findViewById(R.id.txtTicket);
holder.txtNumero = (TextView)convertView.findViewById(R.id.txtNumero);
holder.btn = (Button)convertView.findViewById(R.id.button1);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtNombre.setText("Nombre :"+rowItem.getNombre());
holder.txtTicket.setText("Ticket :"+rowItem.getTicket());
if (!rowItem.getAsiento().equals("") && !rowItem.getAsiento().equals("null") && rowItem.getAsiento() != null) {
holder.txtAsiento.setText("Asiento :"+rowItem.getAsiento());
}
if (!rowItem.getNumero().equals("") && !rowItem.getNumero().equals("null") && rowItem.getNumero() != null) {
holder.txtNumero.setText("Número :"+rowItem.getNumero());
}
System.out.println("item "+rowItem.getId_inscripcion()+" validado = "+rowItem.getValidado());
if(rowItem.getValidado()==1){
System.out.println("ENTRO");
holder.btn.setBackgroundResource(R.drawable.icon_big_alert);
holder.btn.setText("");
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((int)LayoutParams.WRAP_CONTENT, (int)LayoutParams.WRAP_CONTENT);
params.width = 50;
params.height = 50;
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
holder.btn.setLayoutParams(params);
}else{
holder.btn.setTag(position);
holder.btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position=(Integer)v.getTag();
RowItem item_click = getItem(position);
Connection cn = new Connection();
SessionManager manager = new SessionManager();
BaseDeDatos nueva = new BaseDeDatos();
JSONObject json = new JSONObject();
if(cn.isNetworkAvailable(parent.getContext())){
String nombreCliente = manager.getValue(parent.getContext(), "nombreCliente");
String user = manager.getValue(parent.getContext(), "nombreUser");
String folioEvento = manager.getValue(parent.getContext(), "folioEvento");
String codigoEvento = manager.getValue(parent.getContext(), "codigoEvento");
String seleccionValidadora = manager.getValue(parent.getContext(), "opcionVerificadora");
String nombreUser = manager.getValue(parent.getContext(), "nombreUser");
String hashUser = manager.getValue(parent.getContext(), "hashUsuario");
String URL_TICKET = Config.URL_BASE + nombreCliente
+ "/" + Config.URL_VALIDACION_TICKET
+ nombreUser + "/" + hashUser + "/"
+ folioEvento + "/" + item_click.getHash()
+ "/0/";
System.out.println(URL_TICKET);
if (manager.getValue(parent.getContext(),
"checkin") != null) {
int id_checkin = nueva.idCheckin(parent.getContext(), manager.getValue(parent.getContext(),"checkin"));
String url = URL_TICKET + id_checkin;
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader("content-type",
"application/json");
try {
// Construimos el objeto cliente en formato
// JSON
JSONObject dato = new JSONObject();
StringEntity entity = new StringEntity(
dato.toString());
post.setEntity(entity);
HttpResponse resp = httpClient
.execute(post);
String respStr = EntityUtils.toString(resp
.getEntity());
JSONObject respJSON = new JSONObject(
respStr);
json = respJSON;
} catch (Exception ex) {
Log.e("ServicioRest", "Error!", ex);
}
} else {
String url = URL_TICKET;
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader("content-type",
"application/json");
try {
// Construimos el objeto cliente en formato
// JSON
JSONObject dato = new JSONObject();
StringEntity entity = new StringEntity(
dato.toString());
post.setEntity(entity);
HttpResponse resp = httpClient
.execute(post);
String respStr = EntityUtils.toString(resp
.getEntity());
JSONObject respJSON = new JSONObject(
respStr);
json = respJSON;
} catch (Exception ex) {
Log.e("ServicioRest", "Error!", ex);
}
}
System.out.println(json);
}else{
}
}
});
}
return convertView;
}
I show logs to show that the value is still 0
08-07 13:39:21.890: I/System.out(14317): item 936 validado = 0
08-07 13:39:21.890: I/System.out(14317): item 937 validado = 0
08-07 13:39:21.890: I/System.out(14317): item 938 validado = 0
This log out when you first enter the view of the listview, then I will validate an inscription, whatever, and this is what I get
08-07 13:44:08.300: I/System.out(14317): item 936 validado = 0
08-07 13:44:08.300: I/System.out(14317): item 937 validado = 1
08-07 13:44:08.305: I/System.out(14317): item 938 validado = 0
That's all right, except the first item plus the charge to the button that validates an image which I just want to be charged to the element that is in rowItem.getValidado()==1
EDIT
I answered my question.
So you click on 1 item on the ListView it changes it look (which is intended), because your value changes to 1. But no matter what, the first Visible item in the ListView also changes (unintended)?
I am no expert but I gather you have an issue with your ViewHolder. Try removing the ViewHolder logic and see if you still get the issue (for testing). ListView is tricky with the recycling of Views and repopulating them with new data. Might even have an issue with your getItem(). But I suspect it's the ViewHolder logic.
Also do you need to declare that Inflater every time getView() is called? prob ought to move that up to Constructor and just instantiate it in the getView().
The error was where the code to and not how.
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.lista_validacion_multiple, null);
holder = new ViewHolder();
holder.txtNombre = (TextView)convertView.findViewById(R.id.txtNombre);
holder.txtAsiento = (TextView)convertView.findViewById(R.id.txtAsiento);
holder.txtTicket = (TextView)convertView.findViewById(R.id.txtTicket);
holder.txtNumero = (TextView)convertView.findViewById(R.id.txtNumero);
holder.btn = (Button)convertView.findViewById(R.id.button1);
holder.txtNombre.setText("Nombre :"+rowItem.getNombre());
holder.txtTicket.setText("Ticket :"+rowItem.getTicket());
if (!rowItem.getAsiento().equals("") && !rowItem.getAsiento().equals("null") && rowItem.getAsiento() != null) {
holder.txtAsiento.setText("Asiento :"+rowItem.getAsiento());
}
if (!rowItem.getNumero().equals("") && !rowItem.getNumero().equals("null") && rowItem.getNumero() != null) {
holder.txtNumero.setText("Número :"+rowItem.getNumero());
}
System.out.println("item "+rowItem.getId_inscripcion()+" validado = "+rowItem.getValidado());
if(rowItem.getValidado()==1){
holder.btn.setBackgroundResource(R.drawable.icon_big_alert);
holder.btn.setText("");
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((int)LayoutParams.WRAP_CONTENT, (int)LayoutParams.WRAP_CONTENT);
params.width = 50;
params.height = 50;
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
holder.btn.setLayoutParams(params);
}else{
holder.btn.setTag(position);
holder.btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position=(Integer)v.getTag();
RowItem item_click = getItem(position);
Connection cn = new Connection();
SessionManager manager = new SessionManager();
BaseDeDatos nueva = new BaseDeDatos();
JSONObject json = new JSONObject();
if(cn.isNetworkAvailable(parent.getContext())){
String nombreCliente = manager.getValue(parent.getContext(), "nombreCliente");
String user = manager.getValue(parent.getContext(), "nombreUser");
String folioEvento = manager.getValue(parent.getContext(), "folioEvento");
String codigoEvento = manager.getValue(parent.getContext(), "codigoEvento");
String seleccionValidadora = manager.getValue(parent.getContext(), "opcionVerificadora");
String nombreUser = manager.getValue(parent.getContext(), "nombreUser");
String hashUser = manager.getValue(parent.getContext(), "hashUsuario");
String URL_TICKET = Config.URL_BASE + nombreCliente
+ "/" + Config.URL_VALIDACION_TICKET
+ nombreUser + "/" + hashUser + "/"
+ folioEvento + "/" + item_click.getHash()
+ "/0/";
System.out.println(URL_TICKET);
if (manager.getValue(parent.getContext(),
"checkin") != null) {
int id_checkin = nueva.idCheckin(parent.getContext(), manager.getValue(parent.getContext(),"checkin"));
String url = URL_TICKET + id_checkin;
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader("content-type",
"application/json");
try {
// Construimos el objeto cliente en formato
// JSON
JSONObject dato = new JSONObject();
StringEntity entity = new StringEntity(
dato.toString());
post.setEntity(entity);
HttpResponse resp = httpClient
.execute(post);
String respStr = EntityUtils.toString(resp
.getEntity());
JSONObject respJSON = new JSONObject(
respStr);
json = respJSON;
} catch (Exception ex) {
Log.e("ServicioRest", "Error!", ex);
}
} else {
String url = URL_TICKET;
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader("content-type",
"application/json");
try {
// Construimos el objeto cliente en formato
// JSON
JSONObject dato = new JSONObject();
StringEntity entity = new StringEntity(
dato.toString());
post.setEntity(entity);
HttpResponse resp = httpClient
.execute(post);
String respStr = EntityUtils.toString(resp
.getEntity());
JSONObject respJSON = new JSONObject(
respStr);
json = respJSON;
} catch (Exception ex) {
Log.e("ServicioRest", "Error!", ex);
}
}
System.out.println(json);
}else{
}
}
});
}
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
return convertView;
}
I am trying to send the send voice data immediately to local server using audiorecord.. I am able to record the voice & stores it in SDcard.. but I want to store audio voice in buffer & sends immediate to the server using HTTP POST. How can I proceed.got struck..? I am creating this app in ICS i.e android 4.0.3 version.
got the solutions.. sending voice data as a jsonarray to server & recieve back as a json object. convert back jsonobject to short array n write to audiotrack then play back. here is sample code working.
public void SendAudio() {
String LOG_TAG = null;
long SAMPLE_INTERVAL = 1;
Log.e(LOG_TAG, "start send thread, thread id: ");
int bytes_read = 0;
int bytes_count = 0;
br = br % 5;
br++;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpClient httpclient_recv = new DefaultHttpClient();
// System.out.println("mmdata--------- " + value);
HttpPost httppost = new HttpPost("http://192.168.1.39/call");
HttpPost httppost_recv = new HttpPost("http://192.168.1.39/ping");
// Unix time stamp
long unixTime = System.currentTimeMillis();
String timestamp = String.valueOf(unixTime);
// Json Format
JSONObject holder = new JSONObject();
JSONObject holder_recv = new JSONObject();
JSONArray jArray = new JSONArray();
try {
holder.put("UserId", "1");
holder.put("TimeStamp", timestamp);
holder.put("SessionId", "1");
Queue<byte[]> qArray = new LinkedList<byte[]>();
qArray.add(bData);
byte[] tmparr = qArray.poll();
for (int i = 0; i < tmparr.length; i++) {
jArray.put(i, tmparr[i]);
}
System.out.println("send audio -- " + jArray);
holder.put("MMData", jArray.toString());
System.out.println("JSON -- " + holder.toString());
holder_recv.put("UserId", "1");
holder_recv.put("TimeStamp", timestamp);
holder_recv.put("SeqNo", "100");
holder_recv.put("SessionId", "0");
} catch (JSONException e1) {
e1.printStackTrace();
}
System.out.println("time " + timestamp);
try {
StringEntity se = new StringEntity(holder.toString());
StringEntity se_recv = new StringEntity(holder_recv.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
se_recv.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
httppost.setEntity(se);
httppost_recv.setEntity(se_recv);
HttpResponse response = httpclient.execute(httppost);
HttpResponse response_recv = httpclient_recv
.execute(httppost_recv);
if (response_recv != null) {
t = EntityUtils.toString(response_recv.getEntity());
System.out.println("after response -- " + t);
Queue<String> qe = new LinkedList<String>();
qe.add(t);
t = null;
System.out.println("on play side ...1 ");
try {
System.out.println("on play side ...2 ");
JSONObject get = new JSONObject(qe.poll());
// JSONArray jArray_recv = get.getJSONArray("MMData");
String mmdata = (String) get.get("MMData");
JSONObject temp2 = new JSONObject("{ \"MMData\" : "
+ mmdata + "}");
JSONArray jArray_recv = temp2.getJSONArray("MMData");
System.out.println("jsonarray -- " + jArray_recv);
// String timeData = (String) get.get("TimeStamp");
String userData = (String) get.get("UserId");
// String sessionId = (String) get.get("TimeStamp");
System.out.println("on play side ...3 ");
// if (Long.valueOf(timeData) > ts)
{
// ts = Long.valueOf(timeData);
System.out.println("on play side ...4 ");
if (at != null) {
System.out.println("on play side ...5 ");
byte[] shortArray = new byte[jArray_recv
.length()];
for (int i = 0; i < jArray_recv.length(); i++) {
shortArray[i] = (byte) jArray_recv
.getInt(i);
}
jArray_recv = null;
System.out.println("recv audio -- " + br
+ " ----" + shortArray);
byte[] temp = shortArray;
shortArray = null;
byte[] bArray = temp;
temp = null;
byte[][] newbarray = new byte[5][1024];
newbarray[br - 1] = bArray;
byte[] sbayyay = new byte[1024 * 5];
System.arraycopy(bArray, 0, sbayyay,
(br - 1) * 1024, bArray.length);
if (br == 5) {
for (int i = 0; i < 5; i++) {
System.out.println("in for---" + i
+ "----" + sbayyay.length);
// System.arraycopy(newbarray[i], 0,
// sbayyay, i * 1024,
// bArray.length);
}
System.out.println("bsbsbsbs --- "
+ new String(sbayyay));
at.write(sbayyay, 0, sbayyay.length);
at.play();
}
}
else {
Log.d("Audio",
"audio track is not initialised ");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
System.out.println("Exception");
e.printStackTrace();
}
bytes_count += bytes_read;
Log.d(LOG_TAG, "bytes_count : " + bytes_count);
Thread.sleep(SAMPLE_INTERVAL, 0);
} catch (InterruptedException ie) {
Log.e(LOG_TAG, "InterruptedException");
}
}
I have a web service returning the following string verbatim:
"{\"type\":\"youtube\", \"data\":\"http://66.84.12.156/android/?x=12&uid=4&lati=40.73972412&longi=-73.99234962&y=14&pixel_id=7224&pid=4&surface_id=7&fn=showHTML&data_id=7224&data=kT2UQ8TYMpk\",\"pixel_id\":\"471\",\"x\":\"12\",\"y\":\"14\",\"pid\":\"4\",\"surface_id\":\"7\",\"data_id\":\"7224\",\"user_id\":\"4\"}"
Code looks lke:
dataScanner.client = new DefaultHttpClient();
dataScanner.post = new HttpPost("http://someurl/somepage.php");
post.setEntity(new UrlEncodedFormEntity(userKV));
Log.d("DST Scanner", "post string:" + post.toString());
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line);
}
Log.d("DST Scanner", "Post Response (string)" + builder.toString());
//JSONTokener tokener = new JSONTokener(builder.toString());
finalResult = new JSONObject(builder.toString());
I've tried many different formats (escaped quotes, unescaped quotes, no surrounding quotes, escaped forward slashes), but I keep getting this error:
org.json.JSONException: Value {"type":"youtube", "data":"http://66.84.12.156/android/?x=12&uid=4&lati=40.73972412&longi=-73.99234962&y=14&pixel_id=7224&pid=4&surface_id=7&fn=showHTML&data_id=7224&data=kT2UQ8TYMpk","pixel_id":"471","x":"12","y":"14","pid":"4","surface_id":"7","data_id":"7224","user_id":"4"} of type java.lang.String cannot be converted to JSONObject
Everything looks fine to me, but I've been looking at this so long I wouldn't be surprised if there's some silly thing I'm doing..
I'm new to json, but all of my JSON start and end with "[" and "]" and I use PHP to echo out the json_encode method.
On Android side i use:
try {
URL pHH = new URL("http://192.168.1.5/somephp.php");
URLConnection WC = pHH.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(WC.getInputStream()));
String line;
while((line = in.readLine()) != null){
JSONArray ja = new JSONArray(line);
for (int i = 0; i < ja.length(); i++){
JSONObject jo = (JSONObject) ja.get(i);
items[i] = jo.getString("title");
thumbnails[i] = jo.getString("thumb");
links[i] = jo.getString("link");
}
}
char[] utf8 = null;
StringBuilder properString = new StringBuilder("");
utf8 = Response.toCharArray();
for (int i = 0; i < utf8.length; i++) {
if ((int) utf8[i] < 65000) {
properString.append(utf8[i]);
}
}
System.out.println("Response of Login::"
+ properString.toString());