The application is minimized when the code is executed - java

I am writing the simplest application for Android. I receive all the HTML of the site and display this text on the smartphone screen. All this happens in Android Studio. Created a project using the "Fragment + ViewModel" template. In MainActiviti, using the getContent method, I connect to the site and read its HTML.
The method works, but as soon as I try to transfer the text to the screen, the application is immediately minimized on startup. Tell me what's wrong.
public class MainFragment extends Fragment{
final public String URL_POSTER = "https://udmfil.ru/";
public static MainFragment newInstance() {
return new MainFragment();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
DownLoad FOG = new DownLoad();
FOG.execute(URL_POSTER);
String result_post = String.valueOf(FOG);
Log.i("URL",result_post);
return inflater.inflate(R.layout.main_fragment, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new ViewModelProvider(this).get(MainViewModel.class);
}
public class DownLoad extends AsyncTask<String,Void,String[]> {
#Override
protected String[] doInBackground(String... strings) {
HttpURLConnection connection = null;
BufferedReader reader= null;
try {
URL url = new URL(strings[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder buffer = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
buffer.append(line);
Log.i("URL", String.valueOf(buffer));
/*String pos = buffer.toString();
int indexPost, i = 1;
String postB;
do {
indexPost = pos.indexOf("m-img buy") + 21;
Log.i("URL", String.valueOf(indexPost));
if (indexPost != -1){
postB = pos.substring(indexPost, indexPost + 55);
Log.i("URL",postB);
strings[i] = postB;
indexPost = indexPost +55;
pos = pos.substring(indexPost);
Log.i("FLAG",pos);
i++;
Log.i("FLAG",strings[i]);
Log.i("URL", String.valueOf(i));
}
}while (indexPost != -1);*/
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
}catch (IOException e){
e.printStackTrace();
}
}
return strings;
}
}
}
error log:
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$4.done(Unknown Source:27)
at java.util.concurrent.FutureTask.finishCompletion(Unknown Source:36)
at java.util.concurrent.FutureTask.setException(Unknown Source:23)
at java.util.concurrent.FutureTask.run(Unknown Source:40)
at android.os.AsyncTask$SerialExecutor$1.run(Unknown Source:2)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source:79)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source:2)
at java.lang.Thread.run(Unknown Source:4)
Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
at java.net.Inet6AddressImpl.lookupHostByName(Unknown Source:111)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Unknown Source:22)
at java.net.InetAddress.getAllByName(Unknown Source:3)
at com.android.okhttp.Dns$1.lookup(Dns.java:41)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:178)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:144)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:86)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:176)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:90)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:30)
at com.example.myapplication.ui.main.MainFragment$DownLoad.doInBackground(MainFragment.java:58)
at com.example.myapplication.ui.main.MainFragment$DownLoad.doInBackground(MainFragment.java:48)
at android.os.AsyncTask$3.call(Unknown Source:20)
at java.util.concurrent.FutureTask.run(Unknown Source:31)
Caused by: android.system.GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
at libcore.io.Linux.android_getaddrinfo(Native Method)
at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:74)
at libcore.io.BlockGuardOs.android_getaddrinfo(BlockGuardOs.java:200)
at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:74)
at java.net.Inet6AddressImpl.lookupHostByName(Unknown Source:51)
Caused by: android.system.ErrnoException: android_getaddrinfo failed: EACCES (Permission denied)
Now this is how it turns out.

As the message in the error log suggested, you have to add INTERNET permission to the Manifest file like below:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.stackoverflow">
<uses-permission android:name="android.permission.INTERNET" />

As you have not given the Internet permission host is not able to access the address and receive the data and in result it is getting crashed when you initiating the app.
Insert the below line in your menifest:
<uses-permission android:name="android.permission.INTERNET" />

Related

How can I connect to web page, get status code to check if page available or not

