java.io.IOException: Post failed with error code 403 [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i tried to post values from android mobile to my web server. i am getting 403 error with java.io.exception.
this is my logcat messages
[CDS]connect[local.test.com/192.99.166.230:80] tm:90
04-30 12:57:07.388 10416-10434/gcm.androidexample.com.ravi D/Posix﹕ [Posix_connect Debug]Process gcm.androidexample.com.ravi :80
04-30 12:57:07.413 10416-10416/gcm.androidexample.com.ravi V/InputMethodManager﹕ onWindowFocus: null softInputMode=288 first=true flags=#1810100
04-30 12:57:07.413 10416-10416/gcm.androidexample.com.ravi D/InputMethodManager﹕ deactivate the inputconnection in ControlledInputConnectionWrapper.
04-30 12:57:07.413 10416-10416/gcm.androidexample.com.ravi V/InputMethodManager﹕ START INPUT: com.android.internal.policy.impl.PhoneWindow$DecorView{41cd4600 V.E..... R.....ID 0,0-480,800} ic=null tba=android.view.inputmethod.EditorInfo#41cfca48 controlFlags=#104
04-30 12:57:07.416 10416-10416/gcm.androidexample.com.ravi V/InputMethodManager﹕ Starting input: Bind result=InputBindResult{com.android.internal.view.IInputMethodSession$Stub$Proxy#41cfd2d8 com.android.inputmethod.latin/.LatinIME #186}
04-30 12:57:07.513 10416-10416/gcm.androidexample.com.ravi D/OpenGLRenderer﹕ Flushing caches (mode 0)
04-30 12:57:07.696 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [socket][/192.168.1.70:36222] connected
04-30 12:57:07.696 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]rx timeout:0
04-30 12:57:07.820 10416-10416/gcm.androidexample.com.ravi D/OpenGLRenderer﹕ Flushing caches (mode 0)
04-30 12:57:08.012 10416-10434/gcm.androidexample.com.ravi D/AndroidRuntime﹕ zoneinfo:Asia/Calcutta
04-30 12:57:08.014 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]close[36222]
04-30 12:57:08.015 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ close [socket][/0.0.0.0:36222]
04-30 12:57:08.015 10416-10434/gcm.androidexample.com.ravi E/GCM Android Example﹕ Failed to register on attempt 1:java.io.IOException: Post failed with error code 403
04-30 12:57:08.015 10416-10434/gcm.androidexample.com.ravi D/GCM Android Example﹕ Sleeping for 2401 ms before retry
04-30 12:57:10.416 10416-10434/gcm.androidexample.com.ravi D/GCM Android Example﹕ Attempt #2 to register
04-30 12:57:10.418 10416-10434/gcm.androidexample.com.ravi V/GCM Android Example﹕ Posting 'email=fvgghhgv#hhngfg.hjh&regId=APA91bFKaVLGMwjZ-4DywjSCncNlokYu96l_4MyIFCt1cqCYEnDlCr-WMns4IuuEVAyCOl8XGKgOKptfbUxHgiDS_qy65C48uRPsl3NCZRuOhtswsEuJZLSq2x5w0i-znjhdqYFhDwSUJHrr8ye-2vgMP6duXCW9pw&name=gfgh' to
04-30 12:57:10.418 10416-10434/gcm.androidexample.com.ravi E/URL﹕ >
04-30 12:57:10.425 10416-10434/gcm.androidexample.com.ravi D/libc-netbsd﹕ getaddrinfo: local.test.com get result from proxy >>
04-30 12:57:10.426 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ propertyValue:true
04-30 12:57:10.426 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [socket][1] connection local.test.com/192.99.166.230:80;LocalPort=34236(0)
04-30 12:57:10.427 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ /192.99.166.230:80] tm:90
04-30 12:57:10.427 10416-10434/gcm.androidexample.com.ravi D/Posix﹕ [Posix_connect Debug]Process gcm.androidexample.com.ravi :80
04-30 12:57:10.460 10416-10436/gcm.androidexample.com.ravi I/SurfaceTextureClient﹕ [STC::queueBuffer] (this:0x52c45438) fps:0.33, dur:3015.55, max:3015.55, min:3015.55
04-30 12:57:10.733 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [socket][/192.168.1.70:34236] connected
04-30 12:57:10.733 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]rx timeout:0
04-30 12:57:11.045 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]close[34236]
04-30 12:57:11.046 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ close [socket][/0.0.0.0:34236]
04-30 12:57:11.046 10416-10434/gcm.androidexample.com.ravi E/GCM Android Example﹕ Failed to register on attempt 2:java.io.IOException: Post failed with error code 403
04-30 12:57:11.047 10416-10434/gcm.androidexample.com.ravi D/GCM Android xample﹕ Sleeping for 4802 ms before retry
04-30 12:57:15.849 10416-10434/gcm.androidexample.com.ravi D/GCM Android Example﹕ Attempt #3 to register
04-30 12:57:15.873 10416-10434/gcm.androidexample.com.ravi V/GCM Android Example﹕ Posting 'email=fvgghhgv#hhngfg.hjh&regId=APA91bFKaVLGMwjZ-4DywjSCncNlokYu96l_4MyIFCt1cqCYEnDlCr-WMns4IuuEVAyCOl8XGKgOKptfbUxHgiDS_qy65C48uRPsl3NCZRuOhtswsEuJZLSq2x5w0i-znjhdqYFhDwSUJHrr8ye-2vgMP6duXCW9pw&name=gfgh' to
04-30 12:57:15.885 10416-10434/gcm.androidexample.com.ravi E/URL﹕ >
04-30 12:57:15.889 10416-10436/gcm.androidexample.com.ravi I/SurfaceTextureClient﹕ [STC::queueBuffer] (this:0x52c45438) fps:0.18, dur:5428.43, max:5428.43, min:5428.43
04-30 12:57:15.889 10416-10436/gcm.androidexample.com.ravi I/SurfaceTextureClient﹕ [STC::queueBuffer] this:0x52c45438, api:1, last queue time elapsed:5428.43
04-30 12:57:15.891 10416-10434/gcm.androidexample.com.ravi D/libc-netbsd﹕ getaddrinfo: local.test.com get result from proxy >>
04-30 12:57:15.891 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ propertyValue:true
04-30 12:57:15.892 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [socket][2] connection local.test.com/192.99.166.230:80;LocalPort=44926(0)
04-30 12:57:15.892 10416-10434/gcm.androidexample.com.ravi I/System.out﹕
04-30 12:57:15.893 10416-10434/gcm.androidexample.com.ravi D/Posix﹕ [Posix_connect Debug]Process gcm.androidexample.com.ravi :80
04-30 12:57:16.202 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [socket][/192.168.1.70:44926] connected
04-30 12:57:16.202 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]rx timeout:0
04-30 12:57:16.503 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]close[44926]
04-30 12:57:16.504 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ close [socket][/0.0.0.0:44926]
04-30 12:57:16.504 10416-10434/gcm.androidexample.com.ravi E/GCM Android Example﹕ Failed to register on attempt 3:java.io.IOException: Post failed with error code 403
04-30 12:57:16.505 10416-10434/gcm.androidexample.com.ravi D/GCM Android Example﹕ Sleeping for 9604 ms before retry
04-30 12:57:26.109 10416-10434/gcm.androidexample.com.ravi D/GCM Android Example﹕ Attempt #4 to register
04-30 12:57:26.140 10416-10434/gcm.androidexample.com.ravi V/GCM Android Example﹕ Posting 'email=fvgghhgv#hhngfg.hjh&regId=APA91bFKaVLGMwjZ-4DywjSCncNlokYu96l_4MyIFCt1cqCYEnDlCr-WMns4IuuEVAyCOl8XGKgOKptfbUxHgiDS_qy65C48uRPsl3NCZRuOhtswsEuJZLSq2x5w0i-znjhdqYFhDwSUJHrr8ye-2vgMP6duXCW9pw&name=gfgh' to
04-30 12:57:26.145 10416-10434/gcm.androidexample.com.ravi E/URL﹕ >
I/SurfaceTextureClient﹕ [STC::queueBuffer] (this:0x52c45438) fps:0.10, dur:10271.53, max:10271.53, min:10271.53
04-30 12:57:26.160 10416-10436/gcm.androidexample.com.ravi I/SurfaceTextureClient﹕ [STC::queueBuffer] this:0x52c45438, api:1, last queue time elapsed:10271.53
04-30 12:57:26.162 10416-10434/gcm.androidexample.com.ravi D/libc-netbsd﹕ getaddrinfo: local.test.com get result from proxy >>
04-30 12:57:26.165 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ propertyValue:true
04-30 12:57:26.166 10416-10434/gcm.androidexample.com.ravi I/System.out﹕
04-30 12:57:26.166 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]connect[local.test.com/192.99.166.230:80] tm:90
04-30 12:57:26.174 10416-10434/gcm.androidexample.com.ravi D/Posix﹕ [Posix_connect Debug]Process gcm.androidexample.com.ravi :80
04-30 12:57:26.492 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [socket][/192.168.1.70:45892] connected
04-30 12:57:26.492 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]rx timeout:0
04-30 12:57:26.806 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]close[45892]
04-30 12:57:26.806 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ close [socket][/0.0.0.0:45892]
04-30 12:57:26.807 10416-10434/gcm.androidexample.com.ravi E/GCM Android Example﹕ Failed to register on attempt 4:java.io.IOException: Post failed with error code 403
04-30 12:57:26.807 10416-10434/gcm.androidexample.com.ravi D/GCM Android Example﹕ Sleeping for 19208 ms before retry
04-30 12:57:46.015 10416-10434/gcm.androidexample.com.ravi D/GCM Android Example﹕ Attempt #5 to register
04-30 12:57:46.044 10416-10434/gcm.androidexample.com.ravi V/GCM Android Example﹕ Posting 'email=fvgghhgv#hhngfg.hjh&regId=APA91bFKaVLGMwjZ-4DywjSCncNlokYu96l_4MyIFCt1cqCYEnDlCr-WMns4IuuEVAyCOl8XGKgOKptfbUxHgiDS_qy65C48uRPsl3NCZRuOhtswsEuJZLSq2x5w0i-znjhdqYFhDwSUJHrr8ye-2vgMP6duXCW9pw&name=gfgh' to
04-30 12:57:46.051 10416-10436/gcm.androidexample.com.ravi I/SurfaceTextureClient﹕ [STC::queueBuffer] (this:0x52c45438) fps:0.05, dur:19890.52, max:19890.52, min:19890.52
04-30 12:57:46.051 10416-10436/gcm.androidexample.com.ravi I/SurfaceTextureClient﹕ [STC::queueBuffer] this:0x52c45438, api:1, last queue time elapsed:19890.52
04-30 12:57:46.060 10416-10434/gcm.androidexample.com.ravi E/URL﹕ > http://local.test.com/gcmfile/register
04-30 12:57:46.065 10416-10434/gcm.androidexample.com.ravi D/libc-netbsd﹕
04-30 12:57:46.066 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ propertyValue:true
04-30 12:57:46.066 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [socket][4] connection local.test.com/192.99.166.230:80;LocalPort=38220(0)
04-30 12:57:46.066 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]connect[local.test.com/192.99.166.230:80] tm:90
04-30 12:57:46.067 10416-10434/gcm.androidexample.com.ravi D/Posix﹕ [Posix_connect Debug]Process gcm.androidexample.com.ravi :80
04-30 12:57:46.390 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [socket][/192.168.1.70:38220] connected
04-30 12:57:46.393 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]rx timeout:0
04-30 12:57:46.701 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ [CDS]close[38220]
04-30 12:57:46.702 10416-10434/gcm.androidexample.com.ravi I/System.out﹕ close [socket][/0.0.0.0:38220]
04-30 12:57:46.702 10416-10434/gcm.androidexample.com.ravi E/GCM Android Example﹕ Failed to register on attempt 5:java.io.IOException: Post failed with error code 403
this is my code on register
package gcm.androidexample.com.ravi;
/**
* Created by Thidiff on 4/24/2015.
*/
import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.PowerManager;
import android.util.Log;
import com.google.android.gcm.GCMRegistrar;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import gcm.androidexample.com.gcm.R;
public class Controller extends Application{
private final int MAX_ATTEMPTS = 5;
private final int BACKOFF_MILLI_SECONDS = 2000;
private final Random random = new Random();
// Register this account with the server.
void register(final Context context, String name, String email, final String regId) {
Log.i(Config.TAG, "registering device (regId = " + regId + ")");
String serverUrl = Config.YOUR_SERVER_URL;
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
params.put("name", name);
params.put("email", email);
long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
String res = "";
// Once GCM returns a registration id, we need to register on our server
// As the server might be down, we will retry it a couple
// times.
for (int i = 1; i <= MAX_ATTEMPTS; i++) {
Log.d(Config.TAG, "Attempt #" + i + " to register");
try {
//Send Broadcast to Show message on screen
displayMessageOnScreen(context, context.getString(
R.string.server_registering, i, MAX_ATTEMPTS));
// Post registration values to web server
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, true);
//Send Broadcast to Show message on screen
String message = context.getString(R.string.server_registered);
displayMessageOnScreen(context, message);
return;
} catch (IOException e) {
// Here we are simplifying and retrying on any error; in a real
// application, it should retry only on unrecoverable errors
// (like HTTP error code 503).
Log.e(Config.TAG, "Failed to register on attempt " + i + ":" + e);
if (i == MAX_ATTEMPTS) {
break;
}
try {
Log.d(Config.TAG, "Sleeping for " + backoff + " ms before retry");
Thread.sleep(backoff);
} catch (InterruptedException e1) {
// Activity finished before we complete - exit.
Log.d(Config.TAG, "Thread interrupted: abort remaining retries!");
Thread.currentThread().interrupt();
return;
}
// increase backoff exponentially
backoff *= 2;
}
}
String message = context.getString(R.string.server_register_error,
MAX_ATTEMPTS);
//Send Broadcast to Show message on screen
displayMessageOnScreen(context, message);
}
// Unregister this account/device pair within the server.
void unregister(final Context context, final String regId) {
Log.i(Config.TAG, "unregistering device (regId = " + regId + ")");
String serverUrl = Config.YOUR_SERVER_URL + "/unregister";
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
try {
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, false);
String message = context.getString(R.string.server_unregistered);
displayMessageOnScreen(context, message);
} catch (IOException e) {
// At this point the device is unregistered from GCM, but still
// registered in the our server.
// We could try to unregister again, but it is not necessary:
// if the server tries to send a message to the device, it will get
// a "NotRegistered" error message and should unregister the device.
String message = context.getString(R.string.server_unregister_error,
e.getMessage());
displayMessageOnScreen(context, message);
}
}
// Issue a POST request to the server.
private static void post(String endpoint, Map<String, String> params)
throws IOException {
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
Log.v(Config.TAG, "Posting '" + body + "' to " + url);
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
Log.e("URL", "> " + url);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
// If response is not success
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
// Checking for all possible internet providers
public boolean isConnectingToInternet(){
ConnectivityManager connectivity =
(ConnectivityManager) getSystemService(
Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
// Notifies UI to display a message.
void displayMessageOnScreen(Context context, String message) {
Intent intent = new Intent(Config.DISPLAY_MESSAGE_ACTION);
intent.putExtra(Config.EXTRA_MESSAGE, message);
// Send Broadcast to Broadcast receiver with message
context.sendBroadcast(intent);
}
//Function to display simple Alert Dialog
public void showAlertDialog(Context context, String title, String message,
Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Set Dialog Title
alertDialog.setTitle(title);
// Set Dialog Message
alertDialog.setMessage(message);
if(status != null)
// Set alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Set OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Show Alert Message
alertDialog.show();
}
private PowerManager.WakeLock wakeLock;
public void acquireWakeLock(Context context) {
if (wakeLock != null) wakeLock.release();
PowerManager pm = (PowerManager)
context.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.ON_AFTER_RELEASE, "WakeLock");
wakeLock.acquire();
}
public void releaseWakeLock() {
if (wakeLock != null) wakeLock.release(); wakeLock = null;
}
}

Error 403 in HTML is Forbidden, this means your server is not setup to accept xmlhttp or forum posts or you are using your service incorrectly.

Related

Why does second http request is always null?

When I do http request in the PoolData(), request returns with data, and in AccoutData is always null.
In debugger, if I wait 1-2 sec after PoolData(), next request - returns not null. Method oder doesn't metter. Why is that, and how can I wait for 2nd request?
public void onClick(View v) {
new PoolData().execute();
}
private class PoolData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dataPool.clear();
}
#Override
protected Void doInBackground(Void... arg0) {
PoolData();
AccoutData();
return null;
}
private void PoolData(){
HttpHandler sh = new HttpHandler();
String statsBrowser = "http://api.electroneum.space/v1/stats/nonBrowser";
String browserStr = sh.makeServiceCall(statsBrowser);
//parsing...
}
private void AccoutData(){
HttpHandler sh = new HttpHandler();
String statsAddress = "http://api.electroneum.space/v1/stats/address/" + settings.getString(lp, "n/a");
String addressStr = sh.makeServiceCall(statsAddress);
//parsing...
}
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
Log.e(TAG, "Responce: " + response);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.toString());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.toString());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.toString());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
12-14 14:27:18.941 6624-6651/dev.flair.the.electroneumspacepool
I/OpenGLRenderer: Initialized EGL, version 1.4
12-14 14:27:18.956 6624-6651/dev.flair.the.electroneumspacepool I/OpenGLRenderer: Get enable program binary service property (1)
12-14 14:27:18.956 6624-6651/dev.flair.the.electroneumspacepool I/OpenGLRenderer: Initializing program atlas...
12-14 14:27:18.958 6624-6651/dev.flair.the.electroneumspacepool I/OpenGLRenderer: Program binary detail: Binary length is 169916, program map length is 152.
12-14 14:27:18.958 6624-6651/dev.flair.the.electroneumspacepool I/OpenGLRenderer: Succeeded to mmap program binaries. File descriptor is 54, and path is /dev/ashmem .
12-14 14:27:18.958 6624-6651/dev.flair.the.electroneumspacepool I/OpenGLRenderer: No need to use file discriptor anymore, close fd(54).
12-14 14:27:18.979 6624-6624/dev.flair.the.electroneumspacepool W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
12-14 14:27:19.035 6624-6651/dev.flair.the.electroneumspacepool W/MALI: glDrawArrays:714: [MALI] glDrawArrays takes more than 5ms here. Total elapse time(us): 10394
12-14 14:27:23.448 6624-6672/dev.flair.the.electroneumspacepool I/System.out: url:http://api.electroneum.space/v1/stats/address/hVDo4adTwWsPK1
12-14 14:27:23.452 6624-6672/dev.flair.the.electroneumspacepool I/System.out: open:http://api.electroneum.space/v1/stats/address/hVDo4adTwWsPK1
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: [getaddrinfo]: mtk hostname=api.electroneum.space; servname=(null); cache_mode=(null), netid=0; mark=0
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo( app_uid:10085
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo() uid prop:
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo() getuid():10085
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: [getaddrinfo]: mtk ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: [getaddrinfo]: mtk hostname=api.electroneum.space; servname=(null); cache_mode=(null), netid=0; mark=0
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo( app_uid:10085
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo() uid prop:
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo() getuid():10085
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: [getaddrinfo]: mtk ai_addrlen=0; ai_canonname=(null); ai_flags=1024; ai_family=0
12-14 14:27:23.457 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo: api.electroneum.space get result from proxy >>
12-14 14:27:23.457 6624-6672/dev.flair.the.electroneumspacepool I/System.out: propertyValue:true
12-14 14:27:23.459 6624-6672/dev.flair.the.electroneumspacepool I/System.out: [CDS]connect[api.electroneum.space/104.27.156.123:80] tm:90
12-14 14:27:23.497 6624-6672/dev.flair.the.electroneumspacepool I/System.out: [OkHttp] sendRequest>>
12-14 14:27:23.497 6624-6672/dev.flair.the.electroneumspacepool I/System.out: [OkHttp] sendRequest<<
12-14 14:27:23.612 6624-6672/dev.flair.the.electroneumspacepool E/HttpHandler: MalformedURLException: java.io.BufferedInputStream#3d6a54f5
12-14 14:27:23.613 6624-6672/dev.flair.the.electroneumspacepool I/NetworkManagementSocketTagger: untagSocket(56)
12-14 17:08:49.897 19931-20613/dev.flair.the.electroneumspacepool E/HttpHandler: Responce:
{"stats":{"data...."}}
12-14 17:08:49.899 19931-20613/dev.flair.the.electroneumspacepool I/System.out: url:http://api.electroneum.space/v1/stats/nonBrowser
12-14 17:08:49.900 19931-20613/dev.flair.the.electroneumspacepool I/System.out: open:http://api.electroneum.space/v1/stats/nonBrowser
12-14 17:08:49.901 19931-20613/dev.flair.the.electroneumspacepool I/System.out: [OkHttp] sendRequest>>
12-14 17:08:49.901 19931-20613/dev.flair.the.electroneumspacepool I/System.out: [OkHttp] sendRequest<<
12-14 17:08:50.008 19931-20613/dev.flair.the.electroneumspacepool E/HttpHandler: IOException: java.io.FileNotFoundException: http://api.electroneum.space/v1/stats/nonBrowser
12-14 17:08:50.008 19931-20613/dev.flair.the.electroneumspacepool E/MainActivity: Response from browser: null

Not moving to profile screen even after giving genuine credentials in login page

In database we have login details {"email":"nagu#gmail.com","pwd":"12345"}.By using REST services I got the URL, I need to validate the credentials and move to next screen. But unable to move to next screen so please help me
public class LoginScreen extends DIBaseActivty {
public static final int CONNECTION_TIMEOUT=10000;
public static final int READ_TIMEOUT=15000;
private EditText editTextUsername;
private EditText editTextPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
editTextUsername = (EditText)findViewById(R.id.emaiId);
editTextPassword = (EditText)findViewById(R.id.password);
}
public void buttonLogin (View arg0)
{
final String username = editTextUsername.getText().toString();
final String password = editTextPassword.getText().toString();
new TaskLogin().execute(username,password);
}
public class TaskLogin extends AsyncTask<String,String,String>
{
ProgressDialog pdLoading = new ProgressDialog(LoginScreen.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("\t Loading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try{
url = new URL("http://localhost:8080/RestSpring/DialysisInfo/login");
} catch (MalformedURLException e) {
e.printStackTrace();
return "exception";
}
try{
conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("username",params[0])
.appendQueryParameter("password",params[1]);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1)
{
e1.printStackTrace();
return "Exception";
}
try{
int response_code = conn.getResponseCode();
if(response_code==HttpURLConnection.HTTP_OK)
{
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line= reader.readLine())!=null)
{
result.append(line);
}
return (result.toString());
} else { return ("unsuccessful");
}
} catch (IOException e)
{
e.printStackTrace();
return "Exception";
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
pdLoading.dismiss();
if(result.equalsIgnoreCase("true"))
{
Intent intent = new Intent(LoginScreen.this,DIUserProfile.class);
startActivity(intent);
LoginScreen.this.finish();
}else if (result.equalsIgnoreCase("false"))
{
Toast.makeText(LoginScreen.this, "Invalid email or password", Toast.LENGTH_LONG).show();
} else if(result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful"))
{
Toast.makeText(LoginScreen.this, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).show();
}
}
}
}
Here is my error log
02-02 10:42:56.660 25016-27263/com.dialysis
W/System.err: java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 8080) after 10000ms: isConnected failed: ECONNREFUSED (Connection refused)
02-02 10:42:56.661 25016-27263/com.dialysis W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:238)
02-02 10:42:56.661 25016-27263/com.dialysis W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:171)
02-02 10:42:56.661 25016-27263/com.dialysis W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:122)
02-02 10:42:56.663 25016-27263/com.dialysis W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
02-02 10:42:56.663 25016-27263/com.dialysis W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456)
02-02 10:42:56.664 25016-27263/com.dialysis W/System.err: at java.net.Socket.connect(Socket.java:882)
02-02 10:42:56.664 25016-27263/com.dialysis W/System.err: at com.android.okhttp.internal.Platform.connectSocket(Platform.java:174)
02-02 10:42:56.664 25016-27263/com.dialysis W/System.err: at com.android.okhttp.Connection.connect(Connection.java:152)
02-02 10:42:56.665 25016-27263/com.dialysis W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276)
02-02 10:42:56.665 25016-27263/com.dialysis W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
02-02 10:42:56.665 25016-27263/com.dialysis W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
02-02 10:42:56.665 25016-27263/com.dialysis W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:217)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at com.dialysis.renalteam.app.ui.activities.LoginScreen$TaskLogin.doInBackground(LoginScreen.java:86)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at com.dialysis.renalteam.app.ui.activities.LoginScreen$TaskLogin.doInBackground(LoginScreen.java:49)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:292)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
02-02 10:42:56.666 25016-27263/com.dialysis W/System.err: at java.lang.Thread.run(Thread.java:818)
02-02 10:42:56.667 25016-27263/com.dialysis W/System.err: Caused by: android.system.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)
02-02 10:42:56.667 25016-27263/com.dialysis W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:223)
02-02 10:42:56.667 25016-27263/com.dialysis W/System.err: ... 20 more
02-02 10:42:56.714 25016-25071/com.dialysis W/EGL_emulation: eglSurfaceAttrib not implemented
02-02 10:42:56.714 25016-25071/com.dialysis W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xb43cbb00, error=EGL_SUCCESS
02-02 10:42:57.143 25016-25071/com.dialysis W/EGL_emulation: eglSurfaceAttrib not implemented
02-02 10:42:57.144 25016-25071/com.dialysis W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xb43cbd20, error=EGL_SUCCESS
02-02 10:52:41.787 25016-25030/com.dialysis W/art: Suspending all threads took: 5.515ms
From your logcat:
java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 8080) after 10000ms: isConnected failed: ECONNREFUSED (Connection refused)
Your Android app failed to connect to the server. Set debug breakpoints and check the following:
Url is correct
Method name is correct
Parameters key and value are correct
Server is working fine or not
Since you have not specified you are connected to a server from the device or emulator so I guess you are using your application in the emulator.
If you are referring your localhost on your system from the Android emulator then you have to use http://10.0.2.2:8080/ Because Android emulator runs in a Virtual Machine therefore here 127.0.0.1 or localhost will be emulator's own loopback address.
Replace: url = http://localhost:8080/RestSpring/DialysisInfo/login"
With : url = "http://10.0.2.2:8080/RestSpring/DialysisInfo/login"

