Json object parsing error using http request - java

I am having an issue when http request is attempted the code that does the parsing works well...i tried to put a sample json string into the variable result and commented out all the code related to http request...i found the code works fine.But when i do a http request it is not working.Thank you in advance.The following is my code
`
public class MainActivity extends AppCompatActivity {
String result = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onclick();
}
public void onclick(){
Asynctaskrunner run = new Asynctaskrunner();
run.execute("http://headers.jsontest.com/");
TextView text = (TextView) findViewById(R.id.textView);
TextView text1 = (TextView) findViewById(R.id.textView2);
final TextView text2= (TextView) findViewById(R.id.textView5);
final TextView text3 = (TextView) findViewById(R.id.textView6);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
JSONObject json = new JSONObject(result);
String name = json.getString("Accept-Language");
String salary = json.getString("Host");
text2.setText(name);
text3.setText(salary);
}catch (Exception e){
e.printStackTrace();
}
}
}
);
}
//-----------------------------------
private class Asynctaskrunner extends AsyncTask<String,Void,Void>{
private String response;
#Override
protected Void doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
InputStream in = new BufferedInputStream(conn.getInputStream());
response=convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
result=response;
TextView textView = (TextView) findViewById(R.id.textView4);
return null;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
}`

String name = json.getString("Accept-Language");
the problem is here! JSON response is not returning any value for the Accept-Language key.
This is the response.
{
"X-Cloud-Trace-Context": "8bc66db5c468f43daff9c6a69fa7d0be/11367517399452323805",
"Host": "headers.jsontest.com",
"User-Agent": "Dalvik/2.1.0 (Linux; U; Android 6.0.1; D6503 Build/23.5.A.0.570)"
}
Change it with other key!
String trace = json.getString("X-Cloud-Trace-Context");
String host = json.getString("Host");
String agent = json.getString("User-Agent");

Related

android class async upload reference

