I've been trying to write code in which the app gets image links from a webpage, converts it into a bitmap and then displays the image.However, even though studio shows no errors, the image isn't being displayed.The code is written below.Please excuse wrong usages of jargon as I'm new to this.
package com.example.android.web;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
ArrayList<String> url = new ArrayList<String>();
ArrayList<String> name = new ArrayList<String>();
public class DOwnloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
URL url;
int data;
HttpURLConnection connect;
String result = "";
try {
url = new URL(strings[0]);
connect = (HttpURLConnection) url.openConnection();
InputStream in = connect.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
data = reader.read();
while (data != -1) {
char curr = (char) data;
result += curr;
data = reader.read();
}
return result;
} catch (Exception e) {
return null;
}
}
}
public class Imagedownloader extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... strings) {
URL url;
int data;
HttpURLConnection connect;
String result = "";
try {
url = new URL(strings[0]);
connect = (HttpURLConnection) url.openConnection();
connect.connect();
InputStream in = connect.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);
return bitmap;
} catch (Exception e) {
return null;
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView img = findViewById(R.id.imageView);
DOwnloadTask task = new DOwnloadTask();
String result = "";
try {
result = task.execute("http://www.posh24.se/kandisar").get();
String[] a = result.split(
"<div class=\"listedArticles\">");
Pattern pattern = Pattern.compile("alt=\"(.*?)\"");
Matcher m = pattern.matcher(a[0]);
while (m.find()) {
name.add(m.group(1));
}
pattern=Pattern.compile("img src=\"(.*?)\"");
m=pattern.matcher(a[0]);
while(m.find()){
url.add(m.group(1));
}
Random r=new Random();
int chosen=r.nextInt(url.size());
Imagedownloader downloader=new Imagedownloader();
Bitmap bit;
bit=downloader.execute(url.get(chosen)).get();
img.setImageBitmap(bit);
} catch (Exception e) {
}
Any help in identifying where the problem is would be appreciated as the imageview is empty during runtime
Use Glide library for displaying the image. https://github.com/bumptech/glide
To insert the image from the URL into your imageView use:
Glide.with(this).load(url).into(img);
Related
This question already has answers here:
What arguments are passed into AsyncTask<arg1, arg2, arg3>?
(5 answers)
Closed 3 years ago.
I am working on an Android app in which I am making a weather app. The application opens api data from a JSON and displays this information. More specifically it takes the user input of a city or zip code and adds this info to the URL for the API and then executes the URL.
MainActivity.java
package com.shanehampcsci3660.weather;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
//import static com.shanehampcsci3660.weather.GetJsonData.*;
public class MainActivity extends AppCompatActivity
{
public static TextView tempTV, jsonTV;
public EditText cityORZipET;
private Button getWeather;
public String zip, cityOrZip;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tempTV = (TextView) findViewById(R.id.tempTV);
jsonTV = (TextView) findViewById(R.id.jsonFeedTV);
cityORZipET = (EditText) findViewById(R.id.cityORZipET);
getWeather = (Button) findViewById(R.id.getWeatherButton);
//cityOrZip = cityORZipET.getText().toString();
getWeather.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
GetJsonData getJsonData = new GetJsonData();
//getJsonData.execute();
cityOrZip = cityORZipET.getText().toString();
getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + cityOrZip +"&appid=x");
jsonTV.setText(cityOrZip);
/*if(cityOrZip.equals(""))
{
getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + cityOrZip +"&appid=x");
}
else
{
zip = "30528";
getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + zip + "&appid=x");
}*/
}
});
}
}
GetJsonData.java
package com.shanehampcsci3660.weather;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class GetJsonData extends AsyncTask<Void, Void, Void>
{
public String data= "", line = "", name = "";
double temp, minTemp, maxTemp;
#Override
protected Void doInBackground(Void... voids)
{
try
{
URL url = new URL("https://api.openweathermap.org/data/2.5/weather?q=30528&appid=id");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while(line != null)
{
line = bufferedReader.readLine();
data = data + line;
}
JSONObject jsonObject = new JSONObject(data);
JSONObject main = jsonObject.getJSONObject("main");
name = jsonObject.getString("name");
temp = main.getDouble("temp");
minTemp = main.getDouble("min_temp");
maxTemp = main.getDouble("max_temp");
/*JSONObject jsonObject = new JSONObject(result);
JSONObject jsonData = new JSONObject(jsonObject.getString("main"));
String weatherInfo = jsonObject.getString("weather");
JSONArray jsonArray = new JSONArray(weatherInfo);
String description, icon, iconURI;
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonData1 = jsonArray.getJSONObject(i);
description = jsonData1.getString("description");
MainActivityController.description.setText(description);
icon = jsonData1.getString("icon");
iconURI = "http://openweathermap.org/img/w/" + icon + ".png";
Picasso.get().load(iconURI).into(MainActivityController.conditionImageView);
}*/
}
catch(MalformedURLException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid)
{
super.onPostExecute(aVoid);
//MainActivity.jsonTV.setText(data);
MainActivity.tempTV.setText("City:\t" + name + "\tTemp:\t" + temp);
Log.d("Json Feed", name + "Temp: " + temp);
}
public static void execute(String s) {
}
}
My issue is that no matter where I put...
if(cityOrZip.equals(""))
{
getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + cityOrZip +"&appid=id");
}
else
{
zip = "30528";
getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + zip + "&appid=id");
}
...It will only show the data of the default Url opened in GetJsonData.java. My question is what am I doing wrong and what should I correct in order to make my app work with the user input like it should.
you are calling an GetJsonData.execute with the url that contains the client data, but it has no code in it. Looking at your current code the zip that the client inputs does not get stored into the worker class.
This is because you always use the same URL in GetJsonData class. According to question What arguments are passed into AsyncTask? your class declaration should look like:
public class GetJsonData extends AsyncTask<String, Void, YourPojo> {
#Override
protected YourPojo doInBackground(String... urls)
{
try
{
URL url = new URL(urls[0]);
...
} catch (Exception e) {
handle(e);
}
}
}
where YourPojo is a class you need to create to store all properties you need to read from JSON payload:
class YourPojo {
private String data;
private String line;
private String name;
private double temp;
private double minTemp
private double maxTemp;
// getters, setters
}
I am writing a currency exchange android app however when the app is run I do not seem to get a response from the API.
API LINK 1) https://restcountries.eu/rest/v2/all
API LINK 2) http://api.fixer.io/latest
MainActivity Code:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import static java.lang.reflect.Modifier.FINAL;
public class MainActivity extends AppCompatActivity {
//Fill spinner with values from this URL - https://restcountries.eu/rest/v2/all
final String CURRENCY_DATA = "https://restcountries.eu/rest/v2/all";
ArrayList<String> currency_list = new ArrayList();
Button btn;
//The amount entered x's by the curreny exchange rate..
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new downloadData().execute();
new downloadExchangeRate().execute();
}
});
}
public class downloadData extends AsyncTask<String, Void, String> {
String result = "";
#Override
protected String doInBackground(String... strings) {
try {
URL url = new URL(CURRENCY_DATA);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = inputStreamReader.read();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("currencies");
for (int i =0; i<jsonArray.length(); i++){
currency_list.add(jsonArray.getJSONObject(i).optString("code"));
Log.d("list", currency_list.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(s);
}
}
}
downloadExchangeRate.java code:
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class downloadExchangeRate extends AsyncTask<String,Void,String> {
String result = "";
#Override
protected String doInBackground(String... strings) {
final String EXCHANGE_RATE = "http://api.fixer.io/latest";
try {
URL url = new URL(EXCHANGE_RATE);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = inputStreamReader.read();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String s) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(result);
for (int i = 0; i<jsonObject.length(); i++){
ArrayList<String> rates = new ArrayList<>();
rates.add(jsonObject.optString("rates"));
Log.d("list", rates.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(s);
}
}
Any help is appreciated, I think I am calling the JSON wrong.
Update Code as:
Use StringBuilder for result (Why? See this https://stackoverflow.com/a/14927864/5227589):
StringBuilder result=new StringBuilder();
...
......
result.append(current);
When using String it will take very long time to complete while loop due to use of result += current;: .
When using StringBuilder:
In onPostExecute
JSONArray jsonArray = new JSONArray(result.toString());
for (int i =0; i<jsonArray.length(); i++){
currency_list.add(jsonArray.getJSONObject(i).getJSONArray("currencies").getJSONObject(0).optString("code"));
//Log.d("list", currency_list.toString());
}
Full Code:
public class downloadData extends AsyncTask<String, Void, String> {
StringBuilder result=new StringBuilder();
#Override
protected String doInBackground(String... strings) {
try {
URL url = new URL(CURRENCY_DATA);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
char current = (char) data;
Log.i("data",current+"");
while (data != -1) {
current = (char) data;
result.append(current);
data = inputStreamReader.read();
// Log.i("data",current+"");
}
//Log.i("data",result+"");
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
#Override
protected void onPostExecute(String s) {
try {
JSONArray jsonArray = new JSONArray(result.toString());
for (int i =0; i<jsonArray.length(); i++){
currency_list.add(jsonArray.getJSONObject(i).getJSONArray("currencies").getJSONObject(0).optString("code"));
//Log.d("list", currency_list.toString());
}
Log.d("list", currency_list.toString());
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(s);
}
}
I am building an app that displays details of a book you have searched. The problem is that every time I change the orientation of my device the list view elements disappear. I want help in how to make them not disappear. I have a feeling that I need to use a Loader but I have no idea in how to implement it. Here are my activities.
MainActivity :-
package com.example.visha.booklistingapp;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private BookAdapter mAdapter;
EditText searchtext;
ListView earthquakeListView;
TextView empty;
TextView authorcheck;
TextView titlecheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
earthquakeListView = (ListView) findViewById(R.id.listView);
mAdapter = new BookAdapter(this, new ArrayList<Book>());
earthquakeListView.setAdapter(mAdapter);
searchtext = (EditText) findViewById(R.id.editText);
empty = (TextView) findViewById(R.id.textView);
earthquakeListView.setEmptyView(empty);
}
public void searchclick(View view) {
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
String parturl = searchtext.getText().toString();
parturl = parturl.replaceAll("\\s","");
StringBuilder urlbuilder = new StringBuilder();
urlbuilder.append(" https://www.googleapis.com/books/v1/volumes?q=");
urlbuilder.append(parturl);
urlbuilder.append("&maxResults=5");
String url = urlbuilder.toString();
BookAsyncTask task = new BookAsyncTask();
task.execute(url); }
else{
Toast.makeText(getApplicationContext(), "You are not connected to the internet",
Toast.LENGTH_LONG).show();
}
}
private class BookAsyncTask extends AsyncTask<String, Void, List<Book>> {
#Override
protected List<Book> doInBackground(String... urls) {
// Don't perform the request if there are no URLs, or the first URL is null
if (urls.length < 1 || urls[0] == null) {
return null;
}
List<Book> result = QueryUtils.fetchBookData(urls[0]);
return result;
}
#Override
protected void onPostExecute(List<Book> data) {
mAdapter.clear();
if (data != null && !data.isEmpty()) {
mAdapter.addAll(data);
}
}
}
}
QueryUtils :-
package com.example.visha.booklistingapp;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* Created by visha on 14-10-2016.
*/
public final class QueryUtils {
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
private QueryUtils() {
}
public static List<Book> fetchBookData(String requestUrl) {
URL url = createUrl(requestUrl);
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
List<Book> Books = extractFeatureFromJson(jsonResponse);
return Books;
}
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the Book JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
private static List<Book> extractFeatureFromJson(String BookJSON) {
if (TextUtils.isEmpty(BookJSON)) {
return null;
}
List<Book> Books = new ArrayList<>();
try {
JSONObject baseJsonResponse = new JSONObject(BookJSON);
JSONArray BookArray = baseJsonResponse.getJSONArray("items");
for (int i = 0; i < BookArray.length(); i++) {
JSONObject currentBook = BookArray.getJSONObject(i);
JSONObject properties = currentBook.getJSONObject("volumeInfo");
String author;
if(properties.has("authors")) {
author = properties.getString("authors");
}
else {
author = "";
}
String title = properties.getString("title");
Book Book = new Book(author, title);
Books.add(Book);
}
} catch (JSONException e) {
Log.e("QueryUtils", "Problem parsing the Book JSON results", e);
}
return Books;
}
}
You need to override onSaveInstanceState and onRestoreInstanceState methods of Activity Class.
In onSaveInstanceState, save the list data into the Bundle.
In onRestoreInstanceState, restore the list with the Bundle data and re-create the list adapter.
Cheers!!!
if you do not have a different layout for the activity landscape mode then simply putting android:configChanges="orientation|screenLayout|screenSize" will do the job for you.
Example:
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenLayout|screenSize" />
and if you do have different layout for landscape mode the you need to override the savedInstanceState and save and restore the list accordingly in OnCreate
The list is working fine but the problem is i can't download the file from the web server file system. When i tried clicking one of the list item, the dialog will show up but after a few seconds the app will crash. I am using GenyMotion emulator
The filename is correct and also the url, i guess it's in the saving part
Memo.java
package com.example.androidtablayout;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class Memo extends ListActivity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ArrayList<HashMap<String, String>> arraylist;
ProgressDialog mProgressDialog, dialog;
JSONParser jsonParser = new JSONParser();
String email;
SessionManager session;
String[] services;
private String url = "http://10.0.3.2/sunshine-ems/memo.php";
// single product url
// ALL JSON node names
private static final String MEMO_ID = "memo_id";
private static final String MEMO_SENDER = "sender";
private static final String MEMO_FILENAME = "file_name";
Button btnLogout;
String username;
String download_path = "";
String dest_file_path = "";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.announc);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
session = new SessionManager(getApplicationContext());
username = session.getUsername();
btnLogout = (Button) findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Launching All products Activity
session.logoutUser();
Intent i = new Intent(getApplicationContext(), Login.class);
startActivity(i);
}
});
new DownloadJSON().execute();
ListView lv = getListView();
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
String memo_filename = ((TextView) view.findViewById(R.id.txt_service)).getText().toString();
download_path = "http://www.sunshine-ems.balay-indang.com/attachments/memo/"+memo_filename+".docx";
String sd_path = Environment.getExternalStorageDirectory().getPath();
dest_file_path = sd_path+"/"+memo_filename+".docx";
dialog = ProgressDialog.show(Memo.this, "", "Downloading file...", true);
new Thread(new Runnable() {
public void run() {
//Log.d("Download Path", dest_file_path+" "+download_path);
downloadFile(download_path, dest_file_path);
}
}).start();
}
});
}
//download
public void downloadFile(String download_path, String dest_file_path) {
try {
File dest_file = new File(dest_file_path);
URL u = new URL(download_path);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(dest_file));
fos.write(buffer);
fos.flush();
fos.close();
hideProgressIndicator();
} catch(FileNotFoundException e) {
hideProgressIndicator();
return;
} catch (IOException e) {
hideProgressIndicator();
return;
}
}
void hideProgressIndicator(){
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(Memo.this);
mProgressDialog.setTitle("Loading Services");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
username = session.getUsername();
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("username", username));
JSONObject json = jsonParser.makeHttpRequest(url, "POST", params1);
// Check your log cat for JSON reponse
Log.d("Check JSON ", json.toString());
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
try {
int success = json.getInt("success");
if (success == 1) {
// Locate the array name
jsonarray = json.getJSONArray("memos");
for (int i = 0; i < jsonarray.length(); i++) {
json = jsonarray.getJSONObject(i);
String m_id = json.optString(MEMO_ID);
String m_subject = json.getString(MEMO_FILENAME);
String m_sender = json.getString(MEMO_SENDER);
// Retrive JSON Objects
HashMap<String, String> map = new HashMap<String, String>();
map.put(MEMO_ID, m_id);
map.put(MEMO_FILENAME, m_subject);
map.put(MEMO_SENDER, m_sender);
// Set the JSON Objects into the array
arraylist.add(map);
}
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String file_url) {
mProgressDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Memo.this,
arraylist,
R.layout.listview_services,
new String[] { MEMO_ID, MEMO_FILENAME, MEMO_SENDER },
new int[] { R.id.transac_id, R.id.txt_service,
R.id.txt_date });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
I think the downloading was fine, maybe the problem is in the saving/writing part. Maybe the destination path or something close to that
And also where can i see the downloaded file after the download?
I'm using GenyMotion emulator
I'm sorry for the noob questions
Thank you so much
The problem seems to be this line (because it is the only array):
byte[] buffer = new byte[contentLength];
Looking at the declaration of contentLenght it seems conn.getContentLength() is returning a negative number.
Returns the content length in bytes specified by the response header field
content-length or -1 if this field is not set or cannot be represented as an int.
I copied your code and checked with a debugger: contentLenght is always -1.
I just rewrote your downloadFile function to use HttpURLConnection instead of URLConnection. Additionally, it uses a small buffer multiple times instead of creating one large buffer.
//download
public void downloadFile(String download_path, String dest_file_path) {
try {
URL u = new URL(download_path);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
InputStream stream = conn.getInputStream();
File f = new File(dest_file_path);
FileOutputStream fos = new FileOutputStream(f);
int bytesRead = 0;
byte[] buffer = new byte[4096];
while ((bytesRead = stream.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
fos.close();
stream.close();
hideProgressIndicator();
} catch(FileNotFoundException e) {
hideProgressIndicator();
return;
} catch (IOException e) {
hideProgressIndicator();
return;
}
}
You can view the file afterwards by using ADB. Android device monitor contains a file explorer and is located at "path-to\AndroidSDK\tools\monitor.bat" (using Windows)
I'm sure I am doing something wrong, new to Android, I already have the URL stored in a string in a for loop, need to grab the image from that URL using AsyncTask. Quite new to Android so I am running into some issues. Any help is appreciated.
SecondClass.java
package edu.colum.iam.JSON;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class SecondClass extends Activity {
private TextView first, second, third;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
first = (TextView)findViewById(R.id.firsttv);
second = (TextView)findViewById(R.id.secondtv);
third = (TextView)findViewById(R.id.thirdtv);
String id = getIntent().getStringExtra("id");
System.out.println(id);
String response = readBuilding(id.trim());
System.out.println(response);
try {
JSONObject jsonObj = new JSONObject(response);
if(jsonObj.length()>0)
{
String CourseName = jsonObj.getString("CourseName");
String CourseNumber = jsonObj.getString("CourseNumber");
String CourseDescription = jsonObj.getString("CourseDescription");
JSONArray arrayOfImages = jsonObj.getJSONArray("Images");
String theImage = arrayOfImages.get(0).toString(); //getting first image in the array and returning the link as a string
int arrSize = arrayOfImages.length();
List<String> urlOfImage = new ArrayList<String>(arrSize);
first.setText("CourseName:- "+CourseName);
second.setText("CourseNumber:- "+CourseNumber);
third.setText("CourseDescription:- "+CourseDescription);
for(int i = 0; i < arrayOfImages.length(); ++i)
{
theImage = arrayOfImages.get(i).toString();
urlOfImage.add(theImage);
ImageDownloadTask(theImage);
}
}
} catch (Exception e){
e.printStackTrace();
}
}
public String readBuilding(String id)
{
return postJSON("http://iam.colum.edu/portfolio/api/course/"+id+"?json=True");
}
private String postJSON(String stringURL) {
StringBuilder builder = new StringBuilder();
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(stringURL);
try {
httpget.addHeader("Content-Type","application/json; charset=utf-8");
HttpResponse response = httpclient.execute(httpget);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
}
ImageDownloadTask.java
package edu.colum.iam.JSON;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
public class ImageDownloadTask extends AsyncTask<String, Void, Bitmap> {
/** The url from where to download the image. */
private String url;
/** Reference to the view which should receive the image */
private final WeakReference<ImageView> imageRef;
/**
* Constructor.
*
* #param imageView
* The ImageView which will receive the image.
*/
public ImageDownloadTask(ImageView imageView) {
imageRef = new WeakReference<ImageView>(imageView);
}
/**
* This function will be executed to download the image in a background
* process.
*
*/
#Override
protected Bitmap doInBackground(String... params) {
try {
InputStream in = new java.net.URL(url).openStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);
return bitmap;
} catch (Exception e) {
Log.e("ImageDownload", e.getMessage());
}
return null;
}
/**
* This function will be called after the image download and attaches
* the bitmap to the ImageView.
*
*/
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageRef != null) {
ImageView imageView = imageRef.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
There might be more issues here (such as possibly accessing network on main thread?), but this ImageDownloadTask(theImage); won't actually execute your AsyncTask. It shouldn't even compile. You'd want something like new ImageDownloadTask(theImage).execute();
For downloading images by URL I recommend to use third part libraries. For example Picasso (http://square.github.io/picasso).
To download image you just need to write this:
Picasso.with(SecondClass.this).load(url).into(imageView);