I am trying to implement the following code:
public class CheckSomeStaff extends AsyncTask<String, String, String> {
private HttpURLConnection urlc;
public boolean hasActiveInternetConnection(Context context) {
try {
this.doInBackground();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
if (isConnectingToInternet() == true) {
try {
urlc = (HttpURLConnection) (new URL(
"http://whatever.com/whatever_data_download/"
+ "myDB.db").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(500);
urlc.connect();
urlc.getResponseCode();
} catch (IOException e) {
Log.d(LOG_TAG, "Error checking internet connection", e);
}
return null;
} else {
Log.d(LOG_TAG, "No network available!");
}
return null;
}
}
It works fine on emulator but when I am trying to download my application to device it trows out NullPointerException at the following line:
if (urlc.getResponseCode() == 200) {
Why does the null pointer occur on a device?
if this block
if (isConnectingToInternet() == true) {
is false, the urlc is never initialized, thus you get a NullPointerException.
Try this way
public class CheckSomeStaff extends AsyncTask<Void, Void, Boolean> {
HttpURLConnection urlc;
int result = -1;
public boolean hasActiveInternetConnection() {
execute();
while (result == -1) {
}
if (result == 200) {
return true;
} else {
return false;
}
}
#Override
protected Boolean doInBackground(Void... arg0) {
try {
urlc = (HttpURLConnection) (new URL("http://whatever.com/whatever_data_download/" + "myDB.db").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(500);
urlc.connect();
return urlc.getResponseCode() == 200 ? true : false;
} catch (IOException e) {
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
try {
this.result = urlc.getResponseCode();
} catch (Exception e) {
this.result = -2;
}
super.onPostExecute(result);
}
}
Initialize "urlc" like-
URL url = new URL("Your URL");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
Related
I need to develop an app with a service that is able to get data from a server when the app is in background. I used a thread in order to run ThreadWorker() for long time when the app is background. (Previously I did a thread in my app: when the app was onStop() the thread stopped and that was not good for me. So I decided to go for a Service)
public class ServiceBG extends Service
{
public class LocalBinder extends Binder {
ServiceBG getService() {
return ServiceBG.this;
}
}
private final IBinder mBinder = new LocalBinder();
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return mBinder;
}
#Override
public void onCreate() {
InitializeVariable();
}
private void InitializeVariable()
{
this.mContext = this;
this.working = false;
this.canRun = true;
this.serverCOM = new ServerCOM(myUrl,departmentID);
ThreadWorker();
}
private void ThreadWorker()
{
thread = new Thread(new Runnable() {
#Override
public void run() {
int i=0 ;
while (canRun)
{
try {
while (!serverCOM.hasActiveInternetConnection(mContext)) {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list = serverCOM.GetFirmwareDeviceNameList();
}
catch (Exception e)
{
e.printStackTrace();
}
if(listDevice!=null) {
Log.d("serviceBG", String.valueOf(list.size()));
if (list.size() > 0) {
working = true;
Intent intent = new Intent();
intent.setAction(MY_ACTION);
intent.putExtra("DATAPASSED",list.get(0));
sendBroadcast(intent);
//complete action
}
}
try {
FirmwareUpdaterThread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
return Service.START_STICKY;
}
}
My ServerCOM object is made like this:
public class ServerCOM {
public List<String> GetFirmwareDeviceNameList()
{
AsyncGetNames asyncGetNames=new AsyncGetNames();
asyncGetNames.execute(URL);
try {
this.NameList =asyncGetNames.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return this.NameList;
}
public boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.e(LOG_TAG, "Error checking internet connection", e);
}
} else {
Log.d(LOG_TAG, "No network available!");
}
return false;
}
private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
private class AsyncGetNames extends AsyncTask<String, String, List<String>>
{
public AsyncGetNames()
{
}
#Override
public List<String> doInBackground(String... params){
List<String> list = null;
try {
URL url = new URL(params[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "*/*");
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
//readStream(in);
String resultString = Operations.convertStreamToString(inputStream);
inputStream.close();
String[] list1 = new Gson().fromJson(resultString, String[].class);
list= Arrays.asList(list1);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
}
}
When I start this service I can get data from server. After more or less half an hour the service is not able to send requests anymore (I see this from Logcat in Android Studio). It seems that the request thread goes to sleep. Is there some possible interaction between this thread and AsyncTask request?
I want to check if a local website from my apache-server is up and reachable.
If read through countless threads about HttpUrlconnection and came up with the following code. Manifest Internet Persmission is set. The website is currently running and I can access it via my smartphones webbrowser. I´ve also read about Input and Outputstreams, do I need them for my task?
public class MainActivity extends AppCompatActivity {
boolean value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
state(value);
}
public boolean state(boolean value){
try {
URL url = new URL("http://192.168.178.59:8090/");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("HEAD");
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setReadTimeout(3000);
value = true;
Toast.makeText(MainActivity.this,"true",Toast.LENGTH_SHORT).show();
return value;
} catch (MalformedURLException e) {
e.printStackTrace();
value = false;
Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
return value;
} catch (IOException e) {
e.printStackTrace();
value = false;
Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
return value;
}
}
}
EDIT: Solution from Exception
import java.net.HttpURLConnection;
import android.os.AsyncTask;
public class MainActivity extends AppCompatActivity {
boolean value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new HttpTask().execute(value);
}
private class HttpTask extends AsyncTask<Boolean, Void, Boolean>
{
#Override
protected Boolean doInBackground(Boolean... params) {
// TODO Auto-generated method stub
boolean value=params[0];
try {
URL url = new URL("http://192.168.178.59:8090/");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("HEAD");
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setReadTimeout(3000);
httpURLConnection.connect();
value = true;
//Toast.makeText(MainActivity.this,"true",Toast.LENGTH_SHORT).show();
return value;
} catch (MalformedURLException e) {
e.printStackTrace();
value = false;
//Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
return value;
} catch (IOException e) {
e.printStackTrace();
value = false;
//Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
return value;
}
}
#Override
protected void onPostExecute(Boolean result) {
if(result){
Toast.makeText(MainActivity.this,"true",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
}
}
}
}
EDIT: Service Solution
#Override
protected void onPostExecute(Boolean result) {
if(result){
Toast.makeText(NotifiyService.this,"true",Toast.LENGTH_SHORT).show();
//Notification in Status Bar
NotificationCompat.Builder builder = new NotificationCompat.Builder(NotifiyService.this);
builder.setSmallIcon(R.drawable.dummy);
Intent intent = new Intent(NotifiyService.this, Main22Activity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(NotifiyService.this,0,intent,0);
builder.setContentIntent(pendingIntent);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.dummy));
builder.setContentTitle(getResources().getString(R.string.newNotify));
builder.setContentText(getResources().getString(R.string.newNotify2));
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1,builder.build());
}
else{
Toast.makeText(NotifiyService.this,"false",Toast.LENGTH_SHORT).show();
}
Replace your code with below given code.
import java.net.HttpURLConnection;
import android.os.AsyncTask;
public class MainActivity extends AppCompatActivity {
boolean value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new HttpTask().execute(value);
}
private class HttpTask extends AsyncTask<Boolean, Void, Boolean>
{
#Override
protected Boolean doInBackground(Boolean... params) {
// TODO Auto-generated method stub
boolean value=params[0];
try {
URL url = new URL("http://192.168.178.59:8090/");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("HEAD");
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setReadTimeout(3000);
httpURLConnection.connect();
value = true;
//Toast.makeText(MainActivity.this,"true",Toast.LENGTH_SHORT).show();
return value;
} catch (MalformedURLException e) {
e.printStackTrace();
value = false;
//Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
return value;
} catch (IOException e) {
e.printStackTrace();
value = false;
//Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
return value;
}
}
#Override
protected void onPostExecute(Boolean result) {
if(result){
Toast.makeText(MainActivity.this,"true",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
}
}
}
}
EDIT:
To launch new activity on notification click, add these lines after Intent intent = new Intent(NotifiyService.this, Main22Activity.class);:
intent .setAction(Intent.ACTION_MAIN);
intent .addCategory(Intent.CATEGORY_LAUNCHER);
intent .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Simply run this code:-
public boolean state(boolean value){
URL url;
String response = "";
try {
url = new URL("http://192.168.178.59:8090/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
//writer.write(getPostDataString(postDataParams));
writer.write(value);
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
System.out.println(response);
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
}
I have developed a code to check if a url exists but it is not doing anything, could you please point out my mistake?
public void main(String s[]) {
String URLName = "http://www.google.com/";
Log_in uRLExists = new Log_in();
uRLExists.checkURLExists(URLName);
}
public void checkURLExists(String URLName) {
try {
HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();
HttpURLConnection.setFollowRedirects(false);
con.setRequestMethod("HEAD");
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
Toast.makeText(getBaseContext(), "URL Exist", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "URL not Exists", Toast.LENGTH_SHORT).show();
}
}
catch(UnknownHostException unknownHostException){
}
catch (Exception e) {
e.printStackTrace();
}
}
On the Toasts, assuming this code is within an Activity, change getBaseContext() to getApplicationContext().
You can't do Network on MainThread. You are most likely getting android.os.NetworkOnMainThreadException. You should call checkURLExists() from a worker thread.
You could use AsyncTask class to do a network operation.
public class UrlChecker extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
String url = params[0];
// Check your URL here
return true;
}
#Override
protected void onPostExecute(Boolean exists) {
// Do something with your result
}
}
You did not call connect method.
After con.setRequestMethod("HEAD");
Add this: con.connect();
BTW, you should put the code in a new thread. Don't run it on the main thread, it will hang the App.
Try this:
new Thread(){
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
try {
URL url = new URL(customURL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("HEAD");
con.connect();
Log.i(TAG, "con.getResponseCode() IS : " + con.getResponseCode());
if(con.getResponseCode() == HttpURLConnection.HTTP_OK){
Log.i(TAG, "Sucess");
}
} catch (Exception e) {
e.printStackTrace();
Log.i(TAG, "fail");
}
}
}.start();
I try to write an android program to check internet connection with two different methods. The first one is the most common method, CheckInternetConnection(), and the second method is through connecting to a website, ConnectGoogleTest().
The first one work perfectly, but in the second one my tablet hang! anybody knows why ?
The codes are:
public class myITClass {
private Context ctx ;
public myITClass(Context context){
this.ctx = context;
}
public boolean CheckInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
//NetworkInfo ni = cm.getActiveNetworkInfo();
if (cm.getActiveNetworkInfo() == null) {
// There are no active networks.
return false;
} else {
return true;
}
}
public boolean googlePingTest(){
boolean res = false ;
try {
URL url = new URL("http://www.google.com/");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(15000);
urlc.connect();
if (urlc.getResponseCode() == 200) { res = true; }
} catch (MalformedURLException e1) {
res = false;
} catch (IOException e) {
res = false ;
}catch (Exception e){
res = false ;
}
return res;
}
}
You can send a ping to http://www.google.com/ through HttpURLConnection. Please make sure that you doing it in the background thread. Creating a network task must be run in the background. There are 3 options to do that:
Using AsyncTask
Using IntentService
Using Service
In this time, we will use AsyncTask. So create a private class inside your Activity:
private boolean res = false;
private class PingTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... urlSite) {
HttpURLConnection urlc = null;
try {
URL url = new URL("http://www.google.com/");
urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(15000);
urlc.setRequestMethod("GET");
urlc.connect();
if (urlc.getResponseCode() == 200) { res = true; }
} catch (MalformedURLException e1) {
res = false;
} catch (IOException e) {
res = false ;
}catch (Exception e){
res = false ;
}finally{
if (urlc != null) {
try{
// close the connection
urlc.disconnect();
}catch (Exception e){
e.printStackTrace();
}
}
}
return null;
}
}
Don't forget to add this field in your class:
private boolean res = false;
Create a method to get the status:
public boolean getStatus(){
return status;
}
How to use?
Execute the PingTask first to check the status:
PingTask ping = new PingTask();
ping.execute();
Get the status:
// if the connection is available
if(getStatus()==true){
// do your thing here.
}
The second method calls network synchronously on main thread, and that blocks the UI. Try using AsyncTask for it.
public class UrlVarificationTask extends AsyncTask<Void, Void, Integer> {
private String url;
private UrlVarificationDelegate delegate;
private HttpURLConnection huc;
public UrlVarificationTask(String url, UrlVarificationDelegate delegate) {
this.url = url;
this.delegate = delegate;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Integer doInBackground(Void... params) {
int responseCode = 0;
try {
System.setProperty("http.keepAlive", "false");
URL u = new URL(url);
huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("HEAD");
huc.connect();
responseCode = huc.getResponseCode();
} catch (MalformedURLException mal) {
responseCode = -555;
} catch (IOException io) {
responseCode = -444;
} catch (Exception ex) {
responseCode = -333;
ex.printStackTrace();
}
if (huc != null) {
try {
huc.getInputStream().close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
huc.disconnect();
}
Logger.debug("Response Code==" + responseCode);
return responseCode;
}
#Override
protected void onPostExecute(Integer responseCode) {
delegate.urlVarificationResponseCode(responseCode);
super.onPostExecute(responseCode);
}
}
I used above dode for validating url,
if HEAD give me response code 200 then only I open a url to webview.
but once I call this it keep connection and not allow any other http request even after close, what to do ?
Safe use of HttpURLConnection
huc.setRequestProperty("keep-alive", "false");
this is working as HttpURLConnection keep connection alive and hence we cann't make make further request so keep-alive setting to false resolve this problem.
For properly closing the HttpURLConnection go to the link
By this URL is closed.