App not able to extract json data - android

I am trying to extract Json data, but somehow the code is not working.
Can somebody please help me ? Can't seem to understand what i am doing wrong.
(I dont really hav any more details to add)
public class MainActivity extends AppCompatActivity{
TextView t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t=(TextView)findViewById(R.id.exchangeRate);
Anindya task = new Anindya();
task.execute("xyz");
}
public class Anindya 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 in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(System.in);
int data = reader.read();
while (data!= 0)
{
char current = (char)data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i("website content",result);
}
}
}

Try replacing InputStreamReader reader = new InputStreamReader(System.in) with InputStreamReader reader = new InputStreamReader(in)
If it still doesn't solve your problem then try to check the value of data and post details about returned value.

Related

Trying to connect with openweather api but SSLHandshakeException occurs

Here is how am trying to connect to openweathermap
public class MainActivity extends AppCompatActivity {
String jsonData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
JsonDownloader jsonDownloader = new JsonDownloader();
jsonData = jsonDownloader.execute("https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=439d4b804bc8187953eb36d2a8c26a02").get();
Log.i("Json data downloaded : ",jsonData);//trying to print json data to logcat
}catch (Exception e) {
e.printStackTrace();
}
}
//below is class to download json data
public class JsonDownloader extends AsyncTask<String,Void,String>{
URL url;
HttpURLConnection connection;
InputStream inputStream;
String jsonData;
#Override
protected String doInBackground(String... urls) {
try {
url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
inputStream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while(data != -1){
char currentChar = (char)data;
jsonData+=currentChar;
data = inputStreamReader.read();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Exact Exception : java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
Also i want to know is it okay to catch multiple exceptions with single 'Exception' class instead of exact exception type class.

Parse Json data into a Json object

I have a problem with parsing a tag inside a Json object.
My json code is structured like that:
{"giocatori":[{"nome":"Giovanni","cognome":"Muchacha","numero":"1","ruolo":"F-G"},
{"nome":"Giorgio","cognome":"Rossi","numero":"2","ruolo":"AG"},
{"nome":"Andrea","cognome":"Suagoloso","numero":"3","ruolo":"P"},
{"nome":"Salvatore","cognome":"Aranzulla","numero":"4","ruolo":"G"},
{"nome":"Giulio","cognome":"Muchacha","numero":"5","ruolo":"F"}]}
I got the code that let me get the Json file from here: Get JSON Data from URL Using Android? and I'm trying to parse a tag (for example the "nome" tag) into a Json object.
This is the code I got:
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
#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://api.myjson.com/bins/177dpo");
}
});
}
private 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();
}
txtJson.setText(result);
}
}
}
I've never worked with this type of file so I'll really appreciate your help!
You can use something like this:
try {
String servResponse = response.toString();
JSONObject parentObj = new JSONObject(servResponse);
JSONArray parentArray = parentObj.getJSONArray("giocatori");
if (parentArray.length() == 0) {
//if it's empty, do something (or not)
} else {
//Here, finalObj will have your jsonObject
JSONObject finalObj = parentArray.getJSONObject(0);
//if you decide to store some value of the object, you can do like this (i've created a nomeGiocatori for example)
nomeGiocatori = finalObj.getString("nome");
}
} catch (Exception e) {
Log.d("Exception: ", "UnknownException");
}
I use this kind of code all the time, works like a charm.

Data leakage through loop

