Checking for internet connectivity in Android app [duplicate] - java

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 7 years ago.
I'm trying to check for INTERNET connectivity from an Android app but just keep running in to problems.
I'm NOT looking for code that tests for an available network connection - I've got that bit working - this is to test whether I can reach an internet site or not.
(I appreciate that if I am behind a system which presents a logon screen instead of the requested site, I may not get the exact result I want, but I will handle that later)
Thanks to the following question I think I've made some progress, but when I run the app it crashes out (error info below).
The code I have so far is as follows (and I must admit that I find the try/catch stuff a bit puzzling and tedious :-/ )
static public boolean isInternetReachable() {
int statusCode = -1;
try{
URL url = new URL("http://www.google.com/humans.txt");
HttpURLConnection http = (HttpURLConnection) url.openConnection();
statusCode = http.getResponseCode();
http.disconnect();
} catch (MalformedURLException ex) {
return false;
} catch (IOException ex) {
return false;
}
if (statusCode == HttpURLConnection.HTTP_OK) {
return true;
}
else
{
//connection is not OK
return false;
}
}
I'm sure there are neater ways to do this and so any general advice is welcome.
The error that I'm getting when the app crashes is:
01-24 19:53:14.767 10617-10617/com.nooriginalthought.bluebadgeparking E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.nooriginalthought.bluebadgeparking, PID: 10617
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nooriginalthought.bluebadgeparking/com.nooriginalthought.bluebadgeparking.PreLoadChecks}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2411)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1155)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:236)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:491)
at com.nooriginalthought.bluebadgeparking.PreLoadChecks.isInternetReachable(PreLoadChecks.java:41)
at com.nooriginalthought.bluebadgeparking.PreLoadChecks.onCreate(PreLoadChecks.java:70)
at android.app.Activity.performCreate(Activity.java:5958)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474) 
at android.app.ActivityThread.access$800(ActivityThread.java:144) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:155) 
at android.app.ActivityThread.main(ActivityThread.java:5696) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823) 

As David is mentioning in the comments, you should just Google for the Exception name and try to get a turnaround by yourself.
By looking at the StackOverflow answer that he is referring to, you need to make all network communications outside the Main thread. The most used way to do this is by creating an AsyncTask.
In your case, it would look (you can create a new InternetTask.java or just append it to your current MainActivity.java) something like:
class InternetTask extends AsyncTask<Void, Void, Boolean>{
private MainActivity activity;
InternetTask(MainActivity activity){
this.activity = activity;
}
#Override
protected Boolean doInBackground(Void... params) {
int statusCode = -1;
try{
URL url = new URL("http://www.google.com/humans.txt");
HttpURLConnection http = (HttpURLConnection) url.openConnection();
statusCode = http.getResponseCode();
http.disconnect();
} catch (MalformedURLException ex) {
return false;
} catch (IOException ex) {
return false;
}
if (statusCode == HttpURLConnection.HTTP_OK) {
return true;
}
else
{
//connection is not OK
return false;
}
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
activity.receiveMagic(aBoolean);
}
}
Then, you just need to add a new public method in your activity to receive the boolean in your MainActivity.
public void receiveMagic(Boolean isGood){
if (isGood){
Toast.makeText(MainActivity.this, "It is good", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this, "It is not connected", Toast.LENGTH_SHORT).show();
}
}
And you would need to call your new AsyncTask from your Activity with:
new InternetTask(this).execute();
Make sure you add the internet permission to your Manifest also.

Related

