Using json and location to display data from a Weather API - java

I am trying to request a JSON froM a url to get specific data as shown below using separate java class.
package com.example.user.test4;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.util.Log;
/**
* Created by user on 05/12/2017.
*/
public class Parser {
// the below line is for making debugging easier
final String TAG = "Parser.java";
// where the returned json data from service will be stored when downloaded
static String json = "";
public String getJSONFromUrl(String url) {
//// TODO: 05/12/2017 https://stackoverflow.com/questions/4308554/simplest-way-to-read-json-from-a-url-in-java
try {
// this code block represents/configures a connection to your REST service
// it also represents an HTTP 'GET' request to get data from the REST service, not POST!
URL u = new URL(url);
HttpURLConnection restConnection = (HttpURLConnection) u.openConnection();
restConnection.setRequestMethod("GET");
restConnection.setRequestProperty("Content-length", "main");
restConnection.setRequestProperty("Content-length", "sys");
restConnection.setRequestProperty("Content-length", "weather");
restConnection.setUseCaches(false);
restConnection.setAllowUserInteraction(false);
restConnection.setConnectTimeout(10000);
restConnection.setReadTimeout(10000);
restConnection.connect();
int status = restConnection.getResponseCode();
// switch statement to catch HTTP 200 and 201 errors
switch (status) {
case 200:
case 201:
// live connection to your REST service is established here using getInputStream() method
BufferedReader br = new BufferedReader(new InputStreamReader(restConnection.getInputStream()));
// create a new string builder to store json data returned from the REST service
StringBuilder sb = new StringBuilder();
String line;
// loop through returned data line by line and append to stringbuilder 'sb' variable
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
// remember, you are storing the json as a stringy
try {
json = sb.toString();
} catch (Exception e) {
Log.e(TAG, "Error parsing data " + e.toString());
}
// return JSON String containing data to activity (or whatever your activity is called!)
return json;
}
// HTTP 200 and 201 error handling from switch statement
} catch (MalformedURLException ex) {
Log.e(TAG, "Malformed URL ");
} catch (IOException ex) {
Log.e(TAG, "IO Exception ");
}
return null;
}
}
Then in another another activity I am getting longitude and latitude and bind it to text to display it:
LocationManager locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
// Use GPS provider to get last known location
String locationProvider = LocationManager.GPS_PROVIDER;
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
if (lastKnownLocation == null)
{
// if no last location is available set lat/long to Lincoln Location
lat = 53.228029;
longi = -0.546055;
}
else
{
// if last location exists then get/set the lat/long
lat = lastKnownLocation.getLatitude();
longi = lastKnownLocation.getLongitude();
}
Afterwards I send information to another application using this code and start the activity:
public void sendLocation(View view) {
Intent coordinates = new Intent(this,MainActivity.class);
coordinates.putExtra("lat", lat);
coordinates.putExtra("longi", longi);
startActivity(coordinates);
}
Then in the main activity I am trying to receive data and display it yet I caught and issue that the data is either not sent or received yet when the latitude and longitude are set in the following code to 0 the lat and longi are still classified as null and display and error message.
public void getCoordinates(View view) {
// FIXME: 05/12/2017
final Button coordinates = (Button) findViewById(R.id.getCoordinates);
final Button displayData = (Button) findViewById(R.id.displayData);
coordinates.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getLocation = MainActivity.this.getIntent();
extras = getLocation.getExtras();
lat = extras.getDouble("lat");
longi = extras.getDouble("longi");
//Checking if there is data stored in the doubles, if not the user will be warned
if (lat == null && longi == null) {
Toast.makeText(MainActivity.this, "No Data recorded, please use permissions", Toast.LENGTH_SHORT).show();
} else {
displayData.setVisibility(View.VISIBLE);
}
The application is supposed to use the collected latitude and longitude to access url and display the weather data but as I don't get any lat/longi I cannot show anything.
I am sorry for the amount of code but I have no clue at which point I have managed to make a mistake so hopefully someone will be able to help.
Thanks.

I see a couple of issues, but it's been a while since I messed with Android java.
Why are you passing a View to SendLocation() and getCoordinates()? Each Activity should control their own screen usage.
You retrieve your MainActivity intent inside an onClick() handler. Instead, this should be in the main line, either from OnCreate(), onNewIntent(), etc. My guess is that this is the cause of your issue. If you capture the MainActivity Intent() at the start of this activity, you can control whether to continue processing or not (if 0's are passed for example).
Also, you don't show how any of these Activity's or the getJSONFromURL class are invoked, which could have an impact on what you see.
HTH, Jim

Related

Get Weather status of multiple locations inside for loop android

I am developing a weather app for that I am using dark sky API in which I want to know the weather status of a bunch of locations which I have stored in ArrayList<LatLng>.
I am using OKHttp to parse the JSON data from API, so I tried to loop the whole fetching process inside for loop but it doesn't give the desired output.
private void beginTask(ArrayList<LatLng> arrayLis) {
//arraylis contains list of locations(LatLng)
m = 0;
startTask = true;
for (int i = 0;i<arrayLis.size();i++) {
double latitude = ((LatLng)arrayLis.get(i)).latitude;
double longitude = ((LatLng)arrayLis.get(i)).longitude;
String url = "https://api.darksky.net/forecast/APIKEY/"
+latitude+","+longitude+"?units=si";
LatLng mylatlng = new LatLng(latitude,longitude);
startProcess(url,mylatlng);
Log.i("GGGTT",""+latitude+", "+longitude);
}
}
private void startProcess(String myurl, final LatLng myLatlng){
OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(myurl)
.build();
Call call = httpClient.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
String data = response.body().string();
Log.i("DATASS",data);
if (response.isSuccessful()){
try {
getCurrentDetails(data,myLatlng);
} catch (JSONException e){
e.printStackTrace();
}
}
}
});
}
private void getCurrentDetails(String data,LatLng myLatlng) throws JSONException{
JSONObject main = new JSONObject(data);
double la = main.getDouble("latitude");
double lon = main.getDouble("longitude");
JSONObject currently = main.getJSONObject("currently");
String summary = currently.getString("summary");
double temperature = currently.getDouble("temperature");
String icon = currently.getString("icon");
LatLng latLngo = new LatLng(la,lon);
ter.add(latLngo);
weatherInfo.add(icon);
// Output here is not in the same order that I have passed
Log.i("LETSCHECK",""+la+", "+lon +icon);
}
I am passing the values as:
19.21111,73.07729
19.20238,73.06582
19.19383,73.05362
19.18848,73.04221
But the output is not in the same order inside the getCurrentDetails method
19.19383,73.05362
19.20238,73.06582
19.18848,73.04221
19.21111,73.07729
I think the method is not waiting before the previous loop gets completed.
Are there any solutions for getting the weather status of all locations stored in ArrayList without changing its order?
EDIT
Hi, I have gone through this method to fetch data in order and its working fine, thanks but one more problem is that I was expecting to show data 4 times as there are four LatLngs in ArrayList and it's working fine, but when I try to read the fetching data that I have stored in another array it only shows 2 items rather than 4.
private void getCurrentDetails(String data,LatLng myLatlng) throws JSONException{
JSONObject main = new JSONObject(data);
double la = main.getDouble("latitude");
double lon = main.getDouble("longitude");
JSONObject currently = main.getJSONObject("currently");
String summary = currently.getString("summary");
double temperature = currently.getDouble("temperature");
String icon = currently.getString("icon");
//Log.i("LETSCHECK",""+la+", "+lon +icon+",k");
loopi++;
Log.i("LETSCHECK",""+loopi);
if (loopi < arrayList.size()) {
getItAgain();
} else if (loopi == arrayList.size()){
for (String l:weatherInfo){
Log.i("LETSCHECK",l);
//expected 4 items to show but its showing only 2 items
}
}
Log.i("LETSCHECK",""+la+", "+lon +icon);
weatherInfo.add(icon);
}
private void getItAgain() {
double latitude = ((LatLng)arrayList.get(loopi)).latitude;
double longitude = ((LatLng)arrayList.get(loopi)).longitude;
String url = "https://api.darksky.net/forecast/74d8feeda5ecf5ee6667d034778b239d/"
+latitude+","+longitude+"?units=si";
LatLng mylatlng = new LatLng(latitude,longitude);
startProcess(url,mylatlng);
}
The network calls are asynchronous and this the expected behavior that you are having here. If you want to get them sorted as you have passed them, then you might need to have a mechanism of waiting for the network call of the previous one to be completed and then again call the next one. However, this might increase the delay of waiting for the response from the server, as you are not fetching multiple responses from the server concurrently.
If you want to wait for the response to maintain the sorted manner, you might just need to do the following.
// Declare a global variable of the list of your locations.
ArrayList<LatLng> arrayLis;
int i = 0;
// Just start the first task without the loop.
double latitude = ((LatLng)arrayLis.get(i)).latitude;
double longitude = ((LatLng)arrayLis.get(i)).longitude;
String url = "https://api.darksky.net/forecast/APIKEY/"
+latitude+","+longitude+"?units=si";
LatLng mylatlng = new LatLng(latitude,longitude);
startProcess(url,mylatlng);
Now in the getCurrentDetails function, you might just have to do the following.
private void getCurrentDetails(String data,LatLng myLatlng) throws JSONException{
JSONObject main = new JSONObject(data);
double la = main.getDouble("latitude");
double lon = main.getDouble("longitude");
JSONObject currently = main.getJSONObject("currently");
String summary = currently.getString("summary");
double temperature = currently.getDouble("temperature");
String icon = currently.getString("icon");
LatLng latLngo = new LatLng(la,lon);
ter.add(latLngo);
weatherInfo.add(icon);
// Now initiate the next call
i++;
if(i < arrayLis.size()) getItAgain();
Log.i("LETSCHECK",""+la+", "+lon +icon);
}
public void getItAgain() {
// Just start the first task without the loop.
double latitude = ((LatLng)arrayLis.get(i)).latitude;
double longitude = ((LatLng)arrayLis.get(i)).longitude;
String url = "https://api.darksky.net/forecast/APIKEY/"
+latitude+","+longitude+"?units=si";
LatLng mylatlng = new LatLng(latitude,longitude);
startProcess(url,mylatlng);
}
Update
I do not understand why it is showing 2 instead of 4 results. However, I think you need to modify the code as follows.
private void getCurrentDetails(String data,LatLng myLatlng) throws JSONException {
JSONObject main = new JSONObject(data);
double la = main.getDouble("latitude");
double lon = main.getDouble("longitude");
JSONObject currently = main.getJSONObject("currently");
String summary = currently.getString("summary");
double temperature = currently.getDouble("temperature");
String icon = currently.getString("icon");
// Move this upto here
weatherInfo.add(icon);
loopi++;
Log.i("LETSCHECK",""+loopi);
if (loopi < arrayList.size()) {
getItAgain();
} else {
for (String l:weatherInfo) {
Log.i("LETSCHECK",l);
//expected 4 items to show but its showing only 2 items
}
}
}
You are running asynchronous code, and the reason that their callbacks are not returning one after the other is logical since each HTTP call takes some amount of time, unrelated to the others, so the response for your third call might actually be received before the first one.
You can either use RxJava (and its operators), or improve the current code. For your startProcess, pass the i from your for-loop as the index and create an array outside of our function. Whenever you get a response from the server, you can store it in the ith position of your array. After each call you can check If all values have been fetched (by a counter or something). It is much better to move all this stuff to its own class so its contained and testable.
One thing to note is how you are gonna handle errors, because your calls might not be received successfully.
This is a sample code. After each success call remove the current proceed item from the array and do a another API request.
private void startProcess(ArrayList<LatLong> elementList){
LatLong myLatlng = elementList.get(0);
OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(myurl)
.build();
Call call = httpClient.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
String data = response.body().string();
Log.i("DATASS",data);
if (response.isSuccessful()){
try {
getCurrentDetails(data,myLatlng);
elementList.remove(0)
startProcess(elementList)
}catch (JSONException e){
e.printStackTrace();
}
}
}
});
}