Error occured while executing doInBackground() while running Countdowntimer

I am trying to run a countdowntimer in background to do some computation through asynctask but i am getting this error
This is my code
public class CurrentStatus extends AsyncTask<Context,Void,Context> {
float BatteryStatus;
int TimeStatus,HoursToCharge;
String USID, BatteryID, NetworkID, NetworkStatus, roamingLevel,
TimeID,ETTC,DischargeRate;
int dischargeRate;
Context newContext;
SharedPreferences sharedPreferences;
public float getBatteryLevel(Context context)
{
Intent batteryIntent = context.registerReceiver(null, new
IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
return ((float) level / (float) scale) * 100.0f;
}
public void getDischargeRate(final Context context)
{
final int currentBattery=(int)getBatteryLevel(context);
int q=0;
sharedPreferences=context.getSharedPreferences
("MyDischargePref" ,Context.MODE_PRIVATE);
final SharedPreferences.Editor editor1=sharedPreferences.edit();
new CountDownTimer(120000,600)
{
int BatteryDischargeRate;
public void onTick(long millisUntilFinished)
{
System.out.println(" seconds"+currentBattery);
}
int afterUsage;
public void onFinish()
{
afterUsage = (int)getBatteryLevel(context);
System.out.println("On Finish: "+ afterUsage);
BatteryDischargeRate=currentBattery-afterUsage;
System.out.println("Entering preference. BYE!
"+BatteryDischargeRate);
editor1.putString("DischargeRate",Integer.toString(BatteryDischargeRate));
}
}.start();
}
public String getNetworkInterface(Context context) {
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled())
return "On";
else
return "Off";
}
public String getRoaming(Context context) {
boolean x = false;
TelephonyManager telephoneManager;
telephoneManager = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
x = telephoneManager.isNetworkRoaming();
if (x)
return "On";
else
return "Off";
}
public String getDataConnectionType(Context context) {
TelephonyManager telephoneManager;
telephoneManager = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
int a = telephoneManager.getNetworkType();
switch (a) {
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_IDEN:
case TelephonyManager.NETWORK_TYPE_EDGE:
String nw = "00";
return "2G";
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B:
case TelephonyManager.NETWORK_TYPE_EHRPD:
case TelephonyManager.NETWORK_TYPE_HSPAP:
nw = "01";
return "3G";
case TelephonyManager.NETWORK_TYPE_LTE:
nw = "11";
return "4G";
default:
return "Unknown";
}
}
public String getDataMode(Context context) {
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean x = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
if (x) {
if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return "On";
else
return "Off";
} else
return "No Active Network";
}
public void retrieveStatus(Context context) {
Context retrieveContext=context;
SharedPreferences sharedPreferences=retrieveContext.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
BatteryStatus = getBatteryLevel(retrieveContext);
if (BatteryStatus > 5 && BatteryStatus < 25) {
BatteryID = "11";
}
if (BatteryStatus > 25 && BatteryStatus < 50) {
BatteryID = "10";
}
if (BatteryStatus > 50 && BatteryStatus < 75) {
BatteryID = "01";
}
if (BatteryStatus > 75 && BatteryStatus < 100) {
BatteryID = "00";
}
NetworkID = getNetworkInterface(retrieveContext);
if (NetworkID == "ON") {
NetworkID = getDataConnectionType(retrieveContext);
if (NetworkStatus == "3G") {
NetworkStatus = "11";
}
if (NetworkStatus == "2G") {
NetworkStatus = "10";
}
} else {
NetworkStatus = "00";
}
NetworkID = getNetworkInterface(retrieveContext);
if (NetworkID == "On") {
NetworkStatus = "01";
}
roamingLevel = getRoaming(retrieveContext);
if (roamingLevel.equals("On")) {
roamingLevel = "1";
} else {
roamingLevel = "0";
}
ETTC=(sharedPreferences.getString("ETTC",""));
HoursToCharge=Integer.parseInt(ETTC);
if (HoursToCharge > 12) {
TimeID = "11";
}
if (HoursToCharge > 6 && HoursToCharge < 12) {
TimeID = "10";
}
if (HoursToCharge > 3 && HoursToCharge < 6) {
TimeID = "01";
}
if (HoursToCharge > 0 && HoursToCharge < 3) {
TimeID = "00";
}
DischargeRate=(sharedPreferences.getString("MyDischargePref",""));
System.out.println("Battery id:"+BatteryID);
System.out.println("ETTC:"+TimeID);
System.out.println("Network Status:"+NetworkStatus);
System.out.println("DischargeRate"+DischargeRate);
System.out.println("Roaming"+roamingLevel);
}
#Override
protected Context doInBackground(Context... params) {
Context backgroundcontext;
backgroundcontext=params[0];
getDischargeRate(backgroundcontext);
return backgroundcontext;
}
#Override
protected void onPostExecute(Context context) {
retrieveStatus(context);
}
}
and this is LogCat
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: Process: com.first.shash_000.anantha, PID: 30111
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at android.os.AsyncTask$3.done(AsyncTask.java:304)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:242)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at java.lang.Thread.run(Thread.java:818)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at android.os.Handler.<init>(Handler.java:200)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at android.os.Handler.<init>(Handler.java:114)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at android.os.CountDownTimer$1.<init>(CountDownTimer.java:114)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at android.os.CountDownTimer.(CountDownTimer.java:114)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at com.first.shash_000.anantha.CurrentStatus$1.(CurrentStatus.java:55)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at com.first.shash_000.anantha.CurrentStatus.getDischargeRate(CurrentStatus.java:54)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at com.first.shash_000.anantha.CurrentStatus.doInBackground(CurrentStatus.java:226)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at com.first.shash_000.anantha.CurrentStatus.doInBackground(CurrentStatus.java:26)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: at android.os.AsyncTask$2.call(AsyncTask.java:292)
You shouldn't put your CountDownTimer inside the doInBackground(), think about changing your code logic to run the timer on the main thread, in onPostExecute(Context context) for example