I new to android programming and I had some problem that needs help, I'm stuck at this part for quite some time.
Problem: the code is successfully compiled, but making the connection to check make it crash. Can you help me by telling what is causing the issue and suggest me the solution or help improve my code. Thank you.
Process: the app check whether the app it wants to check is exist in google play store or not by checking its package name by sending simple HTTP connection. If the connection success to the app page in google play store, it will output a string that the page exists and it's a legit app.
Here is a snippet of my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
output3 = findViewById(R.id.output3);
output3.setMovementMethod(ScrollingMovementMethod.getInstance());
connection();
}
public void connection(){
try {
String packagename = "com.facebook.katana";
URL url = new URL("http://play.google.com/store/apps/details?id="+packagename+"&hl=en");
URLConnection urlConn = url.openConnection();
HttpURLConnection con = (HttpURLConnection) urlConn;
con.setUseCaches(false);
con.setAllowUserInteraction(false);
con.setRequestMethod("GET");
con.connect();
int status = con.getResponseCode();
if (status == HttpURLConnection.HTTP_NOT_FOUND){
output3.append("not from google play store");
}
if (status == HttpURLConnection.HTTP_OK) {
output3.append("google App Store");
}
if (status != HttpsURLConnection.HTTP_NOT_FOUND && status != HttpsURLConnection.HTTP_OK)
output3.append("Other Response");
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
First of all HTTP requests are no longer support on the main thread so you must use a parallel Thread, or simple use an AsyncTask. Check below code for AsyncTask.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
output3 = findViewById(R.id.output3);
output3.setMovementMethod(ScrollingMovementMethod.getInstance());
AsyncTask.execute(new Runnable() {
#Override
public void run() {
connection();
}
});
}
Second thing is make sure Internet permission is added in your manifest.

App crashes when trying to call another onGestureListenerAdapter()

I have created 2 onTapEvent listener to add markers of different icons to my map through clicking of different buttons. However, I was only able to add 1 type of marker, the second button(add crowd) will crash my app after i clicked it.
Here is the example of my code for the buttons :
Set Destination:
private void initAddDestinationButton() {
m_setDetinationButton = (Button) findViewById(R.id.setDestinationButton);
m_setDetinationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*
* Clear map if previous results are still on map,otherwise proceed to creating
* route
*/
if (map != null && m_mapRoute != null) {
map.removeMapObject(m_mapRoute);
m_mapRoute = null;
} else
{
addDestination();
}
}
});
}
private void addDestination() {
if (destinationMarker == null) {
image = new Image();
try {
image.setImageResource(R.drawable.letterx);
} catch (final IOException e) {
e.printStackTrace();
}
}
mapFragment.getMapGesture().removeOnGestureListener(addCrowdListener2);
mapFragment.getMapGesture().addOnGestureListener(setDestinationListener2, 1, true);
}
Add Crowd :
private void initAddCrowdButton() {
m_addCrowdButton = (Button) findViewById(R.id.addCrowdButton);
m_addCrowdButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view2) {
if (map != null && m_mapRoute != null) {
map.removeMapObject(m_mapRoute);
m_mapRoute = null;
} else
{
addCrowd();
}
}
});
}
private void addCrowd() {
if (blocked == null) {
image2 = new Image();
try {
image.setImageResource(R.drawable.marker);
} catch (final IOException e) {
e.printStackTrace();
}
}
mapFragment.getMapGesture().removeOnGestureListener(setDestinationListener2);
mapFragment.getMapGesture().addOnGestureListener(addCrowdListener2, 10, true);
}
Here are the 2 onTapEvent listeners that I declared:
private MapGesture.OnGestureListener addCrowdListener2 = new MapGesture.OnGestureListener.OnGestureListenerAdapter() {
#Override
public boolean onTapEvent(PointF pointF) {
GeoCoordinate e = map.pixelToGeo(pointF);
MapMarker b = new MapMarker(e, image2);
blockList.add(b);
b.setAnchorPoint(new PointF(image.getWidth()/2, image.getHeight()));
map.addMapObject(b);
blocked = blockList.get(blockList.size() - 1);
blockedPath = blocked.getCoordinate();
blockedRoad = RoadElement.getRoadElement(blockedPath, "eng" );
return super.onTapEvent(pointF);
}
};
private MapGesture.OnGestureListener setDestinationListener2 = new MapGesture.OnGestureListener.OnGestureListenerAdapter() {
#Override
public boolean onTapEvent(PointF pointF) {
GeoCoordinate endpoint = map.pixelToGeo(pointF);
MapMarker m = new MapMarker(endpoint,image);
markerList.add(m);
m.setAnchorPoint(new PointF(image.getWidth()/2, image.getHeight()));
map.addMapObject(m);
destinationMarker = markerList.get(markerList.size() - 1);
destination = destinationMarker.getCoordinate();
return super.onTapEvent(pointF);
}
};
i have declared the buttons inside OnEngineInitiaizatioCompleted(). So far, only Set Destination button runs normally. Clicking on Add Crowd will crash my app (clicked on it before and after clicking Set Destination, crash the app upon clicking)
Here is the stack trace from its crash :
02-26 22:22:33.907 2233-3776/com.google.android.googlequicksearchbox:search W/ErrorProcessor: onFatalError, processing error from engine(4)
com.google.android.apps.gsa.shared.speech.a.g: Error reading from input stream
at com.google.android.apps.gsa.staticplugins.recognizer.i.a.a(SourceFile:342)
at com.google.android.apps.gsa.staticplugins.recognizer.i.a$1.run(SourceFile:1367)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)
Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.
at com.google.android.apps.gsa.speech.audio.Tee.g(SourceFile:2531)
at com.google.android.apps.gsa.speech.audio.ap.read(SourceFile:555)
at java.io.InputStream.read(InputStream.java:101)
at com.google.android.apps.gsa.speech.audio.al.run(SourceFile:362)
at com.google.android.apps.gsa.speech.audio.ak$1.run(SourceFile:471)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
at java.lang.Thread.run(Thread.java:761) 
at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85) 
and
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.here.android.mpa.common.Image.setImageResource(int)' on a null object reference
at com.here.android.example.basicpositioningsolution.BasicPositioningActivity.addCrowd(BasicPositioningActivity.java:532)
at com.here.android.example.basicpositioningsolution.BasicPositioningActivity.access$1600(BasicPositioningActivity.java:87)
at com.here.android.example.basicpositioningsolution.BasicPositioningActivity$7.onClick(BasicPositioningActivity.java:521)
at android.view.View.performClick(View.java:5619)
at android.view.View$PerformClick.run(View.java:22295)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6342)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770)
Suppressed: java.lang.Throwable: HERE SDK Version: 3.6.0.523
at com.nokia.maps.MapsEngine$l.uncaughtException(MapsEngine.java:377)
at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1068)
at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1063)
at java.lang.Thread.dispatchUncaughtException(Thread.java:1979)
I think your resource R.drawable.marker cannot be rendered by the SDK. What kind of image resource is it? Only bitmap resources are supported.