How to get specific data using http request?

So I'm really new in android, and going to make an application which get the device id of a device, store it on database server, and then check it if the device are the same with the one already registered, if yes, then go to main activity, if not then they need to registered again.
My method :
public class SigninActivity extends AsyncTask<String, String, String> {
private Context context;
public SigninActivity(Context context, int flag) {
this.context = context;
}
protected void onPreExecute(String result) {
}
//#Override
protected String doInBackground(String... arg0) {
try {
String dev = (String) arg0[0];
String link = "http://10.20.2.14/service_antrian/get_data.php?device_id=" + dev;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
Log.d("RETURN", "return");
return sb.toString();
} catch (Exception e) {
Log.d("EXCEPTION", "EXP");
//return "failed";
return new String("Exception: " + e.getMessage());
}
}
// #Override
protected void onPostExecute(String result) {
if (result.equalsIgnoreCase("false")) {
Intent mainIntent = new Intent(UserActivity.this, RegisterActivity.class);
UserActivity.this.startActivity(mainIntent);
} else {
Intent mainIntent = new Intent(UserActivity.this, MainActivity.class);
UserActivity.this.startActivity(mainIntent);
}
}
}
and this is my service in php code:
<?php
ini_set('display_errors', 1);
require_once 'database.php';
if(isset($_GET['device_id'])) {
$device_id = $_GET['device_id'];
$sql = " SELECT * FROM `pasien`.`antrian_mobile` WHERE `device_id`=
'$device_id' ";
$rs = $mysqli->query($sql);
$data = array();
while ($row = $rs->fetch_object()) {
$data[] = $row;
}
if ($mysqli->affected_rows > 0) {
echo "successfull";
} else {
echo "false";
}
echo json_encode($data);
}
?>
but that code only make the app go to the main activity, while there are no records on the database yet. Is it because of my service?
You are returning successfull or failed from your service
if ($mysqli->affected_rows > 0) {
echo "successfull";
} else {
echo "failed";
}
but you are comparing the result with false in your mobile app, hence it always takes the else route and open MainActivity
if (result.equalsIgnoreCase("false")) {
Intent mainIntent = new Intent(UserActivity.this, RegisterActivity.class);
UserActivity.this.startActivity(mainIntent);
} else {
Intent mainIntent = new Intent(UserActivity.this, MainActivity.class);
UserActivity.this.startActivity(mainIntent);
}
I see a few issues in your code:
issue #1
Activity shouldn't extend AsyncTask. AsyncTask should be dedicated to a single asynchronous task (like sending HTTP request) and Activity is representing single user screen (UI layer). You should create AsyncTask separately and call it within an Activity like this:
class SigninActivity extends Activity {
// this method should be called in the place where you want to execute your task
// it could be onResume() method, onClick listener for the button or whatever
private void executeAsyncTask() {
new MyTask().execute(...) // put your params here...
}
private class MyTask extends AsyncTask<String, String, String> {
... // your task code goes here...
}
}
issue #2
Nowadays, using AsyncTask is considered as a bad practice in Android applications, because it has poor error handling and is not aware of the Activity lifecycle. Recommended solution for asynchronous operations on Android is RxJava (version 2).
issue #3
You are using HttpClient. It's recommended to use more mature solutions like Retrofit Http REST client or OkHttp library. They can be easily integrated with RxJava.
issue #4
You're passing Context, but you're not using it
issue #5
You don't have to comment #Override annotations.
issue #6
Your code is messy, hard to debug and read. Once you make it clean, it will be easier to solve problems related to it.
issue #7
In the PHP code, you're mixing responsibilities.
Summary
Make sure you're using the existing code correctly and then try to improve it.