java.lang.NullPointerExeption before onCreate called for android app [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm having a tremendous amount of trouble figuring out how and why I am getting a java.lang.NullPointerException. I have no idea what is going on because it seems to happen before my program loads. I've set a breakpoint at the first line of my onCreate function and my android log still shows that I have a this exception thrown but the program continues to start and I reach my breakpoint. But stepping through I get very weird behavior. I will post the code in question as well as the log. if any other info needed to help me with this please ask. Also please excuse the indention. I'm fairly new to stack overflow
package com.example.facta.myapplication;
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.util.Log;
import org.xmlpull.v1.XmlPullParser;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by facta on 11/21/2014.
*/
public class SiteConfig {
private XmlResourceParser configParser;
ArrayList<RSSProviderInfo> RSSProviderInfos;
ArrayList<String> RSSProviderNames;
public SiteConfig()
{
RSSProviderInfos = new ArrayList<RSSProviderInfo>();
RSSProviderNames = new ArrayList<String>();
}
public ArrayList<RSSProviderInfo> getProvierInfos()
{
return RSSProviderInfos;
}
public ArrayList<String> getProvierNames()
{
return RSSProviderNames;
}
public void loadConfig(Context context, int resourceId)
{
configParser = context.getResources().getXml(resourceId);
RSSProviderInfos.clear();
RSSProviderInfo providerInfo = new RSSProviderInfo();
ArrayList<String> providerNames = loadProviders(configParser);
for(int i=0; i < providerNames.size(); i++)
{
providerInfo = LoadProviderInfo(configParser, providerNames.get(i));
if(providerInfo != null && providerInfo.isComplete()) {
RSSProviderInfos.add(providerInfo);
}
}
}
private RSSProviderInfo LoadProviderInfo(XmlResourceParser parser, String provider) {
RSSProviderInfo info = new RSSProviderInfo();
String attrName = new String();
try {
parser.next();
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG
&& parser.getName().equalsIgnoreCase("site" )) {
attrName = parser.getAttributeValue(null, "name");
if(attrName.equalsIgnoreCase(provider + ".enabled"))
{
/*
String value = parser.getAttributeValue(null, "value");
if(value.equalsIgnoreCase("no")) {
Log.d("LoadProviderInfo", "value does equal no");
return null; //If it's not enabled don't include it in the config
}
*/
}
else if(attrName.equalsIgnoreCase(provider + ".elementTag"))
{
info.setElementTag(parser.getAttributeValue(null, "value"));
}
else if(attrName.equalsIgnoreCase(provider + ".titleTag"))
{
info.setTitleTag(parser.getAttributeValue(null, "value"));
}
else if(attrName.equalsIgnoreCase(provider + ".linkTag"))
{
info.setLinkTag(parser.getAttributeValue(null, "value"));
}
else if(attrName.equalsIgnoreCase(provider + ".descriptionTag"))
{
info.setDescriptionTag(parser.getAttributeValue(null,"value"));
}
else if(attrName.equalsIgnoreCase(provider + ".url"))
{
info.addUrl(parser.getAttributeValue(null, "value"));
}
break;
}
eventType = parser.next();
}
}
catch (Exception e)
{
Log.d("loadProviderInfo", "Caught an exeption: " + e.toString() + e.getMessage());
e.printStackTrace();
StackTraceElement st[] = e.getStackTrace();
for(int i=0; i < st.length; i++)
{
Log.d("loadProviderInfo", "StackTraceElement[" + i + "] " + st[i].getLineNumber());
}
}
return null;
}
private ArrayList<String> loadProviders(XmlResourceParser parser) {
ArrayList<String> names = new ArrayList<String>();
try {
parser.next();
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG
&& parser.getName().equalsIgnoreCase("siteproviders")) {
String[] parsedNames = parser.getAttributeValue(null, "value").split(",");
for (int i=0; i < parsedNames.length; i++)
{
names.add(i, parsedNames[i]);
}
break;
}
eventType = parser.next();
}
}
catch (Exception e)
{
Log.d("loadProviderInfo", "Caught an exeption: " + e.toString() + e.getMessage());
e.printStackTrace();
StackTraceElement st[] = e.getStackTrace();
for(int i=0; i < st.length; i++)
{
Log.d("loadProviderInfo", "StackTraceElement[" + i + "] " + st[i].getLineNumber());
}
}
return names;
}
}
Log Below
11-23 18:20:40.830 537-537/com.example.facta.myapplication D/dalvikvm﹕ Not late-enabling CheckJNI (already on)
11-23 18:20:41.569 537-542/com.example.facta.myapplication I/dalvikvm﹕ threadid=3: reacting to signal 3
11-23 18:20:41.580 537-542/com.example.facta.myapplication I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
11-23 18:20:42.040 537-537/com.example.facta.myapplication D/loadProviders﹕ Caught an exeption: java.lang.NullPointerException
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ java.lang.NullPointerException
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at com.example.facta.myapplication.SiteConfig.loadProviders(SiteConfig.java:119)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at com.example.facta.myapplication.SiteConfig.loadConfig(SiteConfig.java:42)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at com.example.facta.myapplication.ResultsActivity.fetch(ResultsActivity.java:94)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at com.example.facta.myapplication.ResultsActivity.onCreate(ResultsActivity.java:62)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.app.Activity.performCreate(Activity.java:4465)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.app.ActivityThread.access$600(ActivityThread.java:123)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:99)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:4424)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:511)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-23 18:20:42.040 537-537/com.example.facta.myapplication W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
11-23 18:20:42.070 537-542/com.example.facta.myapplication I/dalvikvm﹕ threadid=3: reacting to signal 3
11-23 18:20:42.080 537-542/com.example.facta.myapplication I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
11-23 18:20:42.270 537-537/com.example.facta.myapplication D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
11-23 18:37:36.440 669-669/com.example.facta.myapplication W/ActivityThread﹕ Application com.example.facta.myapplication is waiting for the debugger on port 8100...
11-23 18:37:36.490 669-669/com.example.facta.myapplication I/System.out﹕ Sending WAIT chunk
11-23 18:37:36.701 669-675/com.example.facta.myapplication I/dalvikvm﹕ Debugger is active
11-23 18:37:36.740 669-669/com.example.facta.myapplication I/System.out﹕ Debugger has connected
11-23 18:37:36.740 669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:36.900 669-674/com.example.facta.myapplication I/dalvikvm﹕ threadid=3: reacting to signal 3
11-23 18:37:36.910 669-674/com.example.facta.myapplication I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
11-23 18:37:36.940 669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:37.140 669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:37.680 669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:37.880 669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:38.079 669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:38.279 669-669/com.example.facta.myapplication I/System.out﹕ waiting for debugger to settle...
11-23 18:37:38.369 669-674/com.example.facta.myapplication I/dalvikvm﹕ threadid=3: reacting to signal 3
11-23 18:37:38.379 669-674/com.example.facta.myapplication I/dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'
Calling Activity Below
package com.example.facta.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import java.util.ArrayList;
/* TODO
Need to make a config file that has the following format.
site.names = CNN,FOX,NBC,AP
site.CNN.enabled = yes
site.CNN.searchtag = item
site.CNN.titletag = title
site.CNN.linktag = link
site.CNN.descriptiontag = description
site.CNN.numurls = 10
site.CNN.url.1 = "https://www.cnn.com/top_stories.rss
site.CNN.url.2 = "https://www.cnn.com/world_politics.rss
site.FOX.enabled = no
site.FOX.searchtag = story
*/
public class ResultsActivity extends Activity {
private ArrayList<String> finalUrls = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
finalUrls.add("http://rss.cnn.com/rss/cnn_topstories.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_world.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_us.rss");
finalUrls.add("http://rss.cnn.com/rss/money_latest.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_allpolitics.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_crime.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_tech.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_health.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_showbiz.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_travel.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_living.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_freevideo.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_studentnews.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_mostpopular.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_latest.rss");
finalUrls.add("http://rss.ireport.com/feeds/oncnn.rss");
finalUrls.add("http://rss.cnn.com/rss/cnn_behindthescenes.rss");
this.fetch();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_results, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void fetch() {
/**TODO possibly load config then for each provider pass in RSSProviderInfo into HandleXML
That way HandleXML can set all the tags it needs and then parse the urls from the param
*/
SiteConfig siteConfig = new SiteConfig();
siteConfig.loadConfig(this, R.xml.sites);
ArrayList<RSSProviderInfo> siteConfigProvierInfos = siteConfig.getProvierInfos();
for (int k = 0; k < siteConfigProvierInfos.size(); k++) {
HandleXML obj = new HandleXML(siteConfigProvierInfos.get(k));
obj.fetchXML();
while (!obj.parsingComplete) {
try {
Thread.sleep(500, 0);
} catch (InterruptedException e) {
e.printStackTrace();
}
final ArrayList<RSSInfo> rssInfos = obj.getRssInfos();
final TableLayout tableLayout = (TableLayout) findViewById(R.id.results_table);
Log.d("fetch", "Size of rssinfos " + rssInfos.size());
for (int i = 0; i < rssInfos.size(); i++) {
final int index = i;
final TableRow tableRow = new TableRow(this);
tableRow.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
//Get information from infos
final TextView textView = new TextView(this);
textView.setText(rssInfos.get(index).getTitle());
textView.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
tableRow.setClickable(true);
tableRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(rssInfos.get(index).getLink()));
startActivity(intent);
}
});
tableRow.addView(textView);
tableLayout.addView(tableRow);
}
Log.d("fetch", "tableLayout = " + tableLayout.toString());
}
}
}
}
Sorry for the confusion. I think I need to review Android Studio. That is an error from a previous version of my code (notice the date of yesterday 11-23). I thought "clear all" in logcat literally cleared all and delete it. I just found out I am wrong. There are no NPEs at this time that I am aware of. Sorry for the waste of time....lesson learned for me using android studio. After noticing this I was able to find the logical error that caused the program to exit shortly after. Thanks all for the help