How do i use a URL to set an setImageBitmap for a ImageView?

in manifest:
<uses-permission android:name="android.permission.INTERNET">
in the onCreate method:
webImage = (ImageView) findViewById(R.id.webimage);
String urlImage = "https://thetab.com/blogs.dir/91/files/2017/01/maxresdefault-1.jpg";
// Set setImageBitmap to Bitmap created by getURLBitmap method
webImage.setImageBitmap(getURLBitmap(urlImage));
in the getURLBitmap method:
if(!urlString.isEmpty() || urlString != null) {
InputStream inputStream = null;
// pass the string into a URL object
try {
URL urlForImage = new URL(urlString);
// cast url openConnection into HttpURLConnection
HttpURLConnection connection = (HttpURLConnection) urlForImage.openConnection();
// Set HttpURLConnection setDoInput to true
connection.setDoInput(true);
// Start HttpURLConnection connection
connection.connect();
if(connection.getResponseCode() == 200) {
// Start reading Http inputStream (getInputStream) and use it to initialize a InputStream object
inputStream = connection.getInputStream();
// pass InputStream object into a BitmapFactory's decodeStream (is a static method)
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// set Bitmap object to decodedStream
return bitmap;
}
// return Bitmap
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
I keep getting this error:
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.EX.perfectmoment, PID: 26747
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.EX.perfectmoment/com.example.EX.perfectmoment.MemeMainActivity}: android.os.NetworkOnMainThreadException
You are getting this error because you are running a network operation on the UI thread, which is something that is very looked down upon in Android Dev as it often results in an unresponsive UI and thus, a bad user experience. I recommend either creating your own ASyncTask, which would do the network operations in another thread and feed it back to the UI thread, or use one of the many popular image libraries there are for Android, such as Picasso or Glide.
As said in above comment running network task on UI thread in android no longer supported so you have to do UI blocking task on separate thread either using AsyncTask or some other thread mechanism available.
So by using AsynTask you can do it like mention below code snippet.
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity{
ImageView webImage;
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webImage = (ImageView) findViewById(R.id.imageView1);
new SetImage().execute();
}
private class SetImage extends AsyncTask<Void, Void, Bitmap>{
final String urlImage = "https://thetab.com/blogs.dir/91/files/2017/01/maxresdefault-1.jpg";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(Void... params) {
Bitmap image = getURLBitmap(urlImage);
return image;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
webImage.setImageBitmap(bitmap);
}
}
private Bitmap getURLBitmap(String urlString){
if(!urlString.isEmpty() || urlString != null) {
InputStream inputStream = null;
// pass the string into a URL object
try {
URL urlForImage = new URL(urlString);
// cast url openConnection into HttpURLConnection
HttpURLConnection connection = (HttpURLConnection) urlForImage.openConnection();
// Set HttpURLConnection setDoInput to true
connection.setDoInput(true);
// Start HttpURLConnection connection
connection.connect();
if(connection.getResponseCode() == 200) {
// Start reading Http inputStream (getInputStream) and use it to initialize a InputStream object
inputStream = connection.getInputStream();
// pass InputStream object into a BitmapFactory's decodeStream (is a static method)
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// set Bitmap object to decodedStream
return bitmap;
}
// return Bitmap
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}

Download task throws exception with no internet

I have an app that downloads the current unix timestamp from the internet. The code for the download task is as follows.
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(SplashActivity.this, "you aint got no internet man", Toast.LENGTH_SHORT).show();
}
return null;
}
I run this code in onCreate
DownloadTask task = new DownloadTask();
String result = null;
try {
result = task.execute("http://www.currenttimestamp.com/").get();
Pattern p = Pattern.compile("current_time = (.*?);");
Matcher m = p.matcher(result);
m.find();
String unixTime = (m.group(1));
timeStamp = Integer.parseInt(unixTime);
endTimeMaths = endTime/1000;
} catch (InterruptedException e) {
e.printStackTrace();
Toast.makeText(SplashActivity.this, "you aint got no internet man", Toast.LENGTH_SHORT).show();
} catch (ExecutionException e) {
e.printStackTrace();
Toast.makeText(SplashActivity.this, "you aint got no internet man", Toast.LENGTH_SHORT).show();
}
timeDelta = timeStamp-endTimeMaths;
Log.i("TimeDelta", timeDelta+"");
//If dem boys cheatin
if (timeDelta < 1){
Toast.makeText(SplashActivity.this, "You cheatin boi?", Toast.LENGTH_SHORT).show();
reward=false;
} else if (timeDelta >= 300){
reward = true;
Toast.makeText(SplashActivity.this, "Here is your reward for being gone", Toast.LENGTH_SHORT).show();
}
}
The Exception is as follows
09-04 21:26:42.853 8459-8493/com.firefluxentertainment.retroclicker E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.firefluxentertainment.retroclicker, PID: 8459
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:318)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:346)
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:260)
at com.firefluxentertainment.retroclicker.SplashActivity$DownloadTask.doInBackground(SplashActivity.java:155)
at com.firefluxentertainment.retroclicker.SplashActivity$DownloadTask.doInBackground(SplashActivity.java:119)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
at java.lang.Thread.run(Thread.java:761)
Since all the code is in try catch braces I have no idea why it would be crashing. Any help is very much appreciated!
This is because you are trying to show toast in a non-UI thread. There are multiple solutions to your problem :
Create a handler in the Activity and pass it along to DownloadTask. Simply send a message in Handler and show the toast.
Another solution is to send the context in DownloadTask and show the toast as
context.runOnUIThread(new Runnable() {
public void run(){
Toast.showToast("your message here")
}
)
You can send the result of your task in onPostExecute() and show Toast there.

java.net.UnknownHostException : api.openweathermap.org

I'm following a course on udacity 'Developing Android Apps'. Following is the code of ForecastFragment class which is suppose to get data in json format from the url(http://api.openweathermap.org/data/2.5/forecast/daily?q=Delhi,in&mode=json&cnt=7&units=metric).
public class ForecastFragment extends Fragment {
public ForecastFragment() {
}
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
String[] data = {
"Today-Sunny-34", "Tommorow-Rainy-233", "Wednesday-Cloudy-21", "Thursday-Monayblue-18", "Frida-Rainy-23", "Saturday-Rainy-22", "Sunday-Strorm-100"
};
List<String> weekForecast = new ArrayList<String>(Arrays.asList(data));
ArrayAdapter<String> mForecastAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, weekForecast);
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
return rootView;
}
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater){
inflater.inflate(R.menu.forecastfragment, menu);
}
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(id==R.id.action_refresh){
FetchWeatherTask fetch = new FetchWeatherTask();
fetch.execute();
return true;}
return super.onOptionsItemSelected(item);
}
public class FetchWeatherTask extends AsyncTask<Void,Void,Void>{
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
#Override
protected Void doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String forecastJsonStr = null;
try {
URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=Delhi,in&mode=json&cnt=7&units=metric");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) return null;
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) return null;
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG,"Forecast Json String" + forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error", e);
return null;
} finally {
if (urlConnection != null) urlConnection.disconnect();
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("placeholder fragment", "error closing stream", e);
}
}
}
return null;
}
}
}
However, I'm repeatedly getting this error.
07-20 12:49:14.063 2392-2486/com.example.android.sunshine.app E/FetchWeatherTask﹕ Error
java.net.UnknownHostException: api.openweathermap.org
at java.net.InetAddress.lookupHostByName(InetAddress.java:512)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:300)
at java.net.InetAddress.getAllByName(InetAddress.java:259)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:69)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:48)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:322)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:285)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:267)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:205)
at com.example.android.sunshine.app.ForecastFragment$FetchWeatherTask.doInBackground(ForecastFragment.java:119)
at com.example.android.sunshine.app.ForecastFragment$FetchWeatherTask.doInBackground(ForecastFragment.java:83)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
at java.lang.Thread.run(Thread.java:1027)
Following are the things I've already checked:-
mobile phone has internet access.
AndroidManifest.xml declares the permission for internet usage.
The url works fine in the browser,but I'm clueless as to why this error is coming up.
Also, I'm running the app on my android phone(api 10).
If anyone could please provide a solution or point me in the right direction,it would be great. Thank you.
I had the same issue. Yet I did not turn WiFi on on my mobile phone. Activating wifi solved the problem for me.
I copied your Async class as-is and ran it in a new project on a KitKat VM on my Mac machine. Here are the results:
07-19 14:40:32.070 1670-1683/centerorbit.com.myapplication V/FetchWeatherTask﹕ Forecast Json String{"city":{"id":1273294,"name":"Delhi","coord":{"lon":77.216667,"lat":28.666668},"country":"IN","population":0},"cod":"200","message":0.0095,"cnt":7,"list":[{"dt":1437285600,"temp":{"day":29,"min":28.21,"max":29,"night":28.21,"eve":29,"morn":29},"pressure":984.15,"humidity":88,"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03n"}],"speed":1.66,"deg":64,"clouds":36},{"dt":1437372000,"temp":{"day":29.15,"min":25.17,"max":31.21,"night":27.92,"eve":31.21,"morn":26.55},"pressure":986.25,"humidity":95,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":3.22,"deg":86,"clouds":88,"rain":10.65},{"dt":1437458400,"temp":{"day":30.46,"min":25.15,"max":31.57,"night":27.94,"eve":31.1,"morn":25.15},"pressure":988.81,"humidity":83,"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"speed":6.41,"deg":111,"clouds":68,"rain":0.45},{"dt":1437544800,"temp":{"day":30.63,"min":26.12,"max":32.69,"night":28.12,"eve":32.69,"morn":26.12},"pressure":991.01,"humidity":81,"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"speed":3.57,"deg":118,"clouds":64},{"dt":1437631200,"temp":{"day":34.27,"min":25.81,"max":35.34,"night":27.1,"eve":33.11,"morn":25.81},"pressure":989.86,"humidity":78,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":2.06,"deg":74,"clouds":8,"rain":3.94},{"dt":1437717600,"temp":{"day":31.12,"min":25.71,"max":31.12,"night":26.68,"eve":30.83,"morn":25.71},"pressure":991.3,"humidity":0,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":1.06,"deg":184,"clouds":13,"rain":7.82},{"dt":1437804000,"temp":{"day":31.68,"min":25.88,"max":32.17,"night":27.01,"eve":32.17,"morn":25.88},"pressure":989.57,"humidity":0,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":1.28,"deg":226,"clouds":52,"rain":5.89}]}
It appears that your code is fine, and something is not right with your system/network. I would recommend restarting your phone/computer to see if that fixes the issue. If not, try using a different network (disconnect from your home WiFi and use Cell network).
You have registered permission in androidManifest to access Internet
<uses-permission android:name="android.permission.INTERNET"/>
Append APIKey at the end of URL
To get APIKey you have to create acount on openweathermap.org
e.g. http://api.openweathermap.org/data/2.5/forecast/daily?q=Delhi,in&mode=json&cnt=7&units=metric&appid=yourapiid"
Detail Process to Get APIKey is

Categories