So I have this app I'm trying to make. I just want a photo of a place from a ID of the place that I get from an intent of the previous Activity, and I wanted to know how can I change my code in order to so with an async task.
Here is the Activity code:
public class CrearViajeActivity2 extends AppCompatActivity {
private String TAG="URL ERROR >>> : ";
private Intent intent;
private String Placeid, imageURL ,reference;
private final String API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
private ImageView PlaceImage;
URLService service;
private ArrayList<String> photosR;
public CrearViajeActivity2() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crear_viaje2);
intent = getIntent();
Placeid = intent.getStringExtra("PlaceID");
PlaceImage = findViewById(R.id.imageView2);
// THIS IS WHAT I HAVE TO FIX , WITH AN ASYNC TASK OR SOMETHING , IF I COMMENT THIS 2 LINES THE APP THROWS AN EXCEPTION AND STOPS WORKING BUT I DONT KNOW HOW TO IMPLEMENT IT(DO IT) .
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
//HERE I GET THE REFERENCE OF THE PLACE
reference=String.format("https://maps.googleapis.com/maps/api/place/details/json?placeid=%s&key=%s",Placeid,API_KEY);
service= new URLService();
String jsonStr = service.URLService(reference);
photosR = new ArrayList<>();
if(jsonStr!=null){
try{
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject jsonObjResult = jsonObj.getJSONObject("result");
JSONArray photos = jsonObjResult.getJSONArray("photos");
for (int i = 0; i < photos.length(); i++) {
JSONObject c = photos.getJSONObject(i);
String photoReference = c.getString("photo_reference");
photosR.add(photoReference);
}
}catch(JSONException ex){
Log.e(TAG, "JSON FAILED: " + ex.getMessage());
Toast.makeText(getApplicationContext(),
"JSON FAILED: " + ex.getMessage(),
Toast.LENGTH_LONG)
.show();
}
}else{
Log.e(TAG, "JSON FAILED.");
}
// AND HERE I FINALLY GET THE PHOTO
imageURL =String.format("https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=%s&key=%s",photosR.get(0),API_KEY);
try{
URL url = new URL(imageURL);
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
PlaceImage.setImageBitmap(bmp);
}catch(MalformedURLException ex){
}catch(IOException ex){
}
}
}
Here is the service class:
private static final String TAG = URLService.class.getSimpleName() +" >> : ";
public URLService() {
}
private String convertirStreamaString(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();
}
public String URLService(String reqUrl) {
String ref = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// READS THE REFERENCE OF THE PHOTO
InputStream in = new BufferedInputStream(conn.getInputStream());
ref = convertirStreamaString(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());
}
return ref;
}
}
Related
I have this piece of code on android that reads data from Assets folder, so I need from this code to read data from external like dropbox. Ho to change and read data from dropbox. thanks
#Override
protected RadioDatas doInBackground(Void... params) {
BufferedReader reader = null;
ArrayList<RadioData> radioDatas = new ArrayList<>();
RadioDatas datas = new RadioDatas();
try {
reader = new BufferedReader(
new InputStreamReader(context.getAssets().open("url.txt"), "Unicode"));
String mLine;
while ((mLine = reader.readLine()) != null) {
RadioData radioData = new RadioData();
String[] meta = mLine.split(";");
radioData.setUrl(meta[0]);
radioData.setTitle(meta[1]);
radioData.setGenres(meta[2]);
radioDatas.add(radioData);
}
} catch (IOException e) {
//log the exception
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
datas.setRadioDatas(radioDatas);
return datas;
}
This would work....
public class Execute extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler handler = new HttpHandler();
String jsonString = handler.makeServiceCall(json);
if (jsonString != null) {
try {
//parse jsonString
} catch (JSONException e) {
Log.i("Error with parsing", e.getMessage());
}
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
You will need a HTTPHandler class...
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
in.close();
} 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());
}
return response;
}
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();
}
}
To run it.
new Execute().execute;
I have a HTTP handler class that will handle the calls to a ASYNC method. Everything works fine, I am able to gather information from the json and display it inside of the application, however, I have noticed that I sometimes get the following in my log.
A connection to http://www.abc123.com/ was leaked. Did you forget to close a response body?
Is there any specific reason why I would be getting this. I am closing in within the try method in convertStreamToString.
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
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());
}
return response;
}
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();
}
}
I've tried searching the internet for solution unfortunately I could not find the answer. I tried using try catch to catch error exception but still it won't work.
Here's my code. I have private class LoginTask
private class LoginTask extends AsyncTask<String,String,JSONObject> {
private String[] privateCredentials;
private String privateRequest;
private String errorMessage = "";
//initialize all here
//constructor
LoginTask(String[] credentials,String request) {
this.privateRequest = request;
this.privateCredentials = credentials;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
if(this.privateRequest=="login"){
try {
String response = result.getString("status");
if(response.equals("ok")){
onLoginSuccess(result.getString("username"),result.getString("full_name"),result.getInt("user_id"));
}else{
onLoginFails();
}
} catch (JSONException e) {
if(errorMessage!=""){
Toast ts;
ts = Toast.makeText(LoginActivity.this,errorMessage,Toast.LENGTH_LONG);
ts.show();
}
//e.printStackTrace();
}
}
}
#Override
protected JSONObject doInBackground(String... params) {
String result = "";
JSONObject resultObj = null;
HttpURLConnection con = null;
BufferedReader br = null;
JSONObject cred = new JSONObject();
if(this.privateRequest=="login"){
try {
cred.put("username", this.privateCredentials[0]);
cred.put("password", this.privateCredentials[1]);
URL url = new URL(params[0]);
con = (HttpURLConnection) url.openConnection();
;
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
con.connect();
OutputStream outputStream = con.getOutputStream();
outputStream.write(cred.toString().getBytes());
InputStream stream = con.getInputStream();
br = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
buffer.append(line);
}
//get the result
JSONObject jsonObj = new JSONObject(buffer.toString());
resultObj = jsonObj;
// return buffer.toString();
}catch (JSONException e) {
errorMessage = e.getMessage();
final String error = e.getMessage();
//e.printStackTrace();
runOnUiThread(new Runnable(){
public void run() {
//ErrorDialog(e.getMessage());
Toast ts;
ts = Toast.makeText(LoginActivity.this,error,Toast.LENGTH_LONG);
ts.show();
}
});
} catch (ProtocolException e) {
errorMessage = e.getMessage();
final String error = e.getMessage();
//e.printStackTrace();
runOnUiThread(new Runnable(){
public void run() {
//ErrorDialog(e.getMessage());
Toast ts;
ts = Toast.makeText(LoginActivity.this,error,Toast.LENGTH_LONG);
ts.show();
}
});
//e.printStackTrace();
} catch (IOException e) {
errorMessage = e.getMessage();
final String error = e.getMessage();
//e.printStackTrace();
runOnUiThread(new Runnable(){
public void run() {
//ErrorDialog(e.getMessage());
Toast ts;
ts = Toast.makeText(LoginActivity.this,error,Toast.LENGTH_LONG);
ts.show();
}
});
//e.printStackTrace();
} finally {
if(con!=null) {
con.disconnect();
}
}
return resultObj;
}
return null;
}
}
And here's my event listener code in the login activity.
//when clicking the login button
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//do now the login process
userText.setVisibility(view.INVISIBLE);
passwordText.setVisibility(view.INVISIBLE);
tvRegister.setVisibility(view.INVISIBLE);
umlogo.setVisibility(view.INVISIBLE);
//set textviews to invisible
/* tv[0].setVisibility(view.INVISIBLE);
tv[1].setVisibility(view.INVISIBLE);*/
//set also the button to invisible
loginBtn.setVisibility(view.INVISIBLE);
//set visible the progress bar
pb.setVisibility(view.VISIBLE);
//set now the user login credentials
credentials[0] = userText.getText().toString();
credentials[1] = passwordText.getText().toString();
loginTask = new LoginTask(credentials,"login");
//loginTask.execute("http://10.0.2.2/sampleRequest.php");
//loginTask.execute("http://10.0.2.2/motorpool_june_2016_laravel/public/mobile/login");
loginTask.execute("http://128.199.105.49/mobile/login");
//SessionHolder.login(credentials, la);
}
});
However it is still not working. Please help. :(
You can't compare Strings with == in java. You must write it like below:
if(this.privateRequest.equals("login")){
== tests for reference equality (whether they are the same object)
In here the code with BufferedReaderand line = reader.readLine() works
public class WeatherService extends AsyncTask<TaskParams, Void, String> {
private WeatherServiceCallback callback;
private Exception exception;
public WeatherService(WeatherServiceCallback callback) {
this.callback = callback;
}
#Override
protected String doInBackground(TaskParams... params) {
try {
URL url = new URL("http://api.openweathermap.org/data/2.5/weather?lat=" +
params[0].getLat() + "&lon=" + params[0].getLon() +
"&units=" + TaskParams.getUnits() +
"&type=" + TaskParams.getAccuracy() + "&lang=" + TaskParams.getLanguage() +
"&appid=10660a09a9fb335d72f576f7aa1bbe5b");
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
} catch (MalformedURLException e) {
exception = e;
} catch (IOException e) {
exception = e;
}
return null;
}
#Override
protected void onPostExecute(String s)
{
if (s == null && exception != null)
{
callback.serviceFailure(exception);
return;
}
try
{
JSONObject data = new JSONObject(s);
Parameters parameters = new Parameters();
parameters.poopulate(data);
callback.serviceSuccess(parameters);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I copy-pasted code to other class since it has very similar functionality and now for no reason I'm getting NullPointerException in while ((line = reader.readLine()) != null) and I have no idea why since as I said it's copy-pasted (I only changed URL and object returned if serivce succeeds)
public class PollutionService extends AsyncTask<TaskParams, Void, String>
{
private PollutionServiceCallback callback;
private Exception exception;
private URLConnection connection;
private InputStream inputStream;
private InputStreamReader streamReader;
private BufferedReader reader;
public PollutionService(PollutionServiceCallback callback) {
this.callback = callback;
}
#Override
protected String doInBackground(TaskParams... params) {
try
{
URL url = new URL("http://api.openweathermap.org/pollution/v1/co/" + params[0].getLat() +
"," + params[0].getLon() + "/current.json?&appid=10660a09a9fb335d72f576f7aa1bbe5b");
try
{
connection = url.openConnection();
}
catch (IOException e)
{
exception = new Exception("Connection error");
}
try
{
inputStream = connection.getInputStream();
}
catch (IOException e)
{
exception = new Exception("Input stream error");
}
try
{
streamReader = new InputStreamReader(inputStream);
}
catch (NullPointerException e)
{
exception = new Exception("Input stream reader error");
}
try
{
reader = new BufferedReader(streamReader);
}
catch (NullPointerException e)
{
exception = new Exception("Buffered reader error");
}
StringBuilder builder = new StringBuilder();
String line;
try
{
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
}
catch (IOException e)
{
exception = e;
}
return builder.toString();
}
catch (MalformedURLException e)
{
exception = e;
}
return null;
}
#Override
protected void onPostExecute(String s)
{
if (s == null && exception != null)
{
callback.pollutionServiceFailure(exception);
return;
}
try
{
JSONObject data = new JSONObject(s);
PollutionParameters parameters = new PollutionParameters();
parameters.poopulate(data);
callback.pollutionServiceSuccess(parameters);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Any clue?
EDIT
This is rewritten code for PollutionActivity. Callback function serviceFailure prints now the URL address on my phone's screen
public class PollutionService extends AsyncTask<TaskParams, Void, String>
{
private PollutionServiceCallback callback;
private Exception exception;
public PollutionService(PollutionServiceCallback callback) {
this.callback = callback;
}
#Override
protected String doInBackground(TaskParams... params) {
try
{
URL url = new URL("http://api.openweathermap.org/pollution/v1/co/" + params[0].getLat() +
"," + params[0].getLon() + "/current.json?&appid=10660a09a9fb335d72f576f7aa1bbe5b");
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
InputStreamReader streamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder builder = new StringBuilder();
String line;
try
{
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
}
catch (IOException e)
{
exception = e;
}
return builder.toString();
}
catch (MalformedURLException e)
{
exception = e;
}
catch (IOException e)
{
exception = e;
}
return null;
}
#Override
protected void onPostExecute(String s)
{
if (s == null && exception != null)
{
callback.pollutionServiceFailure(exception);
return;
}
try
{
JSONObject data = new JSONObject(s);
PollutionParameters parameters = new PollutionParameters();
parameters.poopulate(data);
callback.pollutionServiceSuccess(parameters);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Debugging showed me that code jumps to exception after
InputStream inputStream = connection.getInputStream();
If you are getting NPE for reader then it means that reader is not getting initialized and going null.Your code is getting crash at line 23 and 89. So I believe that the problem is right at the start somewhere and not at the point itself, may be some object is going null like connection.Since line number is not displayed here.Check null pointer for every object like if (connection!=null). Since the initial data is coming null,maybe input stream or some other data,hence your reader object is not getting initialized.Also check if you are getting value for every object in debug.
I "wrote" some code which should execute http request + stream download, however it does not seem to be working with the second part. It connects to the server, but without getting the expected data from it. The first few times it evena worked out, it displayed the html data from google, but afterwards,
I tried to optimize my code and threw something away, added something here and there, extended it by a class etc., which probably caused the "error". Here is my code:
public class MainActivity extends ActionBarActivity {
private static final String TAG = null;
TextView httpStuff;
public static String info;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
AsyncDownload data = (AsyncDownload) new AsyncDownload().execute();
info = data.get();
httpStuff.setText(info);
} catch (Exception e){
e.printStackTrace();
}
}
public class AsyncDownload extends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... params) {
Log.v(TAG, "Final Requsting URL is : :" + "google.com");
String line = "";
String responseData = null;
try {
StringBuilder sb = new StringBuilder();
String x = "";
URL httpurl = new URL("http://www.google.com");
URLConnection tc = httpurl.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(tc.getInputStream()));
while ((line = in.readLine()) != null) {
sb.append(line + "\n");
x = sb.toString();
}
responseData = new String(x);
}
catch (UnknownHostException uh){
Log.v("NewWebHelper", "Unknown host :");
uh.printStackTrace();
}
catch (FileNotFoundException e) {
Log.v("NewWebHelper", "FileNotFoundException :");
e.printStackTrace();
}
catch (IOException e) {
Log.v("NewWebHelper", "IOException :");
e.printStackTrace();
}
catch (Exception e) {
Log.v("NewWebHelper", "Exception :");
e.printStackTrace();
}
return responseData;
}
}
I just don't know what's the missing thing. I've been trying to solve this for hours with a big variety of data-passing versions of this, but nothing seems to be working. I'm counting on you, brainiacs.