Android, threadid=1: thread exiting with uncaught exception (group=0xb0d4bb20) - android

So my application makes http request calls to an API and receives a response back. My application turns the response into JSON and I parse through it. The issue I'm having is this?
W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xb0d4bb20)
E/AndroidRuntime: FATAL EXCEPTION: main
E/AndroidRuntime: Process: com.example.stevefoo.wrestt, PID: 30650
E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.stevefoo.wrestt/com.example.stevefoo.wrestt.Admin.AdminUserBrowse}: java.lang.NullPointerException
E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
E/AndroidRuntime: at android.app.ActivityThread.access$800(ActivityThread.java:135)
E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime: at android.os.Looper.loop(Looper.java:136)
E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5017)
E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime: Caused by: java.lang.NullPointerException
E/AndroidRuntime: at com.example.stevefoo.wrestt.Admin.AdminUserBrowse.retrieveUsers(AdminUserBrowse.java:70)
E/AndroidRuntime: at com.example.stevefoo.wrestt.Admin.AdminUserBrowse.onCreate(AdminUserBrowse.java:42)
E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:5231)
E/AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
E/AndroidRuntime: at android.app.ActivityThread.access$800(ActivityThread.java:135) 
E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102) 
E/AndroidRuntime: at android.os.Looper.loop(Looper.java:136) 
E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5017) 
E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method) 
E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:515) 
E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method) 
I realized I'm getting a null pointer exception on the retrieveUser method. When I carefully inspected the JSON response being used by retrieveUser I realized that I'm not getting a full JSON response back. It's only giving me a partial JSON response back. If I use http pie to retrieve the JSON response from the server I get the full thing so the problem isn't the server. It's the call I'm making. The method being used to make the call is inside the CustomThread Callable, executeHttpGet:
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object
* #return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
public static String CustomThreadHttpGet(final String url, final String token){
String result = null;
ExecutorService service = Executors.newCachedThreadPool();
Future<String> future = service.submit(new Callable<String>() {
#Override
public String call() throws Exception {
String response = CustomHttpClient.executeHttpGet(url, token);
response = response.replaceAll("\\s+", "");
return response;
}
});
try {
// get() waits for the task to finish and then gets the result
result = future.get();
} catch (InterruptedException e) {
// thrown if task was interrupted before completion
e.printStackTrace();
} catch (ExecutionException e) {
// thrown if the task threw an execption while executing
e.printStackTrace();
}
return result;
}
public static String executeHttpGet(String url, String token) throws Exception {
BufferedReader in = null;
try {
//creates http client to make request
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
request.setHeader("Accept", "application/json; charset=UTF-8");
request.addHeader("Authorization", "Bearer " + token);
HttpResponse response = client.execute(request);
//Stream reader deciphers the response
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
System.out.println(result);
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
For some reason this call is making the thread exit early before it can get the full JSON response, or at least I think that's what happening. The method actually works fine as long the JSON response is under 4000 characters, however if it goes over that it begins to only give me partial JSON responses back. Any insight for my dilemma would be appreciated.

Related

getting error in doing operations of http url operation in android

I am trying to send sms from my android app but getting the error.
i am using AsyncTask class and the code which put in doInBackground method it gives an error.
PLEASE HELP ME I HAVE PURCHASED THE SMS SERVICE BUT I AM NOT BEING ABLE TO MAKE CALL OF SERVICE.
SendFeedback class
private class SendfeedbackJob extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String[] params) {
// do above Server call here
try {
// Construct data
String apiKey = "apikey=" + "--MY API KEY--";
String message = "&message=" + "New order by "+ userName+"
and dilivery "+userAddress;
String sender = "&sender=" + "TXTLCL";
String numbers = "&numbers=" + "91 CONTACT NO.";
// Send data
HttpURLConnection conn = (HttpURLConnection) new
URL("https://api.textlocal.in/send/?").openConnection();
String data = apiKey + numbers + message + sender;
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Length",
Integer.toString(data.length()));
conn.getOutputStream().write(data.getBytes("UTF-8"));
final BufferedReader rd = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
final StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
stringBuffer.append(line);
}
rd.close();
//return stringBuffer.toString();
Toast.makeText(getContext(),stringBuffer.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
System.out.println("Error SMS "+e);
//return "Error "+e;
Toast.makeText(getContext(),"Error
"+e.toString(),Toast.LENGTH_LONG).show();
}
return "some message";
}
#Override
protected void onPostExecute(String message) {
//process message
}
}
Oncreate method
SendfeedbackJob job = new SendfeedbackJob();
job.execute();
I am getting this Error
'E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.agssoftech.shlokenterprise, PID: 12204
java.lang.RuntimeException: An error occurred while executing
doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:325)
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: Cant create handler
inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:208)
at android.os.Handler.<init>(Handler.java:122)
at android.widget.Toast$TN$2.<init>(Toast.java:341)
at android.widget.Toast$TN.<init>(Toast.java:341)
at android.widget.Toast.<init>(Toast.java:108)
at android.widget.Toast.makeText(Toast.java:261)
at com.agssoftech.shlokenterprise.Fragments
.PlaceOrderFragment$SendfeedbackJob.doInBackground
(PlaceOrderFragment.java:224)
at
com.agssoftech.shlokenterprise.Fragments
.PlaceOrderFragment$SendfeedbackJob.doInBackground
(PlaceOrderFragment.java:190)
at android.os.AsyncTask$2.call(AsyncTask.java:305)
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) 
You can't call Toast.makeText() from the doInBackground method as it is not running on the UI thread.
Move your calls to Toast.makeText() to the onPostExecute method, which runs on the UI thread.

