I am trying to get JsonObject from DownloadTask. But I am getting array values that are stored in downloadData along with JsonObjects stored in jsonObjectText. Look at below in logs. Why my code return array with JsonObject, But I only log the content of the jsonObject variable.
Here picture of Logs:
Here is my Code :
package com.example.smarpitsingh.webview;
public class MainActivity extends AppCompatActivity {
String name = "Result";
String result = "",downloadedData,jsonObjectText;
URL url;
HttpURLConnection httpURLConnection;
InputStream inputStream;
InputStreamReader streamReader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask downloadTask = new DownloadTask();
try {
downloadedData = downloadTask.execute("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty").get();
JSONArray jsonArray = new JSONArray(downloadedData);
for (int i=1; i<20; i++){
DownloadTask jasonTask = new DownloadTask();
jsonObjectText = jasonTask.execute("https://hacker-news.firebaseio.com/v0/item/"+jsonArray.getString(i)+".json?print=pretty").get();
Log.i(name,jsonObjectText);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
public class DownloadTask extends AsyncTask<String,Void,String>{
#Override
protected String doInBackground(String... urls) {
try {
url = new URL(urls[0]);
httpURLConnection = (HttpURLConnection)url.openConnection();
inputStream = httpURLConnection.getInputStream();
streamReader = new InputStreamReader(inputStream);
int data = streamReader.read();
while (data != -1){
char count = (char)data;
result += count;
data = streamReader.read();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
`}`
Because you have got an array in your json:
Related
I'm trying to download an image from a URL by creating a Bitmap using
bitmapFactory.decodeStream(InputStream) and then imageView.setImageBitmap(bitmap) but I am always getting this error:
D/skia: --- Failed to create image decoder with message
'unimplemented'. package com.example.flickrapp;
Here is my code:
import statements will go here ...
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
Button b = (Button)findViewById(R.id.getanimage);
b.setOnClickListener(new GetImageOnClickListener() {
#Override
public void onClick(View v) {
super.onClick(v);
}
});
}
public class GetImageOnClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
AsyncFlickrJSONData imagesData = new AsyncFlickrJSONData();
imagesData.execute("https://www.flickr.com/services/feeds/photos_public.gne?tags=trees&format=json");
}
}
public class AsyncFlickrJSONData extends AsyncTask<String, Void, JSONObject> {
#Override
protected JSONObject doInBackground(String... strings) {
String flickrUrl = strings[0];
JSONObject jsonFlickr = null;
URL url = null;
try {
url = new URL(flickrUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
String s1 = readStream(in);
int lengthS = s1.length();
String s = (String) s1.subSequence(15, lengthS-1);
jsonFlickr = new JSONObject(s);
} finally {
urlConnection.disconnect();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return jsonFlickr;
}
#Override
protected void onPostExecute(JSONObject jsonFlickr) {
super.onPostExecute(jsonFlickr);
try {
String firstUrl = jsonFlickr.getJSONArray("items").getJSONObject(0).getString("link");
AsyncBitmapDownloader firstAsyncImage = new AsyncBitmapDownloader();
firstAsyncImage.execute(firstUrl);
Log.i("JFL", firstUrl);
} catch (JSONException e) {
e.printStackTrace();
}
}
private String readStream(InputStream in) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
Log.e(TAG, "IOException", e);
} finally {
try {
in.close();
} catch (IOException e) {
Log.e(TAG, "IOException", e);
}
}
return sb.toString();
}
}
public class AsyncBitmapDownloader extends AsyncTask<String, Void, Bitmap> {
ImageView firstImage = (ImageView) findViewById(R.id.image);
#Override
protected Bitmap doInBackground(String... strings) {
String imageUrl = strings[0];
Bitmap bm = null;
URL url = null;
try {
url = new URL(imageUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
bm = BitmapFactory.decodeStream(in);
} finally {
urlConnection.disconnect();
}
} catch(IOException e){
e.printStackTrace();
}
return bm;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
firstImage.setImageBitmap(bitmap);
}
}
}
Any Suggestions or Ideas are welcomed :)
I am making this news application in which I m finding difficulties. here I am using list view.here I am performing background task also and even in this I am able to fetch all the news. The only thing which is not working is when I click on list item its respective image is not showing.
How can I take the image from url and when clicked on the item, the image of that respective list is opened?
public class MainActivity extends AppCompatActivity
{
ListView aboutNews;
Bitmap myImage;
ImageView newnewImage;
ArrayAdapter<String> myArrayAdapter;
ArrayList<String> newscontent , urlImageContent;
String finalUrl;
public void DisplayNews(String title, String urlToImage) {
myArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, newscontent); //i will not put this on oncreate because it will slow down my app.
aboutNews.setAdapter(myArrayAdapter);
newscontent.add(title);
urlImageContent.add(urlToImage);
}
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 in = urlConnection.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 null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
String news = jsonObject.getString("articles");
JSONArray arr = new JSONArray(news);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
String title = jsonPart.getString("title");
String description = jsonPart.getString("description");
String urlToImage = jsonPart.getString("urlToImage");
String publish = jsonPart.getString("publishedAt");
String content = jsonPart.getString("content");
DisplayNews(title , urlToImage);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) { //we have renamed strings to url
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream in = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(in); //it adds everything to the bitmap.
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
newscontent = new ArrayList<String>();
urlImageContent = new ArrayList<String>();
aboutNews = findViewById(R.id.aboutNews);
//.........................................................................
aboutNews.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
finalUrl = urlImageContent.get(i);
ImageDownloader task1 = new ImageDownloader();
try {
myImage = task1.execute(finalUrl).get();
newnewImage.setImageBitmap(myImage);
} catch (Exception e) {
e.printStackTrace();
}
}
});
//.........................................................................
downloadTask task = new downloadTask();
try {
task.execute("https://newsapi.org/v2/top-headlines?country=in&apiKey=API_KEY");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here's my code :
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 in = urlConnection.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 null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather content", weatherInfo);
JSONArray arr = new JSONArray(weatherInfo);
for (int i=0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
Log.i("main",jsonPart.getString("main"));
Log.i("description",jsonPart.getString("description"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
task.execute("http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1");
}
This error shows up. It says Value of type java.lang.String cannot be converted to JSONObject. But I saw the same code worked for an instructor in Udemy.I don't understand why it doesn't work for me. How do I solve this?
What changes do I need to make in my code?
weatherInfo must be JSONArray, not String
And then get your String with index 0
JSONArray jsonArray = jsonObject.getJSONArray("weather");
JSONObject jsonWeather = jsonArray.getJSONObject(0);
I want to write a android code to retrieve json array but I cannot do it. I have tried many tutorials but nothing seemed to worked. Please anyone solve this problem.
Here is the Json:
{
"total_records":"3370",
"count":100,
"records": [
{"id":"175274241",
"timestamp":"1494685823",
"state":"Telangana",
"district":"Warangal",
"market":"Mahabubabad",
"commodity":"Cotton",
"variety":"Desi",
"arrival_date":"13/05/2017",
"min_price":"4150",
"max_price":"4150",
"modal_price":"4150" }
]
}
Here is the Android code
public class MainActivity extends Activity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncLogin().execute();
}
private class AsyncLogin extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL("website url");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
pdLoading.dismiss();
try {
List<String> categories = new ArrayList<String>();
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
String str = json_data.getString("records");
Toast.makeText(MainActivity.this,str,Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Toast.makeText(MainActivity.this,""+e,Toast.LENGTH_LONG).show();
}
}
}
}
Anyone write a android code for above json data.
If your json data is in string jsonStr.By the help of following code ,you can parse your json
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String records = jsonObj.getString("total_records");
String count= jsonObj.getString("count");
// Getting JSON Array node
JSONArray records= jsonObj.getJSONArray("records");
// looping through All Contacts
for (int i = 0; i < records.length(); i++) {
JSONObject c = records.getJSONObject(i);
String id = c.getString("id");
String timestamp= c.getString("timestamp");
String state= c.getString("state");
String district= c.getString("district");
String market= c.getString("market");
String commodity= c.getString("commodity");
String variety= c.getString("variety");
String arrival_date= c.getString("arrival_date");
String min_price= c.getString("min_price");
String max_price= c.getString("max_price");
String modal_price= c.getString("modal_price");
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
public class MainActivity extends AppCompatActivity {
Where I set up the url and HttpUrlConnection which allows the program to read the contents of the url.
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 in = urlConnection.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 null;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
String result = null;
try {
result = task.execute("http://www.historyplace.com/specials/").get();
Log.i("Contents of URL", result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
I believe my code is written correctly because the logCat does display a few lines of code. Unfortunately it does not display all of it. I am trying to first retrieve all of the code so I can use Regex to extract certain pictures and names for an educational school project.