I created an android app involving JSON parsing. When I run the application in my emulator it worked, but when I run it in my android phone it outputs an error "Unfortunately has stopped".
This is my JSON class:
package com.example.uichandbook;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button b1;
Button copy;
Button search;
int final_id = 0;
int final_id2 = 0;
int large1 = 0;
int large2 = 0;
int counter2;
int counter1;
String parse;
// url to make request
private static String url = "http://lynda.byethost32.com/UICHandbook/contents.json";
private static String url2 = "http://lynda.byethost32.com/UICHandbook/sub_contents.json";
int id;
DatabaseHandler db = new DatabaseHandler(this);
// contacts JSONArray
JSONArray contacts = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (DetectConnection
.checkInternetConnection(MainActivity.this) == true) {
Toast.makeText(MainActivity.this,
"You have Internet Connection", Toast.LENGTH_LONG)
.show();
updates();
}
DatabaseHandler db = new DatabaseHandler(this);
List<data2> contacts = db.getAllContent();
for (data2 cn : contacts) {
LinearLayout lnr = (LinearLayout) findViewById(R.id.container);
lnr.setPadding(1, 1, 1, 1);
b1 = new Button(this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); // Verbose!
lp.weight = 1.0f; // This is critical. Doesn't work without it.
b1.setId(cn.getid());
final int _id = b1.getId();
b1.setText(cn.getcontentname());
lnr.addView(b1, lp);
copy = ((Button)findViewById(_id));
copy.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
Intent intent = new Intent(MainActivity.this, subcontent.class);
intent.putExtra("id", _id);
startActivity(intent);
}
});
}
db.close();
}
public void getjson()
{
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try{
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet(url);
// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String jsonreader = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(jsonreader);
contacts = jsonObject.getJSONArray("tbl_content");
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
Log.d("contact", c.getString("content_name"));
Log.d("contact", c.getString("content"));
Log.d("contact", c.getString("content_id"));
Log.d("contact", c.getString("book_id"));
DatabaseHandler db = new DatabaseHandler(this);
db.addcontent(new data2(c.getInt("content_id"), c.getString("content_name"),c.getString("content"),c.getInt("book_id")));
}
} catch(Exception e){
// In your production code handle any errors and catch the individual exceptions
e.printStackTrace();
}
}
public void getjson2()
{
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url2);
try{
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet(url2);
// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String jsonreader = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(jsonreader);
contacts = jsonObject.getJSONArray("subcontent");
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
Log.d("contact", c.getString("subcontent_name"));
Log.d("contact", c.getString("subcontent"));
Log.d("contact", c.getString("subcontent_id"));
Log.d("contact", c.getString("content_id"));
DatabaseHandler db = new DatabaseHandler(this);
db.subaddcontent(new data3(c.getInt("subcontent_id"), c.getString("subcontent_name"),c.getString("subcontent"),c.getInt("content_id")));
}
} catch(Exception e){
// In your production code handle any errors and catch the individual exceptions
e.printStackTrace();
}
}
final static String SYSTEM_NEWLINE = "\n";
final static float COMPLEXITY = 5.12f; //Reducing this will increase effici ency but will decrease effectiveness
final static Paint p = new Paint();
public static void justifyText(final TextView tv, final float origWidth){
String s = tv.getText().toString();
p.setTypeface(tv.getTypeface());
String [] splits = s.split(SYSTEM_NEWLINE);
float width = origWidth - 5;
for(int x = 0; x<splits.length;x++)
if(p.measureText(splits[x])>width){
splits[x] = wrap(splits[x], width, p);
String [] microSplits = splits[x].split(SYSTEM_NEWLINE);
for(int y = 0; y<microSplits.length-1;y++)
microSplits[y] = justify(removeLast(microSplits[y], " "), width, p);
StringBuilder smb_internal = new StringBuilder();
for(int z = 0; z<microSplits.length;z++)
smb_internal.append(microSplits[z]+((z+1<microSplits.length) ? SYSTEM_NEWLINE : ""));
splits[x] = smb_internal.toString();
}
final StringBuilder smb = new StringBuilder();
for(String cleaned : splits)
smb.append(cleaned+SYSTEM_NEWLINE);
tv.setGravity(Gravity.LEFT);
tv.setText(smb);
}
private static String wrap(String s, float width, Paint p){
String [] str = s.split("\\s"); //regex
StringBuilder smb = new StringBuilder(); //save memory
smb.append(SYSTEM_NEWLINE);
for(int x = 0; x<str.length; x++){
float length = p.measureText(str[x]);
String [] pieces = smb.toString().split(SYSTEM_NEWLINE);
try{
if(p.measureText(pieces[pieces.length-1])+length>width)
smb.append(SYSTEM_NEWLINE);
}catch(Exception e){}
smb.append(str[x] + " ");
}
return smb.toString().replaceFirst(SYSTEM_NEWLINE, "");
}
private static String removeLast(String s, String g){
if(s.contains(g)){
int index = s.lastIndexOf(g);
int indexEnd = index + g.length();
if(index == 0) return s.substring(1);
else if(index == s.length()-1) return s.substring(0, index);
else
return s.substring(0, index) + s.substring(indexEnd);
}
return s;
}
private static String justifyOperation(String s, float width, Paint p){
float holder = (float) (COMPLEXITY*Math.random());
while(s.contains(Float.toString(holder)))
holder = (float) (COMPLEXITY*Math.random());
String holder_string = Float.toString(holder);
float lessThan = width;
int timeOut = 100;
int current = 0;
while(p.measureText(s)<lessThan&¤t<timeOut) {
s = s.replaceFirst(" ([^"+holder_string+"])", " "+holder_string+"$1");
lessThan = p.measureText(holder_string)+lessThan-p.measureText(" ");
current++;
}
String cleaned = s.replaceAll(holder_string, " ");
return cleaned;
}
private static String justify(String s, float width, Paint p){
while(p.measureText(s)<width){
s = justifyOperation(s,width, p);
}
return s;
}
public void updates()
{
DatabaseHandler db = new DatabaseHandler(this);
db.deletetable1();
db.deletetable2();
getjson();
//getjson2();
}
}
You are doing all your operation on Activity's Main Thread. Please use AsyncTask to download your data from web.
From Android 4.0 + Version, it is mandatory to use Worker Thread.
Async Task documentation Link: AsyncTask
ur executing network call on mainthread in android which is pausing mainthread for more than 5sec will cause ANR error or Force close.Make use of Asynctask.
public class WS_GetSMS_Asynctask extends AsyncTask<Void,Void,Void>{
#Override
protected Void doInBackground(Void... params) {
//do your work here
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try{
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet(url);
// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String jsonreader = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(jsonreader);
contacts = jsonObject.getJSONArray("tbl_content");
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
Log.d("contact", c.getString("content_name"));
Log.d("contact", c.getString("content"));
Log.d("contact", c.getString("content_id"));
Log.d("contact", c.getString("book_id"));
DatabaseHandler db = new DatabaseHandler(this);
db.addcontent(new data2(c.getInt("content_id"), c.getString("content_name"),c.getString("content"),c.getInt("book_id")));
}
} catch(Exception e){
// In your production code handle any errors and catch the individual exceptions
e.printStackTrace();
}
return null;
}
Related
I am trying to make an English Dictionary using the Oxford API. I made this according to docs and resources found on the web. But I got this issue "org.json.JSONException: No value for senses" and I don't why. Wherever I looked I couldn't find reason of this issue. I'll give you my MainActivity and request class. Can anyone help me?
MainActiviy:
package com.alitalhacoban.english_dictionary;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
TextView textView;
EditText editText;
private String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
editText = findViewById(R.id.editText);
url = dictionaryEntries();
}
public void find(View view){
MyDictionaryRequest myDictionaryRequest = new MyDictionaryRequest(this);
myDictionaryRequest.execute(url);
}
private String dictionaryEntries() {
final String language = "en-gb";
final String word = "Ace";
final String fields = "pronunciations";
final String strictMatch = "false";
final String word_id = word.toLowerCase();
return "https://od-api.oxforddictionaries.com:443/api/v2/entries/" + language + "/" + word_id + "?" + "fields=" + fields + "&strictMatch=" + strictMatch;
}
}
Request class:
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class MyDictionaryRequest extends AsyncTask<String, Integer, String> {
Context context;
MyDictionaryRequest(Context context) {
this.context = context;
}
final String app_id = "127ae33f";
final String app_key = "e42c0fccfe30223fb9ec02e12ae8c8a9";
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestProperty("app_id", app_id);
urlConnection.setRequestProperty("app_key", app_key);
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
return stringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
String def = "";
try {
JSONObject js = new JSONObject(result);
JSONArray results = js.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject lentries = results.getJSONObject(i);
JSONArray la = lentries.getJSONArray("lexicalEntries");
for (int j = 0; j < la.length(); j++) {
JSONObject entries = la.getJSONObject(j);
JSONArray e = entries.getJSONArray("entries");
for (int k = 0; k < e.length(); k++) {
JSONObject senses = e.getJSONObject(k);
JSONArray s = senses.getJSONArray("senses");
JSONObject d = e.getJSONObject(0);
JSONArray de = d.getJSONArray("definitions");
def = de.getString(0);
}
}
}
Log.e("def", def);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
try to validate the "senses" with senses.has("senses") before use it and then parse it with optjsonarray or optjsonobject for this type and check this key or check at backend side from where what value getting in json response.
I tried more and more and nothing is worked.Last i used sharedPreferences.but that not relevant to me...Please help me to replace the sharedPreferences..
my MainActivity is
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.CancellationSignal;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
TextView textView,textView2;
String[] name=new String[100];
String[] id=new String[100];
String[] names=null;
String[] idg=new String[100];
String[] ids=null;
int i;
int len;
ArrayList<NewsItem> listData;
int size;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Fetch().execute();
SharedPreferences sharedPreferences = getSharedPreferences("local", 0);
SharedPreferences.Editor editor=sharedPreferences.edit();
size = sharedPreferences.getInt("array_size", 0);
ids = new String[size];
names = new String[size];
for(i=0; i<size; i++){
ids[i]=sharedPreferences.getString("array1_" + i, null);
names[i]=sharedPreferences.getString("array2_" + i, null);
}
editor.clear();
editor.commit();
listData = getListData();
final ListView listView = (ListView) findViewById(R.id.custom_list);
listView.setAdapter(new CustomListAdapter(this, listData));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
NewsItem newsData = (NewsItem) listView.getItemAtPosition(position);
Toast.makeText(MainActivity.this, "Selected :" + " " + newsData, Toast.LENGTH_LONG).show();
}
});
//textView=(TextView)findViewById(R.id.textView);
//textView2=(TextView)findViewById(R.id.textView2);
}
class Fetch extends AsyncTask<String,String,Void>{
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream is = null ;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Fetching data...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialogInterface) {
dialogInterface.cancel();
}
});
}
#Override
protected Void doInBackground(String... params) {
String url_select = "http://andrinfo.comli.com/rimgid.php";
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_SHORT).show();
}
});
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
//read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
// ambil data dari Json database
try {
JSONArray Jarray = new JSONArray(result);
len = Jarray.length();
for(i=0;i<Jarray.length();i++)
{
JSONObject Jasonobject = null;
Jasonobject = Jarray.getJSONObject(i);
//get an output on the screen
id[i] ="http://developer.andrinfo.comli.com/img/"+ Jasonobject.getInt("id")+".jpg";
name[i] = Jasonobject.getString("name");
SharedPreferences sharedPreferences=getSharedPreferences("local",0);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putInt("array_size", len);
for(int i=0;i<len; i++) {
editor.putString("array1_" + i, id[i]);
editor.putString("array2_" + i, name[i]);
}
editor.apply();
drac d=new drac();
//d.exe(id,name,len);
}
this.progressDialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
private ArrayList<NewsItem> getListData() {
ArrayList<NewsItem> listMockData = new ArrayList<NewsItem>();
String[] images = getResources().getStringArray(R.array.images_array);
String[] headlines = getResources().getStringArray(R.array.headline_array);
for (i = 0; i < size; i++) {
NewsItem newsData = new NewsItem();
newsData.setUrl(ids[i]);
newsData.setHeadline(names[i]);
newsData.setReporterName("Price");
newsData.setDate("May 26, 2015, 1:35PM");
listMockData.add(newsData);
}
return listMockData;
}
class drac{
public void exe(String[] ids, String[] idg,int size)
{
for (i = 0; i < size; i++) {
Toast.makeText(getApplicationContext(), ""+ids[i], Toast.LENGTH_SHORT).show();
}}}
}
And the PROBLEM IS IN MainActivity.java
See http://developer.android.com/intl/es/reference/android/os/AsyncTask.html. Especially the part with the result.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
Finally I solved by using volley library thanks for the response.
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
I have a successfully converted data from database into json format, my json data is as follows
{"room":[{"id":"1044","location":"kathmandu","title":"room room rome",
"quantity":"2","price":"1000","contact":"9811111111","area":"1500",
"description":"kjkfs ksdjfsd kj","address":"kat"}],"success":1}
I want to view these data on android, my json parser code is
package com.iwantnew.www;
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.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
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() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// 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();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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;
}
}
my view room java file is intended to extract the json data
package com.iwantnew.www;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
//import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class viewroom extends ListActivity {
// url to make request
private static String url = "http://10.0.2.2/iWant/src/android_view_all_room.php";
// JSON Node names
private static final String TAG_ROOM = "room";
// private static final String TAG_SUCCESS = "success";
private static final String TAG_ID = "id";
private static final String TAG_LOCATION = "location";
private static final String TAG_TITLE = "title";
private static final String TAG_QUANTITY = "quantity";
private static final String TAG_PRICE = "price";
private static final String TAG_CONTACT = "contact";
private static final String TAG_AREA = "area";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_ADDRESS = "address";
// contacts JSONArray
JSONArray room = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_room);
// Hashmap for ListView
ArrayList<HashMap<String, String>> roomList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url, "GET", params);
try {
// Getting Array of Contacts
room = json.getJSONArray(TAG_ROOM);
// looping through All Contacts
for(int i = 0; i < room.length(); i++){
JSONObject c = room.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String location = c.getString(TAG_LOCATION);
String quantity = c.getString(TAG_QUANTITY);
String address = c.getString(TAG_ADDRESS);
String price = c.getString(TAG_PRICE);
String contact = c.getString(TAG_CONTACT);
String area = c.getString(TAG_AREA);
String description = c.getString(TAG_DESCRIPTION);
String title = c.getString(TAG_TITLE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_LOCATION, location);
map.put(TAG_QUANTITY, quantity);
map.put(TAG_ADDRESS, address);
map.put(TAG_PRICE, price);
map.put(TAG_CONTACT, contact);
map.put(TAG_AREA, area);
map.put(TAG_DESCRIPTION, description);
map.put(TAG_TITLE, title);
// adding HashList to ArrayList
roomList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, roomList,
R.layout.list_room,
new String[] { TAG_TITLE, TAG_LOCATION, TAG_PRICE }, new int[] {
R.id.title, R.id.location, R.id.price });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String location = ((TextView) view.findViewById(R.id.location)).getText().toString();
String price = ((TextView) view.findViewById(R.id.price)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleRoomActivity.class);
in.putExtra(TAG_TITLE, title);
in.putExtra(TAG_LOCATION, location);
in.putExtra(TAG_PRICE, price);
startActivity(in);
}
});
}
}
the singleroom activity class is intended to show data about clicked room only,
it is as follows
package com.iwantnew.www;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleRoomActivity extends Activity {
private static final String TAG_TITLE = "title";
private static final String TAG_LOCATION = "location";
private static final String TAG_PRICE = "price";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.single_room);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String title = in.getStringExtra(TAG_TITLE);
String location = in.getStringExtra(TAG_LOCATION);
String price = in.getStringExtra(TAG_PRICE);
// Displaying all values on the screen
TextView lblTitle = (TextView) findViewById(R.id.title_label);
TextView lblLocation = (TextView) findViewById(R.id.location_label);
TextView lblPrice = (TextView) findViewById(R.id.price_label);
lblTitle.setText(title);
lblLocation.setText(location);
lblPrice.setText(price);
}
}
and here is the log cat error i get. :(
http://pastebin.com/q4yQxKvF
According to your code one Exception Which you will be getting is NetworkOnMainThreadException
Because you are performing Network operations on Main UI Thread
to Avoid it use AsyncTask inside view room java file
Check Example here AsyncTask Android example
Try using the below code inside your viewroom activity below setContentView() to avoid networkOnmainThread exception..
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
But, doing heavy operation inside background thread using AsyncTask without blocking main thread would be great!
With ICS & beyond, you can't make network calls on the main thread (as you've noticed, it throws an error), which is why you need to use something like AsyncTask; or, you can create a new thread (using the Runnable class) to make your network call. Either way, you are not making the http call on the main thread. Even if you aren't using an ICS or JB device, you should never make network calls on the main thread.
From the Android docs:
Network operations can involve unpredictable delays. To prevent this
from causing a poor user experience, always perform network operations
on a separate thread from the UI. The AsyncTask class provides one of
the simplest ways to fire off a new task from the UI thread.
Here is that link: http://developer.android.com/training/basics/network-ops/connecting.html