Volley request too slow

My app crashes because the images ArrayList is empty when I set the adapter, I figured that out by putting a toast message right after I parse my JSON request, and a Toast message after I initialize my adapter, "second" gets printed first on screen and the app crashes right after, does it have to do with my internet? Or am I missing something, here's my code, thanks!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page);
mViewPager = (ViewPager) findViewById(R.id.view_pager);
mVolleySingleton = VolleySingleton.getInstance();
mRequestQueue = mVolleySingleton.getRequestQueue();
//First Toast message inside this method
sendAPIRequest();
//after you get the images
mCustomSwipeAdapter = new CustomSwipeAdapter(this, images);
//SECOND TOAST
Toast.makeText(getApplicationContext(), "Second", Toast.LENGTH_LONG).show();
mViewPager.setAdapter(mCustomSwipeAdapter);
mCustomSwipeAdapter.notifyDataSetChanged();
}
public void sendAPIRequest(){
String requestURL = "";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, requestURL, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
parseJSONResponse(response);
//FIRST TOAST : SHOULD BE CALLED FIRST
Toast.makeText(getApplicationContext(), "First", Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(jsonObjectRequest);
}
public void parseJSONResponse(JSONObject response) {
if (response != null || response.length() != 0) {
try {
JSONObject GObject = response.getJSONObject("game");
String name = "N/A";
if (GObject.has("name") && !GObject.isNull("name")) { name = GObject.getString("name"); }
if (GObject.has("screenshots") && !GObject.isNull("screenshots")) {
JSONArray screenShotsArray = GObject.getJSONArray("screenshots");
for (int i = 0; i < screenShotsArray.length(); i++){
JSONObject screenshot = screenShotsArray.getJSONObject(i);
String screenshotURL = screenshot.getString("url");
images.add(screenshotURL);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Does it have to do with my internet? Or am I missing something ...
Both. It happens because you have a race condition.
From what I can make out, your images list is being populated asynchronously by the onResponse callback. Basically, that happens when your app gets the responses to the API requests that it is making. That is going to take at least milliseconds, and possibly seconds (or longer).
But your app is (so you say) crashing soon after the swipe adapter is registered, and the evidence is that the images list has not been populated.
There are three possibilities:
There is something wrong with the requests you are sending which is causing the API requests to not give you any response. (Hypothetically, you could have authentication wrong or something.)
The API requests are taking a long time because of internet connection speed, congestion, or the remote server being slow.
The API requests are taking a short time ... but the adapter registration is even quicker.
If (hypothetically) there is a problem with your requests you will need to fix that. But both of the other scenarios have to be fixed by:
modifying the code that uses the images to work properly if there are no images (yet), or
modifying the code to wait until the image loading has completed before registering the adapter.
Please use this code in your onResponse callback :
//after you get the images
mCustomSwipeAdapter = new CustomSwipeAdapter(this, images);
//SECOND TOAST
Toast.makeText(getApplicationContext(), "Second", Toast.LENGTH_LONG).show();
mViewPager.setAdapter(mCustomSwipeAdapter);
mCustomSwipeAdapter.notifyDataSetChanged();
Volley adds your requests in queue , so better do all the dependent tasks in Response or Error callback only.

Comparing values from textviews and JSONArray

Sorry for the (seemingly) lazy question, but i've been looking for a solution with no luck (in other words, I haven't found a solution that i understand).
I want to have users log in to an app by way of entering a username and password, this username and password has to match a username and password from the jsonarray which i've retrieved from a phpmyadmin database. The username and password have to be in the same row.
Here's the function I use to retrieve my jsonarray:
private void getData(){
JSONArray json;
try{
user = editText1.getText().toString();
password = editText2.getText().toString();
json = readJsonFromUrl("http://localhost/indextest.php?function=getdata");
Thread.sleep(1000);
} catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
}
I just need to know how to search the jsonarray for the values that i retrieve from my textviews.
If possible I would like to retrieve a value that I can easily assign to an if statement like such:
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
if ( editText1 != null && editText1.length() != 0 && editText2 != null && editText2.length() != 0){
getData();
m_ProgressDialog = ProgressDialog.show(HomeScreen.this,
"Please wait...", "Checking Details...", true);
m_ProgressDialog.setCancelable(true);
if ( /*username and password match*/){
Intent i = new Intent(this, Afterlog.class);
startActivity(i);
}
else{
Toast.makeText(HomeScreen.this, "The username and password did not match any in our database...", Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(HomeScreen.this, "Please enter a user name AND a password...", Toast.LENGTH_SHORT).show();
}
break;
}
}
Two things:
Take a look at GSON. It is a Google Library for encoding objects into json and then decoding json into objects. In essence, you can define a class that has the same structure as the data you are receiving in JSON and then use GSON to read the JSON and create an object of your class with the appropriate fields filled in. Your code would look something like this:
First, define your class structure for the data you are sending as JSON:
public class LoginData {
public String Username; //These identifiers must match the JSON structure
public String HashedPassword;
public LoginData(String username, String hashedPass) {
Username = username;
HashedPassword = hashedPass;
}
}
Then, once you receive the JSON, you can parse the information like this:
LoginData login = mGson.fromJson(json, LoginData.class);
It sounds like you are storing usernames and passwords in raw text and retrieving them from your database in raw text. This is a VERY BAD IDEA! Passwords should always be stored in an encrypted form (i.e. hashed). When the user provides their password to log in, you encrypt the provided password and compare the encrypted versions (i.e. compare the hash of the provided password to the stored hash from your database). This prevents people who might be listening to your network traffic from being able to capture your passwords. Instead, if they were watching your network traffic they would see the hashed password, and without knowing exactly the algorithm used to hash the passwords, they would not be able to calculate the original password.
Your code needs to run in an asyncTask because it is performing a network request:
Here is an example:
class LoginTask extends AsyncTask<String, String, JSONObject>
{
protected JSONObject doInBackground(String... urls)
{
return readJsonFromUrl(urls[0]);
}
protected void onPostExecute(JSONObject result)
{
try {
//this assumes that the response looks like this:
//{"username" : "john" , "password" : "Bsd6578" }
String responseUsername = result.getString("username");
String responsePassword = result.getString("password");
if (user.equals(responseUsername) && password.equals(responsePassword)){
Intent i = new Intent(this, Afterlog.class);
startActivity(i);
}else{
Log.d("mylog", "username and password dont match");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Your button is should be responsible for running that task:
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
user = editText1.getText().toString();
password = editText2.getText().toString();
new LoginTask().execute()
break;
}
}
Found a very simple and to the point tutorial here:
http://www.coderzheaven.com/2012/04/22/create-simple-login-form-php-android-connect-php-android/
Thanks for all the help #meda :)

FileNotFoundException in HttpRequest every second time

In my android app, i want to let the user fetch data from a website (by sending an http request). The http-response is then sent to another activtiy which shows the data. (i made this a bit simplier in this example code. In real, the data is parsed into an object and the object is sent).
This all works good with my code. But when the user goes back to the main activity by pressing the back key, and trys another request, the application throws an java.io.FileNotFoundException while getting the input stream from the URLConnection. If the app is closed (by pressing back again) and then reopend, all works well again.
Im pretty sure its a problem with a connection not being closed properly or something like that but i cant find the error in my code.
Any idea whats wrong here?
MainActivity.java
*no interessting code here.
it just calls the static function from MainMethods.java
when a button is pressed*
MainFunctions.java - I want to call the methods from several classes so its in an extra class
class MainFunctions {
public static void search(final Activity, final String searchString) {
new AsyncTast<String, String, String>() {
protected void onPreExecute() {
// im opening a progress dialog for the activity here
}
protected String doInBackground(String... searchString) {
try{
return new HttpUtils().sendRequest(searchString)
} catch (Exception e) {
// print a dialog, stacktrace and stuff
return null;
}
}
protected void onPostExecute(String result) {
if(result != null) {
// dismiss the dialog etc..
Intent i = new Intent("packagename");
i.putExtra("key", result);
activity.startActivity(i);
}
}
}.start(searchString)
}
}
HttpUtils.java
public class HTTPUtils {
public String sendRequest(String data)
throws IOException {
String answer = "";
URL url = new URL("http://myURL.com/" + data);
URLConnection conn = url.openConnection();
conn.setReadTimeout(5000);
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
answer += inputLine;
in.close();
return answer;
}
}
The Stacktrace shows that the Exception is thrown while conn.getInputStream() is called.
java.io.FileNotFoundException: http://myURL.com/danijoo
at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java)
at com.elophant.utils.HTTPUtils.sendRequest(HTTPUtils.java:20)
at com.elophant.Elophant.getSummoner(Elophant.java:183)
at com.lolsummoners.datacollector.Collecter.getSummonerInfo(Collecter.java:39)
at com.lolsummoners.utils.MainFunctions$1.doInBackground(MainFunctions.java:106)
at com.lolsummoners.utils.MainFunctions$1.doInBackground(MainFunctions.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java)
at java.util.concurrent.FutureTask.run(FutureTask.java)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java)
at java.lang.Thread.run(Thread.java)
The Methods getSummoner() and getSummonerInfo() are methods to parse objects out of the response string. i let that out to make the problem easier to undearstand.
Thanks!

Categories

Resources