Send data to a Php Script with Android Studio [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 3 years ago.
I have to send some parameters from my Android application to a Php script, for a database insert.
I tried this script on Eclipse and it works fine.
But when I try to run it on Android it crashes.
public static void Insert(){
try {
// open a connection to the site
URL url = new URL("http://192.168.1.105/JavaInsert.php");
URLConnection con = url.openConnection();
// activate the output
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
// send your parameters to your site
ps.print("&email=random#gmail.com");
//ps.print("&Company=Company");
//ps.print("&Shares=Shares");
//ps.print("&Date=Date");
con.getInputStream();
ps.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
System.out.print("Db error 1");
} catch (IOException e2) {
e2.printStackTrace();
System.out.print("Db error 1");
}
}
There are these errors in the LogCat section
07-28 14:28:07.259 20554-20554/com.example.ivan.rocketsocialstudioapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ivan.rocketsocialstudioapp, PID: 20554
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:389)
at android.view.View.performClick(View.java:6663)
at android.view.View.performClickInternal(View.java:6635)
at android.view.View.access$3100(View.java:794)
at android.view.View$PerformClick.run(View.java:26199)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7593)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384)
at android.view.View.performClick(View.java:6663) 
at android.view.View.performClickInternal(View.java:6635) 
at android.view.View.access$3100(View.java:794) 
at android.view.View$PerformClick.run(View.java:26199) 
at android.os.Handler.handleCallback(Handler.java:907) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:216) 
at android.app.ActivityThread.main(ActivityThread.java:7593) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987) 
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1523)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:390)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:231)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:213)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
at java.net.Socket.connect(Socket.java:621)
at com.android.okhttp.internal.Platform.connectSocket(Platform.java:145)
at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:141)
at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:112)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:184)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:258)
at com.example.ivan.rocketsocialstudioapp.MainActivity.Insert(MainActivity.java:72)
at com.example.ivan.rocketsocialstudioapp.MainActivity.send(MainActivity.java:45)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384) 
at android.view.View.performClick(View.java:6663) 
at android.view.View.performClickInternal(View.java:6635) 
at android.view.View.access$3100(View.java:794) 
at android.view.View$PerformClick.run(View.java:26199) 
at android.os.Handler.handleCallback(Handler.java:907) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:216) 
at android.app.ActivityThread.main(ActivityThread.java:7593) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987) 
07-28 14:28:07.284 20554-20554/com.example.ivan.rocketsocialstudioapp I/Process: Sending signal. PID: 20554 SIG: 9
The Php script works with Eclipse.
I've also already added the android Network and Internet Permissions
its because you cant run network operation on main thread it will cause the NetworkOnMainThreadException which you have
try networking libraries or do the operation on a AsyncTask
You need to create a Runnable Thread or AsyncTask to run network operations.
Check out my example below
private void login() {
JSONObject request = new JSONObject();
try {
//Populate the request parameters
request.put(KEY_USERNAME, username);
request.put(KEY_PASSWORD, password);
//Log.v("test", request.toString());
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsArrayRequest = new JsonObjectRequest
(Request.Method.POST, login_url, request, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
try {
//Check if user got logged in successfully
if (response.getInt(KEY_STATUS) == 0) {
session.loginUser(username, response.getString(KEY_FULL_NAME));
loadDashboard();
} else {
Toast.makeText(getApplicationContext(),
response.getString(KEY_MESSAGE), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
//Display error message whenever an error occurs
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});

java.lang.RuntimeException: Unable to resume activity with java.lang.IllegalArgumentException

Recently I sometimes got this exception when MainActivity called onResume().
java.lang.RuntimeException: Unable to resume activity {com.qau4d.c35s3.androidapp/com.xxx.XXX.XXX.MainActivity}: java.lang.IllegalArgumentException
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3400)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3440)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1510)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.IllegalArgumentException
at android.os.Parcel.readException(Parcel.java:1687)
at android.os.Parcel.readException(Parcel.java:1636)
at android.app.ActivityManagerProxy.isTopOfTask(ActivityManagerNative.java:5475)
at android.app.Activity.isTopOfTask(Activity.java:5961)
at android.app.Activity.onResume(Activity.java:1252)
at com.qau4d.c35s3.androidapp.onResume(XActivity.java:29)
at com.qau4d.c35s3.androidapp.onResume(MainActivity.java:196)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1269)
at android.app.Activity.performResume(Activity.java:6768)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3377)
Both in MainActivity and super class XActivity, only super.onResume(); is called. It's really strange to get this exception after a long time normal development.I checked some relative reference material but nothing got.
In the method Activity#isTopOfTask we can see:
private boolean isTopOfTask() {
if (mToken == null || mWindow == null) {
return false;
}
try {
return ActivityManager.getService().isTopOfTask(getActivityToken());
} catch (RemoteException e) {
return false;
}
}
And in ActivityManagerService#isTopOfTask we can found:
#Override
public boolean isTopOfTask(IBinder token) {
synchronized (this) {
ActivityRecord r = ActivityRecord.isInStackLocked(token);
if (r == null) {
throw new IllegalArgumentException();
}
return r.task.getTopActivity() == r;
}
}
So, I think that ActivityRecord is null.But I don't know why it is null....
There is insufficient information in your question to determine the cause of the java.lang.IllegalArgumentException, Unfortunately the android ActivityThread doesn't log the stacktrace of that exception, and the exception message appears to be empty.
However, it looks like there is a way forward. The exception is handled by the following code in the ActivityThread::performResumeActivity method:
} catch (Exception e) {
if (!mInstrumentation.onException(r.activity, e)) {
throw new RuntimeException(
"Unable to resume activity "
+ r.intent.getComponent().toShortString()
+ ": " + e.toString(), e);
}
}
If you register an Instrumentation class for your activity, it should be possible to use an onException method to log the stacktrace for the causal exception. Another possibility is to use Thread.setUncaughtExceptionHandler to set a handler for the thread in which the IllegalArgumentException is thrown.
These won't solve the problem (!) but it will get you a step closer to a solution.

Query working on local backend but not on deployed backend