I am trying to download an html of a webpage via AsyncTask and then, show that html in the LOGs.
This is my code. However, when I run the code, loop never stops.
public class MainActivity extends AppCompatActivity {
public class DownloadTask extends AsyncTask<String,Void,String>{
#Override
protected String doInBackground(String... urls) {
String result = "";
HttpURLConnection connection = null;
URL myUrl;
try{
myUrl = new URL(urls[0]);
connection = (HttpURLConnection) myUrl.openConnection();
InputStream in = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while(data != -1){
char current = (char) data;
result += current;
data = reader.read();
}
return result;
}
catch(Exception e){
e.printStackTrace();
return "Failed";
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
try {
String result = task.execute("http://www.posh24.com/celebrities").get();
Log.i("asd",String.valueOf(result));
}
catch(Exception e){
e.printStackTrace();
}
}
}
My Logs get filled with:
D/dalvikvm: GC_FOR_ALLOC freed 297K, 20% free 2582K/3200K, paused 4ms, total 4ms
Any Idea whats wrong with the code?
The problem with your code is data will not change after you initialized it with a single read() call, so it will never be -1 (hence the infinite loop).
You need to call read() inside the loop.
Replace the following:
int data = reader.read();
while(data != -1){
// ...
With something like this:
int data;
while ((data = reader.read()) != -1) {
// ...
To make things faster you could use a BufferedReader:
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
StringBuilder builder = new StringBuilder();
while((line = reader.readLine()) != null) {
builder.append(line);
}
String data = builder.toString();
Probably because of creating a new string on every character received. Do NOT do this:
result += current;
Instead, create a StringBuilder and append to it.
Or, better yet, do not read one character at a time, but create a BufferedReader and read into a buffer of a considerable size, e.g. 1024 bytes.
I am able to get the data with your code. I believe you already add internet permission when testing.
But your code blocks UI thread because of task.execute().get(). I changed it a bit:
public class DownloadTask extends AsyncTask<String, Void, String> {
private Listener mListener;
DownloadTask(Listener listener) {
mListener = listener;
}
#Override
protected String doInBackground(String... urls) {
String result = "";
HttpURLConnection connection = null;
URL myUrl;
try {
myUrl = new URL(urls[0]);
connection = (HttpURLConnection) myUrl.openConnection();
InputStream in = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return "Failed";
}
}
#Override
protected void onPostExecute(String s) {
mListener.deliverResult(s);
}
public interface Listener {
void deliverResult(String result);
}
}
And the code in Activity looks like:
DownloadTask task = new DownloadTask(new DownloadTask.Listener() {
#Override
public void deliverResult(String result) {
Log.i("asd",String.valueOf(result));
}
});
task.execute("http://www.posh24.com/celebrities");

Android Studio OnCreate Never used warning

This is an rssfeed and everything compiles and I don't think i am missing anything but my app wont launch and there is a warning about my OnCreate never being used. I am unsure if this is related to the problem.
public class MainActivity extends AppCompatActivity {
private TextView src;
private Button btn;
protected void OnCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
setContentView(R.layout.activity_main);
src = (TextView) findViewById(R.id.text);
btn = (Button)findViewById(R.id.Fetch);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fetch();
}
});
}
public void fetch() {
Downloader d = new Downloader();
d.execute("https://en.wikipedia.org/wiki/Main_Page");
try {
src.setText(d.get());
} catch (Exception e) {
Log.e("Error to thread", e.toString());
}
}
class Downloader extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = null;
try {
URL url = new URL(urls[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
result = result + line;
}
conn.disconnect();
reader.close();
} catch (Exception e) {
Log.e("error to fetching", e.toString());
}
return result;
}
}
The correct writing is onCreate, not OnCreate. Try to change that.
OnCreate --> onCreate and use #Override

Why i can not read JSON from this URL?

I faced a problem that I couldn't read the content of a JSON file, the code as below:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
runOnUiThread(new Runnable() {
#Override
public void run() {
new LoadJsonAsync().execute("http://dongabank.com.vn/exchange/export");
}
});
}
class LoadJsonAsync extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
if(params[0] != null){
return readFromURL(params[0]);
}else {
return null;
}
}
#Override
protected void onPostExecute(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
}
private static String readFromURL(String url){
StringBuilder content = new StringBuilder();
try {
URL u = new URL(url);
URLConnection urlConnection = u.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) != null){
content.append(line + "\n");
}
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
}
The problem is from
When i try to use other json links, it work properly. But when i use json link above, i couldn't read anything from this.
Is anyone explain to me the reason why? and how to solve this problem?
Thanks!
It's becouse this JSON response is not JSON.
Aparently this JSON response is wrapped in brackets. You have to retrieve the response as String an then remove the first and the last bracket before parse as JSON.
Your JSON is not valid, remove the bracket at the beginning and the end of your string
It's not a JSON, It's like a JSONP, Google it

Categories

Resources