I created two activities one contains some text fields which accepts data. From other activity(Async Task) this data is sent to the server and gets the response from the server.
I am able to log the response but unable to store that response in variable and user in other activities. Is there any way to do that?
Here is one activity,
RegisterDevice.java
package sys.darpan.tracking;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class RegisterDevice extends Activity{
EditText regEmail, regPassword, regImei, regDeviceName, regVehicleNumber;
Button regButton;
AsyncRegisterDevice asd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_device);
regEmail = (EditText)findViewById(R.id.regEmail);
regPassword = (EditText)findViewById(R.id.regPassword);
regVehicleNumber = (EditText)findViewById(R.id.regVehicleNum);
regImei = (EditText)findViewById(R.id.regImei);
regDeviceName = (EditText)findViewById(R.id.regDeviceName);
regButton = (Button)findViewById(R.id.regButton);
regImei.setText("165465416416416");
regDeviceName.setText("GT-I9300");
regButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerDevice();
}
});
}
protected void registerDevice(){
asd = new AsyncRegisterDevice();
String email = regEmail.getText().toString();
String password = regPassword.getText().toString();
String imei = regImei.getText().toString();
String deviceName = regDeviceName.getText().toString();
String vehicleNo = regVehicleNumber.getText().toString();
String aobj[] = new String[5];
aobj[0] = email;
aobj[1] = password;
aobj[2] = vehicleNo;
aobj[3] = imei;
aobj[4] = deviceName;
asd.execute(aobj);
}
}
Here is Async Task,
package sys.darpan.tracking;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.util.Log;
public class AsyncRegisterDevice extends AsyncTask<String, String, String> {
String sb;
String finalResult;
#Override
protected String doInBackground(String... params) {
String email = params[0];
String password = params[1];
String vnumber = params[2];
String imei = params[3];
String deviceName = params[4];
DefaultHttpClient defaulthttpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://logicvibes.com/vts/register-device.php");
ArrayList<BasicNameValuePair> arraylist = new ArrayList<BasicNameValuePair>(5);
arraylist.add(new BasicNameValuePair("email", email));
arraylist.add(new BasicNameValuePair("pass", password));
arraylist.add(new BasicNameValuePair("vno", vnumber));
arraylist.add(new BasicNameValuePair("imei", imei));
arraylist.add(new BasicNameValuePair("dname", deviceName));
try
{
httppost.setEntity(new UrlEncodedFormEntity(arraylist));
httppost.getAllHeaders();
}
catch (UnsupportedEncodingException unsupportedencodingexception)
{
unsupportedencodingexception.printStackTrace();
}
try {
// HttpResponse is an interface just like HttpPost.
//Therefore we can't initialize them
HttpResponse httpResponse = defaulthttpclient.execute(httppost);
// According to the JAVA API, InputStream constructor do nothing.
//So we can't initialize InputStream although it is not an interface
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
sb = stringBuilder.toString();
Log.d("Custom resp: ", sb);
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String sb) {
Log.d("RESULT", "Result : " + sb);//this returns NULL
finalResult = sb;
}
public String getFinalResult() {
return finalResult;
}
}
I searched a lot but no luck, please tell me the proper way to do this.
Solved it by using,
try {
asd.execute(aobj).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
The main thread waits until the async task finished processing. (good for short processes)
Related
I want to retrieve weather data from an API as JSON, but it isn't working. How do I pull in weather data, such as a 5-day forecast, into a text view?
My code is below, but I need to somehow adapt it to pass in the JSON 5-day weather forecast and put that into a text view.
package mytweets.mytweets;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MytweetsActivity extends Activity {
// we are reading weathe
final String URL `enter code here`="http://api.openweathermap.org/data/2.5/forecast/daily?q,gb&mode=json&units=metric&cnt=5&APPID=xxxxxxxxxxxxxxxx";
final String Consumer_Key = "mPfkAwVuuiVYeuZWdHAMzQ"; // change this if it does not work, you can get this from your twitter account at https://dev.twitter.com/apps/new
final String Consumer_Secret = "bkmiQqellGg9jnJFj41E8zukYSNk0FX1W7v1nU376rE"; // change this if it does not work, you can get this from your twitter account at https://dev.twitter.com/apps/new
JSONArray tweets = null; //an array of tweets
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mytweets);
Button btn_token = (Button)findViewById(R.id.get_token);
btn_token.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new GetTokenTask().execute();
}
});
Button btn_feed = (Button)findViewById(R.id.get_tweets);
btn_feed.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView txt_token = (TextView)findViewById(R.id.txt_token);
String token = txt_token.getText().toString();
new GetTweetsTask().execute(token, URL);
}
});
}
protected class GetTokenTask extends AsyncTask<Void, Void, String> { // the class extends AsynTask in order to run as a thread in the background
#Override
protected String d
try {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("https://api.twitter.com/oauth2/token"); //asks for a token
String apiString = Consumer_Key + ":" + Consumer_Secret;
String authorization = "Basic " + Base64.encodeToString(apiString.getBytes(), Base64.NO_WRAP); // twitter ants the authorization in bytes
httppost.setHeader("Authorization", authorization);
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httppost.setEntity(new StringEntity("grant_type=client_credentials"));
InputStream inputStream = null;
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); // reading the input stream
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
return sb.toString();
}catch (Exception e){
Log.e("GetTokenTask", "Error:" + e.getMessage());
return null;
}
}
#Override
protected void onPostExecute(String jsonText){
try {
JSONObject root = new JSONObject(jsonText);
String bearer_token = root.getString("access_token");
TextView txt = (TextView)findViewById(R.id.txt_token);
txt.setText(bearer_token);
}catch (Exception e){
Log.e("GetTokenTask", "Error:" + e.getMessage());
}
}
}
protected class GetTweetsTask extends AsyncTask<String, Void, String> { //the class is run as a thread in the background to get the tweets
#Override
protected String doInBackground(String... params) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpGet httpget = new HttpGet(params[1]);
httpget.setHeader("Authorization", "Bearer " + params[0]);
httpget.setHeader("Content-type", "application/json"); //json content type
InputStream inputStream = null;
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
return sb.toString();
}catch (Exception e){
Log.e("GetFeedTask", "Error:" + e.getMessage());
return null;
}
}
#Override
protected void onPostExecute(String jsonString){
try {
TextView txt_tweets = (TextView)findViewById(R.id.txt_tweets);
JSONObject forecastJson = new JSONObject(jsonString);
JSONArray forecastArray = forecastJson.getJSONArray("list");
String txt = "";
int i;
double minTemp, maxTemp;
// we are going to parse the json string and only display created_at and text. You can decide to display more objects if you want.
for (i=0;i<tweets.length();i++)
{
JSONObject dailyForecast = forecastArray.getJSONObject(i);
JSONObject tempObject = dailyForecast.getJSONObject("temp");
minTemp = tempObject.getDouble("min");
maxTemp = tempObject.getDouble("max");
//add these minTemp and maxTemp to array or the
//way you want to use
txt_tweets.setText(txt);
txt += "------------\n"; //separtors, check the output
}
}catch (Exception e){
Log.e("GetFeedTask", "Error:" + e.getMessage());
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mytweets, menu);
return true;
}
}
This is the JSON format of weather data:
city: {
id: 2643743,
name: "London",
coord: {
lon: -0.12574,
lat: 51.50853
},
country: "GB",
population: 0
},
cod: "200",
message: 0.0268,
cnt: 5,
list: [
{
dt: 1448535600,
temp: {
day: 8.58,
min: 8.58,
max: 9.18,
night: 9.18,
eve: 8.58,
morn: 8.58
},
pressure: 1025.14,
humidity: 95,
weather: [
{
id: 500,
main: "Rain",
description: "light rain",
icon: "10d"
}
],
speed: 3.67,
deg: 224,
clouds: 92,
rain: 0.35
},
{},
{},
{},
{}
]
Now to access the weather data (e.g. min and max temp) you need to parse as below:
JSONObject forecastJson = new JSONObject(jsonString);
JSONArray forecastArray = forecastJson.getJSONArray("list");
double minTemp, maxTemp;
for(int i = 0; i < forecastArray.length(); i++) {
JSONObject dailyForecast = forecastArray.getJSONObject(i);
JSONObject tempObject = dailyForecast.getJSONObject("temp");
minTemp = tempObject.getDouble("min");
maxTemp = tempObject.getDouble("max");
//add these minTemp and maxTemp to array or the
//way you want to use
}
If you have further doubts, please let me know.
Use arrays and objects and make sure you have a json parser
Hi (fresher to andorid)
I'm developing an android application which will use the webservice which should accept 1 parameter from the user and based on that the value is fetched datas from DB(sql server 2008) and bind that to android:LISTVIEW.
Without using the parameter my android application is working fine.But when i altered my webserservice to accept parameter and call it in android it is not displaying the result based on the given value instead of that it displays all values.
Here is my webservice code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class JService : System.Web.Services.WebService
{
public JService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public void Cargonet(string jobno)
{
try
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
SqlCommand cmd = new SqlCommand();
//cmd.CommandText = "SELECT id,name,salary,country,city FROM EMaster where age = '" + jobno + "'";
cmd.CommandText = "SELECT [Id] as Id,[Status] as status ,[DateTime] as DateTime FROM [Attendance].[dbo].[cargo] WHERE JobNo= '" + jobno + "' ";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.Connection = con;
da.Fill(dt);
con.Close();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow rs in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, rs[col].ToString().Trim());
}
rows.Add(row);
}
this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(serializer.Serialize(new { Cargo = rows }));
}
catch (Exception ex)
{
//return errmsg(ex);
}
}
}
Here is my android code(Main.java):
package com.example.cargotracking;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView list;
TextView Id;
TextView Status;
TextView DateTime;
Button Btngetdata;
String JobNo;
EditText editText1;
ArrayList<HashMap<String, String>> CargoTracklist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://ip/testing/TrackId.asmx/Cargonet";
//JSON Node Names
private static final String TAG_CargoTrack = "Cargo";
private static final String TAG_Id = "Id";
private static final String TAG_Status = "Status";
private static final String TAG_DateTime = "DateTime";
JSONArray Cargo = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CargoTracklist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.button1);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
Status = (TextView)findViewById(R.id.textView2);
Id= (TextView)findViewById(R.id.textView1);
DateTime = (TextView)findViewById(R.id.textView3);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
// List params = new ArrayList();
params.add(new BasicNameValuePair("JobNo","01"));
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url,params);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
Cargo = json.getJSONArray(TAG_CargoTrack);
for(int i = 0; i < Cargo.length(); i++){
JSONObject c = Cargo.getJSONObject(i);
// Storing JSON item in a Variable
String Status = c.getString(TAG_Status);
String Id = c.getString(TAG_Id);
String DateTime = c.getString(TAG_DateTime);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_Status, Status);
map.put(TAG_Id, Id);
map.put(TAG_DateTime, DateTime);
CargoTracklist.add(map);
list=(ListView)findViewById(R.id.listView1);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, CargoTracklist,
R.layout.listview,
new String[] { TAG_Status,TAG_Id, TAG_DateTime }, new int[] {
R.id.textView2,R.id.textView1, R.id.textView3});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+CargoTracklist.get(+position).get("Id"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Here is my json parser code:
package com.example.cargotracking;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
//public JSONObject getJSONFromUrl(String url, List params) {
public JSONObject getJSONFromUrl(String url, List<BasicNameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
please help me to resolve this.
Thanks in advance
Reading Php Json values, Eclipse dont see the error but it doesnt work. Im becoming crazy because it must run, can you help me?
When i execute it nothing happens.
This is the java activity code:
package com.json.php;
import android.app.Activity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONExampleActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://iatek.eu/sys/getsms.php");
TextView textView = (TextView)findViewById(R.id.textView1);
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
JSONObject obj = new JSONObject(jsonResult);
JSONArray jsonArray = obj.getJSONArray("posts");
/*Para hacer prueba accedo a un registro concreto en este caso el 3*/
JSONObject childJSONObject = jsonArray.getJSONObject(3);
String username = childJSONObject.getString("username");
String sms = childJSONObject.getString("sms");
String fcat = childJSONObject.getString("fcat");
textView.setText(""+sms+"--" + username);
/* para hacer pruebas lo he comentado
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject childJSONObject = jsonArray.getJSONObject(i);
String username = childJSONObject.getString("username");
String sms = childJSONObject.getString("sms");
String fcat = childJSONObject.getString("fcat");
textView.setText(""+sms+"--" + username);
}*/
}
catch (JSONException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}
and here is the json code into iatek.eu/sys/getsms.php
{"posts":[{"cid":"11","username":"Livi","sms":"ag","fto":"","fcat":"cat"},{"cid":"10","username":"Sumone","sms":"","fto":"","fcat":""},{"cid":"9","username":"R2D2","sms":"dw","fto":"wd","fcat":"wd"},{"cid":"5","username":"Roy","sms":"sa","fto":"sa","fcat":"sa"},{"cid":"12","username":"Charles","sms":"ag","fto":"","fcat":"cat"},{"cid":"13","username":"Clarck","sms":"age","fto":"","fcat":"cat"}]}
can someone tell me where is the mistake?
thanks
You cannot run network operation on the main thread.
Use asyncTask instead.
public class JSONExampleActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new GetSmsTask().execute("http://iatek.eu/sys/getsms.php");
}
private class GetSmsTask extends AsyncTask<String, Void, JSONObject> {
protected JSONObject doInBackground(String... urls) {
JSONObject obj = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url[0]);
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity()
.getContent()).toString();
obj = new JSONObject(jsonResult);
}
catch (JSONException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return obj;
}
protected void onPostExecute(JSONObject obj) {
JSONArray jsonArray = obj.getJSONArray("posts");
JSONObject childJSONObject = jsonArray.getJSONObject(3);
String username = childJSONObject.getString("username");
String sms = childJSONObject.getString("sms");
String fcat = childJSONObject.getString("fcat");
textView.setText(""+sms+"--" + username);
}
}
}
EDIT:
I just ran the code myslef, and I got this
09-13 13:33:59.315: W/System.err(14200): org.json.JSONException:
Unterminated object at character 7551 of {"posts":[{......
This means your JSON is invalid
http://pro.jsonlint.com/ paste your link there you will see the error.
To test that the code is working replace this
String jsonResult = inputStreamToString(response.getEntity()
.getContent()).toString();
with this:
String jsonResult = "{\"posts\":" +
"[{\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}," +
" {\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}, " +
"{\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}," +
"{\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}]}";
RESOLVED!!!! ALL ITS PERFECT
HERE IS THE CODE
THANK YOU VERY MUCH meda
package com.json.php;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.json.php.R;
public class JSONExampleActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new GetSmsTask().execute("http://YOURWEBSITE.eu/sys/getsms.php");
}
private class GetSmsTask extends AsyncTask<String, Void, JSONObject> {
protected JSONObject doInBackground(String... urls) {
JSONObject obj = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urls[0]);
HttpResponse response = httpclient.execute(httppost);
/* String jsonResult = "{\"posts\":" + //FOR TESTS
"[{\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}," +
" {\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}, " +
"{\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}," +
"{\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}]}";
*/
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
obj = new JSONObject(jsonResult);
}
catch (JSONException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return obj;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
return answer;
}
protected void onPostExecute(JSONObject obj) {
JSONArray jsonArray;
try {
jsonArray = obj.getJSONArray("posts");
JSONObject childJSONObject = jsonArray.getJSONObject(3);
String username = childJSONObject.getString("username");
String sms = childJSONObject.getString("sms");
String fcat = childJSONObject.getString("fcat");
TextView textView = (TextView) findViewById(R.id.textView1);
textView.setText(""+sms+"--" + username);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I am doing an Android program that is supposed to send data from the tablet to a PHP Web Service. The code for sending the JSON:
package com.example.shvalidation;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
public class MainMenuScreen extends Activity {
//JSON Variables
JSONParser jsonParser = new JSONParser();
String pid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu_layout);
new TestThread().execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu_layout, menu);
return true;
}
public void PlantToDome(View view) {
Intent intent = new Intent(this, SelectLocationScreen.class);
startActivity(intent);
}
//Código del Web Service
public class TestThread extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(MainMenuScreen.this, "Loading", "Loading data, please wait..");
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
protected Void doInBackground(Void...args0) {
try {
HttpClient client = new DefaultHttpClient();
HttpResponse response;
HttpPost post = new HttpPost("http://192.168.1.101:8080/GetBook.php");
JSONObject holder = new JSONObject();
JSONObject euid = new JSONObject();
euid.put("euid", 1);
holder.accumulate("euids", euid);
euid.put("euid", 2);
holder.accumulate("euids", euid);
post.setHeader("json", holder.toString());
StringEntity se = new StringEntity(holder.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
if (response != null) {
InputStream in = response.getEntity().getContent();
String a = convertStreamToString(in);
Log.i("Read from Server", a);
}
} catch (Exception e) {
Log.d("error", e.toString());
}
return null;
}
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
}
}
The PHP Web Service:
<?php
ob_start();
var_dump(json_decode(file_get_contents('php://input')));
$out = ob_get_contents();
ob_end_clean();
$f = fopen('out.txt', 'w+');
fwrite($f, html_entity_decode($out));
fclose($f);
?>
I have tried different methods for getting the JSON, but none of them have worked for me. Maybe the fine people of StackOverflow can help me out with this, as they always have for every other problem that I've had.
From the comments section, it appears you only want the JSON being sent to your PHP script. Normally, you post POST this to PHP, and extract it:
<?php
print_r($_POST);
$json_string = $_POST['message'];
$json = json_decode($json_string);
print_r($json);
?>
And then a small client example:
public static void main(String[] args) {
String json = "{\"message\":\"This is a message\"}";
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost request = new HttpPost("http://somesite.com/test.php");
StringEntity params =new StringEntity("message=" + json);
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
// handle response here...
System.out.println(org.apache.http.util.EntityUtils.toString(response.getEntity()));
org.apache.http.util.EntityUtils.consume(response.getEntity());
} catch (Exception ex) {
// handle exception here
} finally {
httpClient.getConnectionManager().shutdown();
}
}
The output of this is:
Array
(
[message] => {"message":"This is a message"}
)
stdClass Object
(
[message] => This is a message
)
I'm scratching my head at this problem that I can't seem to figure out. What I'm trying to do is extract the URL following the HTTPpost. This will allow me to go through the Oauth process.
Currently I'm extracting the whole website into my entity.
For example: The data will be posted to https://mysite.com/login and will redirect after the post to https://mysite.com/dashboard?code=3593085390859082093720
How does one extract the url?
If you need any more information or can direct me in the right direction, all is appreciated! Thank you!
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginActivity extends Activity implements OnClickListener {
Button ok,back,exit;
TextView result;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Login button clicked
ok = (Button)findViewById(R.id.submit);
ok.setOnClickListener(this);
result = (TextView)findViewById(R.id.result);
}
public void postLoginData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://mysite.com/login");
try {
// Add user name and password
EditText uname = (EditText)findViewById(R.id.username);
String username = uname.getText().toString();
EditText pword = (EditText)findViewById(R.id.password);
String password = pword.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("pseudonym_session[unique_id]", username));
nameValuePairs.add(new BasicNameValuePair("pseudonym_session[password]", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("CANVAS", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent()).toString();
Log.w("CANVAS", str);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String ResponseBody = httpclient.execute(httppost, responseHandler);
Intent intent = new Intent(getBaseContext(), DashboardActivity.class);
startActivity(intent);
if(str.toString().equalsIgnoreCase("true"))
{
Log.w("CANVAS", "TRUE");
result.setText("Login successful");
}else
{
Log.w("CANVAS", "FALSE");
result.setText(ResponseBody);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
#Override
public void onClick(View view) {
if(view == ok){
postLoginData();
}
}
}
if you set a redirect handler, you can get back from the response the location the server's sending you to. here's a snippet of code I was just playing with... (and I should point out, if you DON'T set a redirect handler, you'll just get redirected to the final destination, which might be the login screen itself)
DefaultHttpClient htc = getHttpClient();
htc.setRedirectHandler(new RedirectHandler() {
#Override
public boolean isRedirectRequested(HttpResponse response, HttpContext context)
{
Log.d(TAG, "isRedirectRequested, response: " + response.toString());
return false;
}
#Override
public URI getLocationURI(HttpResponse response, HttpContext context)
throws ProtocolException
{
Log.d(TAG, "getLocationURI, response: " + response.toString());
return null;
}
});
HttpResponse resp = null;
StringBuilder out = new StringBuilder();
try
{
HttpGet get = new HttpGet(spec);
resp = htc.execute(get);
for (Header hdr : resp.getAllHeaders())
Log.d(TAG, "header " + hdr.getName() + " -> " + hdr.getValue());
...
}
catch (Exception e)
{
Log.e(TAG, "Error connecting to " + spec, e);
return null;
}
Search for a substring in the HttpPost url