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
Related
With the following android code, i manage to do this:
Display authentification page, on my Android smartphone, to my user
Login, as a valid user, through this page with my credentials
Catch the Auth code
See, on my smarthpone webview, the access_token
public class MainActivity extends AppCompatActivity
{
public static String OAUTH_URL = "https://api.misfitwearables.com/auth/dialog/authorize";
public static String OAUTH_ACCESS_TOKEN_URL = "https://api.misfitwearables.com/auth/tokens/exchange";
public static String CLIENT_ID = "my id";
public static String CLIENT_SECRET = "my secret code";
public static String CALLBACK_URL = "just a simple url";
public static String SCOPE = "public,birthday,email,tracking,session,sleep";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.other);
String url = OAUTH_URL+ "?response_type=code" +"&client_id=" + CLIENT_ID+ "&redirect_uri=" + CALLBACK_URL + "&scope=" + SCOPE;
WebView webview = (WebView) findViewById(R.id.aaa);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient() {
public void onPageStarted(WebView view, String url, Bitmap favicon) {
String accessTokenFragment = "access_token=";
String accessCodeFragment = "code=";
if (url.contains(accessCodeFragment))
{
String accessCode = url.substring(url.indexOf(accessCodeFragment));
String query = "grant_type=authorization_code" + "&client_id=" + CLIENT_ID + "&client_secret=" + CLIENT_SECRET + "&" + accessCode + "&redirect_uri=" + CALLBACK_URL;
view.postUrl(OAUTH_ACCESS_TOKEN_URL, query.getBytes());
System.out.println("url:" + url);
System.out.println(accessCode);
}
System.out.println(url);
if (url.contains(accessTokenFragment)) {
String accessToken = url.substring(url.indexOf(accessTokenFragment));
url = url.replace("#", "?");
//view.loadUrl(url);
System.out.println("token=" + accessToken);
}
}
});
webview.loadUrl(url);
}
}
Like I said above, I manage to display the access_token on my webview, on my smarthpone. But I am not able to catch this token, to make get request in order to recover user's data.
I am novice in java/android, but I have some skills in C.
I just took the time to discover Java, so my skills in this area are limited.
Is that someone could advise me?
I have found some piece of code, and made an Android App that works well.
Main
package com.example.vta.webview_example;
/*
* Note that I was a complete novice in Java and Android when I was writting this.
* Note that I found pieces of code that I adapted for my needs.
*/
import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
public class MainActivity extends Activity
{
private static String CLIENT_ID = "your ID_CLIENT code";
private static String CLIENT_SECRET ="your SECRET_CLIENT code";
private static String REDIRECT_URI="http://localhost";
private static String GRANT_TYPE="authorization_code";
private static String TOKEN_URL ="https://api.misfitwearables.com/auth/tokens/exchange";
private static String OAUTH_URL ="https://api.misfitwearables.com/auth/dialog/authorize";
private static String OAUTH_SCOPE="public,birthday,email,tracking,session,sleep";
WebView web;
Button auth;
SharedPreferences pref;
TextView Access;
#Override
protected void onCreate(Bundle savedInstanceState)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getSharedPreferences("AppPref", MODE_PRIVATE);
Access =(TextView)findViewById(R.id.Access);
auth = (Button)findViewById(R.id.auth);
auth.setOnClickListener(new View.OnClickListener()
{
Dialog auth_dialog;
#Override
public void onClick(View arg0)
{
auth_dialog = new Dialog(MainActivity.this);
auth_dialog.setContentView(R.layout.auth_dialog);
web = (WebView)auth_dialog.findViewById(R.id.webv);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl(OAUTH_URL+"?redirect_uri="+REDIRECT_URI+"&response_type=code&client_id="+CLIENT_ID+"&scope="+OAUTH_SCOPE);
web.setWebViewClient(new WebViewClient()
{
boolean authComplete = false;
Intent resultIntent = new Intent();
String authCode;
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
if (url.contains("?code=") && authComplete != true)
{
Uri uri = Uri.parse(url); //Create an uri, identical to the url
System.out.println("=====> uri <===== \n" + uri);
authCode = uri.getQueryParameter("code"); //Parse the uri to fond the first occurence of "code", and extract his value
Log.i("", "CODE : " + authCode);
System.out.println("=====> code <===== \n" + authCode);
authComplete = true;
resultIntent.putExtra("code", authCode);
MainActivity.this.setResult(Activity.RESULT_OK, resultIntent);
setResult(Activity.RESULT_CANCELED, resultIntent);
SharedPreferences.Editor edit = pref.edit();
edit.putString("Code", authCode);
edit.commit();
auth_dialog.dismiss();
new TokenGet().execute();
Toast.makeText(getApplicationContext(),"Authorization Code is: " +authCode, Toast.LENGTH_SHORT).show();
}
else if(url.contains("error=access_denied"))
{
Log.i("", "ACCESS_DENIED_HERE");
resultIntent.putExtra("code", authCode);
authComplete = true;
setResult(Activity.RESULT_CANCELED, resultIntent);
Toast.makeText(getApplicationContext(), "Error Occured", Toast.LENGTH_SHORT).show();
auth_dialog.dismiss();
}
}
});
auth_dialog.show();
auth_dialog.setTitle("Authorize Misfit");
auth_dialog.setCancelable(true);
}
});
}
private class TokenGet extends AsyncTask<String, String, JSONObject>
{
private ProgressDialog pDialog;
String Code;
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Contacting Misfit ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
Code = pref.getString("Code", "");
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args)
{
GetAccessToken jParser = new GetAccessToken();
JSONObject json = jParser.gettoken(TOKEN_URL,Code,CLIENT_ID,CLIENT_SECRET,REDIRECT_URI,GRANT_TYPE);
System.out.println("=====> json <===== \n" + json);
return json;
}
#Override
protected void onPostExecute(JSONObject json)
{
pDialog.dismiss();
if (json != null)
{
try
{
final String tok = json.getString("access_token");
Log.d("Token Access", tok);
System.out.println("TOKN = " + tok);
auth.setText("Authenticated");
Access.setText("Access Token:" + tok);
}
catch (JSONException e)
{
e.printStackTrace();
}
getRequestToMisfit(json);
}
else
{
Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show();
pDialog.dismiss();
}
}
}
public void getRequestToMisfit(JSONObject json)
{
try
{
URL url;
HttpURLConnection connection;
String tok;
InputStream is;
BufferedReader rd;
String line;
String responseStr;
StringBuffer response;
String end_date;
String today;
String start_date;
Context context;
File file;
File file_value;
String filepath;
String filepath_value;
String result;
result = null;
context = MyApp.getContext();
connection = null;
rd = null;
tok = json.getString("access_token");
FileManagement fm = new FileManagement();
Calendar c = Calendar.getInstance();
String d = String.valueOf(c.get(Calendar.DAY_OF_MONTH));
String m = String.valueOf((c.get(Calendar.MONTH) + 1));
String y = String.valueOf(c.get(Calendar.YEAR));
today = y + "-" + m + "-" + d;
end_date = new String(today);
filepath = context.getFilesDir().getPath().toString() + "/sync_date.txt";
filepath_value = context.getFilesDir().getPath().toString() + "/sync_value.txt";
file = new File(filepath);
file_value = new File(filepath_value);
//IF YOU WANT TO SIMULATE AN OLD SYNC
//fm.writeToFile("2016-03-28", filepath);
//If you want to delete file that contain previous synchronisation date
//fm.deleteFile(file);
if ((start_date = fm.readFromFile(filepath, file)) == null)
start_date = new String(today);
//String dataUrl = "https://api.misfitwearables.com/move/resource/v1/user/me/profile?access_token=" + tok;
String dataUrl = "https://api.misfitwearables.com/move/resource/v1/user/me/activity/summary?start_date="+start_date+"&end_date="+end_date+"&access_token=" + tok;
System.out.println("=====> access_token <===== \n" + tok);
try
{
// Create connection
url = new URL(dataUrl);
setContentView(R.layout.activity_main);
TextView wv = (TextView) findViewById(R.id.misfit);
System.out.println("=====> url <===== \n" + url);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
//if setDoOutput is set to "true", HttpUrlConnection will send POST request.
connection.setDoOutput(false);
// Send request
int status = connection.getResponseCode();
// Get Response
if(status >= HttpStatus.SC_BAD_REQUEST)
is = connection.getErrorStream();
else
is = connection.getInputStream();
rd = new BufferedReader(new InputStreamReader(is));
response = new StringBuffer();
while ((line = rd.readLine()) != null)
{
System.out.println("line = " + line);
response.append(line);
response.append('\r');
}
rd.close();
responseStr = response.toString();
JSONObject json_res = new JSONObject(responseStr);
System.out.println("JSON_OBJ" + json_res);
result = json_res.getString("points");
Log.d("Server response", responseStr);
System.out.println(responseStr);
System.out.println(start_date);
System.out.println(end_date);
System.out.println(result);
wv.setText("nombre de point :\ndu " + start_date + " au " + end_date + "\n" + "*** " + result + " ***");
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if (connection != null)
connection.disconnect();
if (rd != null)
{
try
{
rd.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
if (!file.exists())
{
try
{
file.createNewFile();
file.mkdir();
}
catch (IOException e)
{
e.printStackTrace();
}
}
fm.writeToFile(today, filepath);
if (!file_value.exists())
{
try
{
file_value.createNewFile();
file_value.mkdir();
}
catch (IOException e)
{
e.printStackTrace();
}
}
fm.writeToFile(result, filepath_value);
System.out.println(fm.readFromFile(filepath_value, file));
Toast.makeText(context, "Result added to file ==> OK", Toast.LENGTH_LONG);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
GetAccessToken
package com.example.vta.webview_example;
/*
* Find on
* http://stackoverflow.com/questions/22499066/invalid-client-in-jsonresponse-in-oauth2-android
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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 GetAccessToken
{
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
List<NameValuePair> params = new ArrayList<NameValuePair>();
Map<String, String> mapn;
DefaultHttpClient httpClient;
HttpPost httpPost;
public GetAccessToken()
{
}
public JSONObject gettoken(String address,String token,String client_id,String client_secret,String redirect_uri,String grant_type)
{
// Making HTTP request
try
{
// DefaultHttpClient
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(address);
params.add(new BasicNameValuePair("code", token));
params.add(new BasicNameValuePair("client_id", client_id));
params.add(new BasicNameValuePair("client_secret", client_secret));
params.add(new BasicNameValuePair("redirect_uri", redirect_uri));
params.add(new BasicNameValuePair("grant_type", grant_type));
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
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;
StringBuilder sb;
String line;
reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
line = null;
while ((line = reader.readLine()) != null)
{
System.out.println("=+=+=+> getAccessToken : line <+=+=+= \n" + line);
sb.append(line + "\n");
}
is.close();
json = sb.toString();
System.out.println("=+=+=+> getAccessToken : json <+=+=+= \n" + json);
Log.e("JSONStr", json);
}
catch (Exception e)
{
e.getMessage();
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// 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;
}
}
The entire project :
https://github.com/v3t3a/android/tree/master/marvin_project/webview_example/app/src/main/java/com/example/vta/webview_example
I am working in a simple android application and i am trying to retrieve data from mysql database on localhost. Below is the code that i have written so far.The error that i am getting is the following:
Error in parsing data java.lang.NullPointerException
I used the debugger to check if the retrieved data is correct. And it is. The retrieved data is : [{"CropID":"1","CropName":"Corn"},{"CropID":"2","CropName":"Wheat"}]
What i am getting that error?
package com.testexternaldatabase;
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.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView resultView;
#SuppressLint("NewApi") #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(android.os.Build.VERSION.SDK_INT > 9){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
System.out.println("*** My thread is now configured to allow connection");
}
setContentView(R.layout.activity_main);
resultView = (TextView) findViewById(R.id.result);
getData();
}
public void getData(){
String result = "";
InputStream isr = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2:8080/android_connect/getCrops.php");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
resultView.setText("Could not connect to the database");
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr),8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
sb.append(line + "\n");
}
isr.close();
result = sb.toString();
System.out.println(result);
} catch (Exception e) {
Log.e("log_tag", "Error in converting result " + e.toString());
}
//parse json data
try {
String s = "";
JSONArray jArray = new JSONArray(result);
int id = 0;
String name = null;
for(int i = 0 ; i < jArray.length(); i++){
JSONObject json = jArray.getJSONObject(i);
if(json != null){
id = json.getInt("CropID");
name = json.getString("CropName");
}
s = s + "Crop ID: " + id + "\n" + "Crop Name: " + name + "\n\n";
}
resultView.setText(s);
} catch (Exception e){
Log.e("log_tag", "Error in parsing data " + e.toString());
}
}
}
LOG CAT
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
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)
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
)