Get Int from AsyncTask - java

class GetData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
String result = "";
try {
URL url = new URL("http://192.168.0.100/index.php?kod=1eba7936&mode=1");
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
if(code==200){
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
if (in != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
}
in.close();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result;
}
#Override
protected void onPostExecute(String result) {
System.out.println(result);
super.onPostExecute(result);
}
}
I got such class, its work great exept i cannot catch variable as it returns void. The result its single integer value. And System.out.println(result) display proper value on console.
I call function from MainActivity with
new GetData().execute();
My goal is to have result from GetData as integer variable in MainActivity.

I made new class with public string
public class Data {
public static String data;
}
In onPostExecute i add:
Data.data = result.toString();
And now i can use Data.data as string whetever i want.

Related

Why my android program works fine on 4.4.3 version but doesnt work on 10.0

On the phone string is empty, why thats happend?
Phone is android version 10, nox is 4.4.3 if thats matters?
I try more codes for read web page but result is same, i dont know why its happend?
class GetData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
String result = "";
try {
URL url = new URL("http://www.b92.net/info/rss/sport.xml");
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
if(code==200){
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
if (in != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
}
in.close();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result;
}
#Override
protected void onPostExecute(String result) {
tv.setText(result);
}
}
}
To turn #intellij-amiya s comment into an answer:
Use https instead of http: https://www.b92.net/info/rss/sport.xml
this blog post tells us that clear-traffic is (basically) forbidden now (as #morrison-chang pointed out)
You need to add Internet Permission in Manifest.

How implements the Google Distance/Matrix Api at Android Studio?

I'm programming an app that calculates, in route, two locations. I've implemented the google places API to get the lat/lon based on name or address but I can't implement the Distance API. The classes/methods don't appear when I try to import. Below is an example of what I'm trying to do.
private static final String API_KEY = "YOUR_API_KEY";
private static final GeoApiContext context = new
GeoApiContext().setApiKey(API_KEY);
public DistanceMatrix estimateRouteTime(DateTime time, Boolean isForCalculateArrivalTime, DirectionsApi.RouteRestriction routeRestriction, LatLng departure, LatLng... arrivals) {
try {
DistanceMatrixApiRequest req = DistanceMatrixApi.newRequest(context);
if (isForCalculateArrivalTime) {
req.departureTime(time);
} else {
req.arrivalTime(time);
}
if (routeRestriction == null) {
routeRestriction = DirectionsApi.RouteRestriction.TOLLS;
}
DistanceMatrix trix = req.origins(departure)
.destinations(arrivals)
.mode(TravelMode.DRIVING)
.avoid(routeRestriction)
.language("fr-FR")
.await();
return trix;
} catch (ApiException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
The GeoApiContext and DistanceMatrix don't appear at import.
Tks for help.
Answering my question...
public class GetJson extends AsyncTask<Void, Void, DeliveryData> {
#Override
protected void onPreExecute() {
// progressDialog
}
#Override
protected DeliveryData doInBackground(Void... params) {
Utils util = new Utils();
DeliveryData json = util.getInfo("https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins="+latLngCompany.latitude+","+latLngCompany.longitude+
"&destinations="+latPlace+","+lonPlace+"&key=" + APISERVERKEY);
deliveryData.saveDeliveryData();
return json;
}
#Override
protected void onPostExecute(DeliveryData deliveryData) {
//progressDialog.dismiss
}
}
Created a AsyncTask to get json from url with the especifics parameters.
public class Utils {
public DeliveryData getInfo(String end){
String json;
DeliveryData output;
json = NetworkUtils.getJSONFromAPI(end);
output = parseJson(json);
return output;
}
private DeliveryData parseJson(String json){
try {
DeliveryData deliveryData = new DeliveryData();
JSONObject distanceJson = new JSONObject(json)
.getJSONArray("rows")
.getJSONObject(0)
.getJSONArray("elements")
.getJSONObject(0)
.getJSONObject("distance");
Double distanceDouble = null ;
String distance = distanceJson.get("text").toString();
if (distance.contains("km")){
distanceDouble = Double.parseDouble(distance.replace("km", ""));
}else {
distanceDouble = Double.parseDouble("0." + distance.replace("m", ""));
}
deliveryData.setDistance(distanceDouble);
return deliveryData;
}catch (JSONException e){
e.printStackTrace();
return null;
}
}
}
At getInfo, the data from url is passed to string. Then, parseJson is call to transform the string to JsonObject.
My Json there is only one position. So, the object is selected at array and the String is parse to Double, excluding the chars. In the end, the distance is saved at object.
public class NetworkUtils {
public static String getJSONFromAPI (String url){
String output = "";
try {
URL apiEnd = new URL(url);
int responseCode;
HttpURLConnection connection;
InputStream is;
connection = (HttpURLConnection) apiEnd.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(15000);
connection.setConnectTimeout(15000);
connection.connect();
responseCode = connection.getResponseCode();
if(responseCode < HttpURLConnection.HTTP_BAD_REQUEST){
is = connection.getInputStream();
}else {
is = connection.getErrorStream();
}
output = convertISToString(is);
is.close();
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return output;
}
private static String convertISToString(InputStream is){
StringBuffer buffer = new StringBuffer();
try {
BufferedReader br;
String row;
br = new BufferedReader(new InputStreamReader(is));
while ((row = br.readLine())!= null){
buffer.append(row);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return buffer.toString();
}
}
This class is resposible for connecting to server and get the data from url.

Trouble with "inputstream" when creating mobile app that downloads weather information (with AsyncTask)

I'm trying to make a mobile app that downloads info from the openweathermap.org apis. For example, if you feed that app this link: http://api.openweathermap.org/data/2.5/weather?q=Boston,us&appid=fed33a8f8fd54814d7cbe8515a5c25d7 you will get the information about the weather in Boston, MA. My code seems to work up to the point where I have to convert the input stream to a string variable. When I do that, I get garbage. Is there a particular way to do this seemingly simple task in a proper way? Here is my code so far...
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return null;
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
TextView test = (TextView) findViewById(R.id.test);
if(result!=null) test.setText(result);
else{
Log.i(DEBUG_TAG, "returned result is null");}
}
}
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.i(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
String text = getStringFromInputStream(is);
//JSONObject json = new JSONObject(text);
//try (Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name())) {
//text = scanner.useDelimiter("\\A").next();
//}
//Bitmap bitmap = BitmapFactory.decodeStream(is);
return text;
}catch(Exception e) {
Log.i(DEBUG_TAG, e.toString());
}finally {
if (is != null) {
is.close();
}
}
return null;
}
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
Check this library . Is An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries.

android set data in external database

i would like to write data in an external mysql database with my android app.
this class works for that:
public class SendingData extends AppCompatActivity {
Intent intent = null;
private class LoadingDataURL extends AsyncTask<String, String, JSONArray> {
#Override
protected JSONArray doInBackground(String... params) {
URL url;
HttpURLConnection urlConnection = null;
JSONArray response = new JSONArray();
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
String responseString = readStream(urlConnection.getInputStream());
intent = new Intent(SendingData.this, Overview.class);
startActivity(intent);
response = new JSONArray(responseString);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
return response;
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loading_data);
String firstname = "Max";
String secondname= "Mustermann";
LoadingDataURL client = new LoadingDataURL();
client.execute("https://domain.com/index.php?"+
"fristname="+fristname+
"&secondname="+secondname);
}
}
My Problem is, that if in my strings (fristname, secondname) is an & or ? or any special characters, the entry will not be save correctly.
any ideas? :)
Use the URLEncoder class.
Try this please
String fn = URLEncoder.encode(fristname, "utf-8");
String sn = URLEncoder.encode(secondname, "utf-8");
LoadingDataURL client = new LoadingDataURL();
client.execute("https://domain.com/index.php?"+
"fristname=" + fn + "&secondname=" + sn);
Note: Don't encode the full url, just the parameter values.

Using HttpUrlconnection in Rss Reader causes Android to hang

I put together an RSS reader that works as-is but, I want to setup the connection to the RSS URL using HttpUrlConnection method. When I tried it, the program locked up after I clicked Read Rss button:
private class getRssFeedTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
URL rssUrl = new URL(params[0]);
HttpURLConnection urlIn = (HttpURLConnection) rssUrl.openConnection();
InputStream in = new BufferedInputStream(urlIn.getInputStream());
String line;
feed = "";
while ((line = in.toString()) != null) {
feed += line;
}
in.close();
return feed;
} catch (MalformedURLException ue) {
System.out.println("Malformed URL");
} catch (IOException ioe) {
System.out.println("The URL is unreachable");
}
return null;
}
}
This is the connection method I am stuck using which works:
private class getRssFeedTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
URL rssUrl = new URL(params[0]);
BufferedReader in = new BufferedReader(new InputStreamReader(rssUrl.openStream()));
String line;
feed = "";
while ((line = in.readLine()) != null) {
feed += line;
}
in.close();
return feed;
} catch (MalformedURLException ue) {
System.out.println("Malformed URL");
} catch (IOException ioe) {
System.out.println("The URL is unreachable");
}
return null;
}
}
Thanks for any help you can provide!
What you need to do is put it into a string I called it results. I have attached my code for the doInBackground. By adding it to a string it has a place to store the feed. And it works for the rss reader.
public String doInBackground(String... urls){
String result = "";
try{
URL url = new URL(urls[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while((line = reader.readLine()) != null){
result = result + line;
}
conn.disconnect();
}
catch(Exception e){
Log.e("ERROR Fetching ", e.toString());
}
return result;
}

Categories