Sending POST request to website and recieving results

I need to send a HTTP post request and receive the output but when I run the app the app crashes.
Below is the code I use.
public String getRequest(String url) {
StringBuilder responseOutput = new StringBuilder();
try {
URL uri = new URL(url);
HttpURLConnection connection = (HttpURLConnection)uri.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
connection.setDoOutput(true);
DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
dStream.flush();
dStream.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
while((line = br.readLine()) != null ) {
responseOutput.append(line);
}
br.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return responseOutput.toString();
}
This is the crash log.
05-18 16:34:50.915 18272-18272/com.prisonvoicemail.appupdater E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.prisonvoicemail.appupdater, PID: 18272
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.prisonvoicemail.appupdater/com.prisonvoicemail.appupdater.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1287)
at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:437)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:245)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java)
at com.prisonvoicemail.appupdater.HTTPRequest.getRequest(HTTPRequest.java:72)
at com.prisonvoicemail.appupdater.MainActivity.onCreate(MainActivity.java:79)
at android.app.Activity.performCreate(Activity.java:6259)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5443) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 
Android doens't allow network calls on main thread(which controls the ui) in order to keep him free , you need to do some easy multithreading , you can take a look at Asynctask for that operation , or use an outside library such as Retrofit , Volley , Loopj etc...
You can start with Asynctask for a first lesson:
http://developer.android.com/reference/android/os/AsyncTask.html
put the code of the call in doinbackground ( another thread and not the main thread ) , after getting your result and finishing the doinbackground you'll get to OnPost method (is on the main thread , you can make ui changes here)
Hope it helps.
You are having NetworkOnMainThreadException, this is because you are calling this method from application main thread.
You should not do any network operation (blocking operation) in the main thread, this will stuck your application until the operation is finished. Besides, wrap the function call inside an AsyncTask then call AsyncTask.execute() this will fix your issue. e.g
AsyncTask task = new AsyncTask() {
#Override
protected Object doInBackground(Object[] params) {
//do your stuff here
return null;
}
};
task.execute();
Hope that helps. cheers :)

Im trying to fetch data from an SQL database but i dont really know whats wrong