class EndpointsAsyncTask extends AsyncTask<Void, Void, List<Quote>> {
private static QuoteEndpoint myApiService = null;
private Context context;
EndpointsAsyncTask(Context context) {
this.context = context;
}
#Override
protected List<Quote> doInBackground(Void... params) {
if(myApiService == null) { // Only do this once
/*QuoteEndpoint.Builder builder = new QuoteEndpoint.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});*/
// end options for devappserver
QuoteEndpoint.Builder builder = new QuoteEndpoint.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
.setRootUrl("https://momcares-987.appspot.com/_ah/api/");
myApiService = builder.build();
}
try {
return myApiService.listQuote().execute().getItems();
} catch (IOException e) {
return Collections.EMPTY_LIST;
}
}
#Override
protected void onPostExecute(List<Quote> result) {
for (Quote q : result) {
Toast.makeText(context, q.getWho() + " : " + q.getWhom(), Toast.LENGTH_LONG).show();
}
}
}
The above class has been included in my MainActivity.java file.
http://rominirani.com/2014/08/26/gradle-tutorial-part-9-cloud-endpoints-persistence-android-studio/
I have been following this tutorial. I manually inserted quotes (Quote is the bean I am using) in the API Explorer and I successfully get the list of quotes in my emulator when I run the local server and test. However, when I deploy the same backend and run the application, I get a NullPointerException in the onPostExecuteMethod. Please help. Thanks!
Error Log:
06-26 11:50:19.889 26342-26342/com.sickstudios.sickapplication W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x430d4140)
06-26 11:50:19.909 26342-26342/com.sickstudios.sickapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.sickstudios.sickapplication, PID: 26342
java.lang.NullPointerException
at com.sickstudios.sickapplication.EndpointsAsyncTask.onPostExecute(MainActivity.java:64)
at com.sickstudios.sickapplication.EndpointsAsyncTask.onPostExecute(MainActivity.java:25)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
at dalvik.system.NativeStart.main(Native Method)
06-26 11:50:23.639 26342-26342/com.sickstudios.sickapplication I/Process﹕ Sending signal. PID: 26342 SIG: 9
Try this:
http://www.momcares-987.appspot.com/_ah/api/
Sometimes https calls raise the connectivity issue.

Android FTP connection problems [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 7 years ago.
Hi I have been trying for two days to get a simple ftp connection to transfer a small xml file. I have tried lots of different examples of code, but all seem to give the same errors.
Main FTP class code:
public class MyFTPClientFunctions {
public FTPClient mFTPClient = null;
public boolean ftpConnect(String host, String username, String password, int port) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
return status;
}
//Log.d(TAG, "Error: could not connect to host " + host);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private Context getApplicationContext() {
return null;
}
}
Main Activity code to send
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//set up FTP file transfer here
MyFTPClientFunctions ftpSend = new MyFTPClientFunctions();
ftpSend.ftpConnect("xxxxxx.asuscomm.com","admin","xxxxxxxxxx",21);
}
LogCat messages
06-22 12:09:21.460 17329-17329/com.example.rats.moham_2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.rats.moham_2, PID: 17329
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getByName(InetAddress.java:305)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:203)
at com.example.rats.moham_2.MyFTPClientFunctions.ftpConnect(MyFTPClientFunctions.java:25)
at com.example.rats.moham_2.MainActivity$3.onClick(MainActivity.java:155)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
This Exception is usualy thrown, if you are using the network on the main thread.
Please use Async Tasks.

Android HttpClient Asynctask