connecting android application to database on the server?

Iam trying to make a connection between my database on the MYSQL(iam using the WAMP server) and android application , but when i run the application an exception is raised , i fixed the log cat and its points to this statement
jArray = new JSONArray(result);
03-18 12:48:59.580: E/AndroidRuntime(458): at org.json.JSONArray.<init>(JSONArray.java:87)
why this exception occur ?and how i can solve it ?
thanks in advanced..
this is my code :
City.php:
<?php
mysql_connect("localhost","username","password");
mysql_select_db("Deal");
$sql=mysql_query("select * from City where Name like 'R%' ");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
the java class:
public class ConnectionActivity extends ListActivity {
int ct_id;
String[] ct_name = null;
JSONArray jArray;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String result = null;
InputStream is = null;
StringBuilder sb = null;
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/city.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// paring data
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
ct_name = new String[jArray.length()];
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
ct_id = json_data.getInt("City_ID");
ct_name[i] = json_data.getString("Name");
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "No City Found", Toast.LENGTH_LONG)
.show();
} catch (ParseException e1) {
e1.printStackTrace();
}
ListView lv;
lv = getListView();
lv.setTextFilterEnabled(true);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, ct_name);
setListAdapter(adapter);
}
public void onListItemClick(ListView parent, View v, int position, long id)
{
Toast.makeText(this,"You have selected " + ct_name[position],Toast.LENGTH_SHORT).show();
}
}
log:
03-18 13:28:46.923: W/ActivityThread(623): Application Com.Connection is waiting for the debugger on port 8100...
03-18 13:28:46.973: I/System.out(623): Sending WAIT chunk
03-18 13:28:46.983: I/dalvikvm(623): Debugger is active
03-18 13:28:47.174: I/System.out(623): Debugger has connected
03-18 13:28:47.183: I/System.out(623): waiting for debugger to settle...
03-18 13:28:47.383: I/System.out(623): waiting for debugger to settle...
03-18 13:28:47.583: I/System.out(623): waiting for debugger to settle...
03-18 13:28:47.783: I/System.out(623): waiting for debugger to settle...
03-18 13:28:47.993: I/System.out(623): waiting for debugger to settle...
03-18 13:28:48.193: I/System.out(623): waiting for debugger to settle...
03-18 13:28:48.403: I/System.out(623): waiting for debugger to settle...
03-18 13:28:48.603: I/System.out(623): waiting for debugger to settle...
03-18 13:28:48.803: I/System.out(623): waiting for debugger to settle...
03-18 13:28:49.003: I/System.out(623): waiting for debugger to settle...
03-18 13:28:49.203: I/System.out(623): waiting for debugger to settle...
03-18 13:28:49.413: I/System.out(623): waiting for debugger to settle...
03-18 13:28:49.613: I/System.out(623): debugger has settled (1497)
03-18 13:30:17.593: E/log_tag(623): Error in http connectionandroid.os.NetworkOnMainThreadException
03-18 13:30:34.315: E/log_tag(623): Error converting result java.lang.NullPointerException
You get an error as you try to perform HTTP connection on the main thread:
03-18 13:30:17.593: E/log_tag(623): Error in http connectionandroid.os.NetworkOnMainThreadException
As far as I can see, the HTTP code is correct, but you are running it on the UI thread. This is not allowed. You need to perform such long actions on a background thread. Android gives you a very easy to use facilities to perform long action on the background and publish the results on the main (UI) thread. One of the most useful is AsyncTask. I would recommend that you read Painless Threading, as it will help you a lot IMO.

Categories