Im trying to fetch some data from a database but im getting, 'fatal error.. AsyncTask # 2'. Im really new to java and android studio, therefore i dont know if what ive done is the right way to go about it. but in short this is what ive tried to read the JsonObject from the database.:
Set up inputput stream (con.getInputStream)
convert that into a string
and send it to the JSONobject to be read and then returned.
Im using API 23 and i havent really found that much/understood much from whats available online. Help would be MUCH appreciated.
public class fetchUserDataAsyncTask extends AsyncTask<Void, Void, User> {
User user;
GetUserCallback userCallback;
fetchUserDataAsyncTask(User user, GetUserCallback userCallback) {
this.user = user;
this.userCallback = userCallback;
}
#Override
protected User doInBackground(Void... params) {
//Use HashMap, it works similar to NameValuePair
Map<String, String> dataToSend = new HashMap<>();
dataToSend.put("username", user.username);
dataToSend.put("password", user.password);
//Encoded String - we will have to encode string by our custom method (Very easy)
String encodedStr = getEncodedData(dataToSend);
User returneduser = null; //for the JSONobject
try {
//Converting address String to URL
URL url = new URL(Server_Address + "FetchUserData.php");
//Opening the connection (Not setting or using CONNECTION_TIMEOUT)
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//Post Method
con.setRequestMethod("POST");
//To enable inputting values using POST method
//(Basically, after this we can write the dataToSend to the body of POST method
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
//Writing dataToSend to outputstreamwriter
writer.write(encodedStr);
//Sending the data to the server - This much is enough to send data to server
//But to read the response of the server, you will have to implement the procedure below
writer.flush();
//Attempt to read data and shit but doesnt work
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) { //Read till there is something available
sb.append(line + "\n"); //Reading and saving line by line - not all at once
}
line = sb.toString(); //Saving complete data received in string, you can do it differently
try {
JSONObject jObject = new JSONObject(line);//result in the ().
if (jObject.length() == 0) {
returneduser = null;
}
else {
try {
String name = jObject.getString("name");
String teamname = jObject.getString("teamname");
String username = jObject.getString("username");
String password = jObject.getString("password");
String emailad = jObject.getString("emailad");
returneduser = new User(name, teamname, username, emailad, password);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e){
e.printStackTrace();
}
}catch (IOException e){
e.printStackTrace();
}
return returneduser;
}
#Override
protected void onPostExecute(User returneduser) {
progressDialog.dismiss();
userCallback.done(returneduser);
super.onPostExecute(returneduser);
}
//get encoded data (edit)
(private String getEncodedData(Map<String, String> data) {
StringBuilder sb = new StringBuilder();
for (String key : data.keySet()) {
String value = null;
try {
value = URLEncoder.encode(data.get(key), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (sb.length() > 0)
sb.append("&");
sb.append(key + "=" + value);
}
return sb.toString();
})
}
Error Stack:
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: Process: pk.com.gameon.myapplication, PID: 8414
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: java.lang.RuntimeException: An error occurred while executing doInBackground()
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: at android.os.AsyncTask$3.done(AsyncTask.java:309)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:242)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: at java.lang.Thread.run(Thread.java:818)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: at libcore.net.UriCodec.encode(UriCodec.java:132)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: at java.net.URLEncoder.encode(URLEncoder.java:57)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: at pk.com.gameon.myapplication.ServerRequest.getEncodedData(ServerRequest.java:134)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: at pk.com.gameon.myapplication.ServerRequest.access$000(ServerRequest.java:29)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: at pk.com.gameon.myapplication.ServerRequest$fetchUserDataAsyncTask.doInBackground(ServerRequest.java:168)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: at pk.com.gameon.myapplication.ServerRequest$fetchUserDataAsyncTask.doInBackground(ServerRequest.java:148)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: at android.os.AsyncTask$2.call(AsyncTask.java:295)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: at java.lang.Thread.run(Thread.java:818) 
12-02 23:36:24.617 8414-8441/pk.com.gameon.myapplication E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab753b90
12-02 23:36:25.453 8414-8441/pk.com.gameon.myapplication E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab755100
Here is your culprit:
java.lang.NullPointerException: Attempt to invoke virtual method 'int
java.lang.String.length()' on a null object reference
You are calling this in your AsyncTask:
if (jObject.length() == 0) {
returneduser = null;
}
Instead, change it to:
if(jObject == null || jObject.length() == 0) {
returneduser = null;
}
That way it is null-safe when it does the check. Also, you could verify this by setting break points in your code and running the debugger via Android Studio or Intellij or Eclipse depending on what you are using. This is your best bet and I suggest trying this for all bugs you cannot easily identify. In most cases, you will see the mistake quickly, and can view the values of all variables in the scope of the break points to verify that they are either as expected or not.
Another less efficient way is to drop Log.i(String, String) lines everywhere to keep track of what is happening and where the state of the application has made it to that then make it into your log cat output as well.

java.lang.NullPointerException at HttpGet httpGet = new HttpGet(url);

public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
This is the class i use for getting String from REST request
12-26 10:51:35.610 1750-1778/hackerspace.invento.ebooks E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
Process: hackerspace.invento.ebooks, PID: 1750
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at java.net.URI.parseURI(URI.java:353)
at java.net.URI.<init>(URI.java:204)
at java.net.URI.create(URI.java:725)
at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:75)
at hackerspace.invento.ebooks.ServiceHandler.makeServiceCall(ServiceHandler.java:63)
at hackerspace.invento.ebooks.ServiceHandler.makeServiceCall(ServiceHandler.java:39)
at hackerspace.invento.ebooks.Books$GetResult.doInBackground(Books.java:113)
at hackerspace.invento.ebooks.Books$GetResult.doInBackground(Books.java:94)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
and this is the Log Error i get How do i solve this?
My guess would be that you are either passing a NULL string into your method, or for some reason the string is getting set to NULL if the HttpGet() method fails to resolve the URL or something else goes wrong. Try appending this at the end of your try / catch statement:
catch (Exception e)
{
Log.e("MyApp", "exception: " + e.getMessage());
Log.e("MyApp", "exception: " + e.toString());
}
Normally, a statement such as this is poor practice to use in your software, as it will essentially squash any exception you get without allowing you to handle the various exception cases. However, for debugging purposes, adding this statement at the end of you try/catch statement will allow you to see if there is perhaps an exception that you are missing that is causing the HttpGet() method to fail which, in turn, causes your NULL error. If you do detect another exception, you can handle it appropriately so that your method no longer returns a NULL string.
Your url is NULL
URISyntaxException
Throws: java.lang.NullPointerException If either the input or reason strings are null

Android API error / httpget NetworkOnMainThreadException [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 8 years ago.
This is my error message:
08-17 07:58:14.286 32620-32620/xxx.dk.xxx E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: xxx.dk.xxx, PID: 32620
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1239)
at java.net.InetAddress.lookupHostByName(InetAddress.java:388)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:239)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
at xxx.dk.xxx.DAL.JsonConnection.checkSecret(JsonConnection.java:42)
at xxx.dk.xxx.BLL.CheckCarrierData.checkSecret(CheckCarrierData.java:14)
at xxx.dk.xxx.GUI.Login.onClick(Login.java:49)
at android.view.View.performClick(View.java:4480)
at android.view.View$PerformClick.run(View.java:18686)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5872)
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:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
at dalvik.system.NativeStart.main(Native Method)
Im trying to use a httpGet method, which is working on API10, but it fails when im using it on an unit with 4.4.2 -> i need the support from API10 and up.
The code:
public class JsonConnection
{
private String secretJsonStr = null;
private String nameOfCarrier = "";
public String checkSecret(String secret)
{
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
final String QueryParam = "secret";
try
{
final String httpUrl = "***SOMEURL***?";
Uri builtUri = Uri.parse(httpUrl).buildUpon().
appendQueryParameter(QueryParam, secret.toString()).build();
URL url = new URL(builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null)
{
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null)
{
buffer.append(line + "\n");
}
if (buffer.length() == 0)
{
// Stream was empty. No point in parsing.
return null;
}
secretJsonStr = buffer.toString();
} catch (IOException e)
{
Log.e("Login", "Error", e);
return null;
} finally
{
if (urlConnection != null)
{
urlConnection.disconnect();
}
if (reader != null)
{
try
{
reader.close();
} catch (final IOException e)
{
Log.e("Login", "Error closing stream", e);
}
}
}
try
{
JSONObject secretJson = new JSONObject(secretJsonStr);
nameOfCarrier = getCarrierInfoFromJson(secretJson);
}
catch (JSONException e)
{
e.printStackTrace();
}
return nameOfCarrier;
}
private String getCarrierInfoFromJson(JSONObject secretJson)
throws JSONException
{
final String CARRIER_NAME = "Name";
String nameOfCarrier2 = secretJson.getString(CARRIER_NAME);
return nameOfCarrier2;
}
}
Due to some protection, i cannot show you the URL, but everything is working like a charm when running in API 10 2.3.6 units..
I though there where complete backwards compatibility on all android devices.
Hope you have the knowledge to help me on, I for sure cannot see how. :-(
Kindest regards
Rasmus
The problem is that the http requests are executed on the main thread (NetworkOnMainThreadException), so you need to move the calls into a Thread. More info here.
update: actually, possible duplicate of this.
As error say you can't execute an HTTP connection on the MainThread that would froze the screen. which is not appropriate.
You can get that permission as the following:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
But, this is not a good practice. you must run the http connection on a background thread and display a loading msg to the user.
new Thread(new Runnable() {
#Override
public void run() {
// code goes here ...
}
}).start();
As other answers are suggesting, you are getting this error because you are running network operation on main thread. I would suggest to use AsyncTask.
This link shows you structure of AsyncTask.
To call the AsyncTask, use
//getData() is name of class
new getData().execute();
More reference on Android Developer site.

Categories

Resources