I have been stuck on this problem for a day or two now, so i decided to see if anyone out there could help me.
The current goal i have, is to make a HttpPost that connects to, and executes a script that i have on my Wamp server. I have implemented a class that extends AsyncTask, and includes the 3 necessary methods, that are required in order for it to work effectively.
I will first show you the code that i have used to put the variables into a Json Object, followed by the JSONParser class, that initializes the HttpPost and then executes it.
Afterwards i will tell you all about the log errors and the narrowing down of the problem; you all problem know what the problem may be already, and if you don't want to read below, briefly, it is caused by the line of code that calls the parser class.
Note: I am using this as a starting point for this type of work, so please understand that it is simple in terms of its passed parameters.
Further Note: I am using Eclipse, and i am testing with the inbuilt Emulator.
METHOD - CreateNewUser
/**
* Background Async Task to Create new user
*/
class CreateNewUser extends AsyncTask<String, String, String>{
/**
* Before starting background thread show progress dialog
*/
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(AddUserActivity.this);
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/*
* Creating user
*/
#Override
protected String doInBackground(String... args){
String username = inputUsername.getText().toString();
String password = inputPassword.getText().toString();
// Building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
// getting JSON object
// Note that create user url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_user, "POST",params);
// check log cat for response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
Next, the JSONParser Class:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get JSON from URL
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
If i remove the line : ( JSONObject json = jsonParser.makeHttpRequest(url_create_user, "POST",params); ) - of course with intending the try catch out, then the program does not crash, when i press the button that calls the CreateNewUser class.
If i do not do that, my program brings up a loading screen that swirls around until it becomes unresponsive, and asks me to close down the application.
The logs describe Async errors, and illegal state ones:
E/AndroidRuntime(1132): FATAL EXCEPTION: AsyncTask #2
E/AndroidRuntime(1132): Process: com.example.propertypanther, PID: 1132
E/AndroidRuntime(1132): java.lang.RuntimeException: An error occured while executing
doInBackground()
E/AndroidRuntime(1132): at android.os.AsyncTask$3.done(AsyncTask.java:300)
E/AndroidRuntime(1132): at
java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
E/AndroidRuntime(1132): at
java.util.concurrent.FutureTask.setException(FutureTask.java:222)
E/AndroidRuntime(1132): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
E/AndroidRuntime(1132): at
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
E/AndroidRuntime(1132): at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
E/AndroidRuntime(1132): at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
E/AndroidRuntime(1132): at java.lang.Thread.run(Thread.java:841)
E/AndroidRuntime(1132): Caused by: java.lang.IllegalStateException: Target host must not
be null, or set in parameters. scheme=null, host=null,
path=localhost/android_connect/sqlconfig/create_user.php
E/AndroidRuntime(1132): at
org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.jav
a:591)
E/AndroidRuntime(1132): at
org.apache.http.impl.client.DefaultRequestDirector.execute
(DefaultRequestDirector.java:293)
E/AndroidRuntime(1132): at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
E/AndroidRuntime(1132): at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
E/AndroidRuntime(1132): at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
E/AndroidRuntime(1132): at
com.example.propertypanther.JSONParser.makeHttpRequest(JSONParser.java:51)
E/AndroidRuntime(1132): at
com.example.propertypanther.AddUserActivity$CreateNewUser.doInBackground
(AddUserActivity.java:116)
E/AndroidRuntime(1132): at
com.example.propertypanther.AddUserActivity$CreateNewUser.doInBackground
(AddUserActivity.java:1)
E/AndroidRuntime(1132): at android.os.AsyncTask$2.call(AsyncTask.java:288)
E/AndroidRuntime(1132): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
E/AndroidRuntime(1132): ... 4 more
I/Choreographer(1132): Skipped 82 frames! The application may be doing too much work on
its main thread.
I/Choreographer(1132): Skipped 58 frames! The application may be doing too much work on
its main thread.
E/WindowManager(1132): android.view.WindowLeaked: Activity
com.example.propertypanther.AddUserActivity has leaked window
com.android.internal.policy.impl.PhoneWindow$DecorView{b1e3d240 V.E..... R.....ID 0,0-
729,192} that was originally added here
E/WindowManager(1132): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:348)
E/WindowManager(1132): at
android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
E/WindowManager(1132): at
android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
E/WindowManager(1132): at android.app.Dialog.show(Dialog.java:286)
E/WindowManager(1132): at
com.example.propertypanther.AddUserActivity$CreateNewUser.onPreExecute
(AddUserActivity.java:97)
E/WindowManager(1132): at
android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
E/WindowManager(1132): at android.os.AsyncTask.execute(AsyncTask.java:535)
E/WindowManager(1132): at
com.example.propertypanther.AddUserActivity$2.run(AddUserActivity.java:78)
E/WindowManager(1132): at android.os.Handler.handleCallback(Handler.java:733)
E/WindowManager(1132): at android.os.Handler.dispatchMessage(Handler.java:95)
E/WindowManager(1132): at android.os.Looper.loop(Looper.java:136)
E/WindowManager(1132): at android.app.ActivityThread.main(ActivityThread.java:5017)
E/WindowManager(1132): at java.lang.reflect.Method.invokeNative(Native Method)
E/WindowManager(1132): at java.lang.reflect.Method.invoke(Method.java:515)
E/WindowManager(1132): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
E/WindowManager(1132): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
E/WindowManager(1132): at dalvik.system.NativeStart.main(Native Method)
The script files themselves work as far as i am aware - besides, the program never executes the script from what i can tell.
If anyone could help me out, i would really appreciate it! I understand you are all busy people, so thank you so much for taking some time out of your day if you do post ideas :)
The clue is in the exception thrown:
Caused by: java.lang.IllegalStateException: Target host must not be
null, or set in parameters. scheme=null, host=null,
path=localhost/android_connect/sqlconfig/create_user.php
I'm going to guess that there is an encoding problem, have you correctly included the "http://" at the beginning of your URL and have you printed the url you are requesting to LogCat to make sure it looks correct?

Categories