I am back from taking a few years break in programming. Today I am trying to access my webserver from android and I have some code I recycled from back in the day. The code used to work, but, lo and behold, today it has an error. Can someone help me figure this out?
Here is my main class:
public class login extends AppCompatActivity {
Button join;
TextView clientid;
EditText username, password;
_upload upload;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
upload = new _upload();
String android_id = Secure.getString(login.this.getContentResolver(),
Secure.ANDROID_ID);
join = findViewById(R.id.join);
clientid = findViewById(R.id.clientid);
clientid.setText(android_id);
username = findViewById(R.id.username);
password = findViewById(R.id.password);
join.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
login();
}});
}
public void login(){
String id = username.getText().toString();
if (id.isEmpty()) { username.setError("required");username.requestFocus();return; }
String pw = password.getText().toString();
String cid = clientid.getText().toString();
String[] params = new String[3];
params[1]="username::" + id;
params[2]="password::" + pw;
params[3]="cid::" + cid;
new upload.send(login.this, "dump.php", params);
Toast.makeText(this, id + " " +pw+ " "+cid, Toast.LENGTH_LONG).show();
}
}
my error is in the line new upload.send(login.this, "dump.php", params);
error: cannot find symbol
new _upload.send(login.this, "dump.php", params);
^
symbol: class send
location: class _upload
this is my second class, the one that used to work:
public class _upload extends AppCompatActivity {
HttpURLConnection conn = null;
String Return;
String homeurl = "removed";
String roomurl = "";
String param;
Context ctx;
String er;
public void location(Context context, String url, String params){
ctx = context;
roomurl = url;
try {
param = "lola=" + URLEncoder.encode(params, "UTF-8");
new sendStatusChange_Server().execute("");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public void send(Context context, String url, String params[]){
ctx = context;
roomurl = url;
int total = params.length;
int i = 0;
while(i<=total-1) {
if (i==0) {
try {
String[] keyval = params[0].split("::");
param = keyval[0] + "=" + URLEncoder.encode(keyval[1], "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
else{
try {
String[] keyval = params[i].split("::");
param = param + "&" + keyval[0] + "=" + URLEncoder.encode(keyval[1], "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
}
new sendStatusChange_Server().execute("");
}
public class sendStatusChange_Server extends AsyncTask<String, String, Void> {
protected Void doInBackground(String... params) {
try {
updateserver();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(er!=null){Toast.makeText(ctx, er, Toast.LENGTH_LONG).show();}
else{Toast.makeText(ctx, Return, Toast.LENGTH_LONG).show();}
}
}
private void updateserver() throws IOException {
URL url = new URL(homeurl + roomurl);
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(param.getBytes().length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(param);
Log.d("SENT:", param + " to " + url.toString());
out.close();
String response = "";
Scanner inStream = new Scanner(conn.getInputStream());
while (inStream.hasNextLine())
response += (inStream.nextLine());
inStream.close();
Return = response;
} catch (MalformedURLException ex) {
} catch (IOException ex) {
er = ex.toString();
}
return;
}
}
the code still runs fine on the old program but I made a new package and want to get that rolling... why would this happen? Thank you for taking the time!
You have a syntax error. Use
upload.send(...)
instead of
new upload.send(...)
since upload is already an instance of your class.
You should probably also make it so _upload doesn't extend AppCompatActivity (just remove the extends AppCompatActivity from public class _upload extends AppCompatActivity).

I got error Android JSON parsing Retrieve from URL

I new to Android... I am trying Android JSON parsing Retrieve from URL and set MySQL DB data into TextView but I got an error. I tried many solutions but it's not working Help me to solve this error
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String org.json.JSONObject.getString(java.lang.String)' on
a null object reference at
com.example.testapplication.MainActivity$GetDataFromServerIntoTextView.onPostExecute(MainActivity.java:123)at
com.example.testapplication.MainActivity$GetDataFromServerIntoTextView.onPostExecute(MainActivity.java:63)
Error shows this line textView.setText(jsonObject.getString("distance"));
My Code
HttpResponse httpResponse;
Button button;
TextView textView;
static JSONObject jsonObject = null ;
String StringHolder = "" ;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
textView = (TextView)findViewById(R.id.textView);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progressBar.setVisibility(View.VISIBLE);
new GetDataFromServerIntoTextView(MainActivity.this).execute();
}
});
}
public class GetDataFromServerIntoTextView extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetDataFromServerIntoTextView(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpClient httpClient = new DefaultHttpClient();
String HttpURL = "https://api.myjson.com/bins/1cuzhn";
// Adding HttpURL to my HttpPost oject.
HttpPost httpPost = new HttpPost(HttpURL);
try {
httpResponse = httpClient.execute(httpPost);
StringHolder = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jsonArray = new JSONArray(StringHolder);
jsonObject = jsonArray.getJSONObject(0);
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {
textView.setText(jsonObject.getString("distance"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
progressBar.setVisibility(View.GONE);
}
}
I modified your AsyncTask and tested below code and its working fine. Let me know if you found any issue.
Add below dependencies
// OKHTTP
implementation 'com.squareup.okhttp:okhttp:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
implementation 'org.apache.httpcomponents:httpcore:4.4.10'
and
public class GetDataFromServerIntoTextView extends AsyncTask<Void, Void,String>
{
public Context context;
public GetDataFromServerIntoTextView(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... voids) {
String strUrl = "https://api.myjson.com/bins/1cuzhn";
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d(TAG, "Exception while downloading url " + e.toString());
} finally {
try {
iStream.close();
} catch (IOException e) {
e.printStackTrace();
}
urlConnection.disconnect();
}
return data;
}
#Override
protected void onPostExecute(String data) {
super.onPostExecute(data);
try {
if (data != null) {
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Here is your all data of distance and time
Log.e(TAG, "distance " + jsonObject.get("distance"));
Log.e(TAG, "time " + jsonObject.get("time"));
}
} else {
Log.e(TAG, "onPostExecute: null json object");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You are using POST request where as your api is expecting GET request
Here is more details about GET and POST
HttpPost httpPost = new HttpPost(HttpURL);
replace this with following
HttpGet request = new HttpGet(HttpURL);
To avoid crash replace your code with
textView.setText(jsonObject.getString("distance"));
this
textView.setText(jsonObject.isNull("distance") ? "null object" : jsonObject.getString("distance"));

Exctracting more than one field at time from a JSon file

I was developing a simple application that exctracts some fields of a JSon that tells me in real time what weather is in that exact moment, and I have exctracted only one filed, and I was asking myself: Is it possible to extract more than on field at time?
Here is the the link from where i parse the Json:
https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139
And here's my code:
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
ArrayMap<Integer, String> arrayMap = new ArrayMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btnHit);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute("https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139");
}
});
}
public class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()) {
pd.dismiss();
}
try {
JSONObject Object = new JSONObject(result);
JSONArray arr = new JSONArray(Object.getString("weather"));
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
//txtJson.append("main: " + jsonPart.getString("main") + '\n');
arrayMap.put(i, jsonPart.getString("main"));
txtJson.append("main: " + arrayMap.get(i) + '\n');
}
} catch (JSONException e) {
e.printStackTrace();
//txtJson.setText(result);
}
//txtJson.setText(result);
}
}
}
If I understand correctly you want to extract other object alongwith main from the array weather
"weather": [
{
"id": 701,
"main": "Mist",
"description": "mist",
"icon": "https://cdn.glitch.com/6e8889e5-7a72-48f0-a061-863548450de5%2F50n.png?1499366021876"
}
If that is the requirement then you can use the same process like you have done just change the name of the object.
arrayMap.put(i, jsonPart.getString("description"));
or
you can use gson and convert the object in pojo class in one go. Then use the object of the pojo and access the data.
Hope it helps.

Is it possible that the array map is too little for contain about 2000 items?

In my code i had caught data from a JSON file,
I executed the program, it stopped but didn't crash.
i've tried to change json file. I found one that is Smaller than the first one and so the program works.
this JSON file is made of data o premier legue(England) and contain 3 mainly data, the name, a key and a code of the squads.
public class MainActivity extends AppCompatActivity {
private ProgressDialog caric;
private String TAG = MainActivity.class.getSimpleName();
public ArrayMap<Integer, Valori> ArrayDati = new ArrayMap<>();
Button buttonProg;
TextView textViewProg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonProg = (Button) findViewById(R.id.button);
textViewProg = (TextView) findViewById(R.id.textView);
buttonProg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonCLASS().execute("https://raw.githubusercontent.com/openfootball/football.json/master/2015-16/en.1.clubs.json");
}
});
}
private class JsonCLASS extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
caric = new ProgressDialog(MainActivity.this);
caric.setMessage("Please wait");
caric.setCancelable(false);
caric.show();
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray Arr = new JSONArray(jsonObject.getString("clubs"));
for (int i = 0; i < Arr.length(); i++){
JSONObject jsonPart = Arr.getJSONObject(i);
ArrayDati.put(i,new Valori( jsonPart.getString("key"), jsonPart.getString("name"), jsonPart.getString("code")));
textViewProg.setText(textViewProg.getText()+"key : "+ ArrayDati.get(i).Key
+"\n"+textViewProg.getText()+"name : "+ ArrayDati.get(i).Name
+"\n"+textViewProg.getText()+"code : "+ ArrayDati.get(i).Code );
}
} catch (Exception e ){
e.printStackTrace();
}
if (caric.isShowing()) {
caric.dismiss();
}
}
}
}
And a class to pass the data
public class Valori {
String Key;
String Name;
String Code;
public Valori(String key, String name, String code) {
this.Key = key;
this.Name = name;
this.Code = code;
}
}
With this code the application stops but it doesn't close.

Simple weather app didn't work?

I am trying to display main and description from json data i take from opneweathermap. And nothing happen, but I don't have errors.
I will not include the link.
Here is my MainActivity class
public class MainActivity extends AppCompatActivity {
private Button mButton;
private TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.button);
mTextView = (TextView) findViewById(R.id.textView2);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DownloadTask task = new DownloadTask();
task.execute("Link");
}
});
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while(data != -1){
char current = (char) data;
result+=current;
data = inputStreamReader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
Toast.makeText(getApplicationContext(), "Soem"+message,Toast.LENGTH_LONG).show();
Log.i("Weather content", weatherInfo);
JSONArray array = new JSONArray(weatherInfo);
for(int i=0;i<array.length();i++){
JSONObject jsonPart = array.getJSONObject(i);
String main = "";
String description = "";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
if(main != "" && description != ""){
message += main + ": " + description + "\r\n";
}
}
if(message != ""){
mTextView.setText(message);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I have included uses-permissions and i have TextView and Button that will display the data from json in my layout file.

Categories

Resources