Keep getting Force close when I test my app - java

I'm build a app that consist of user login and registration but every time I test it on the emulator I receive a force close. Below are the errors I'm receiving in the log cat:
08-14 14:06:28.853: D/dalvikvm(828): GC_FOR_ALLOC freed 108K, 3% free 8262K/8455K, paused 89ms, total 92ms
08-14 14:06:29.273: I/Choreographer(828): Skipped 72 frames! The application may be doing too much work on its main thread.
08-14 14:06:29.373: D/gralloc_goldfish(828): Emulator without GPU emulation detected.
08-14 14:06:29.373: D/dalvikvm(828): GC_CONCURRENT freed 5K, 3% free 8660K/8839K, paused 110ms+28ms, total 365ms
08-14 14:06:29.902: I/Choreographer(828): Skipped 85 frames! The application may be doing too much work on its main thread.
08-14 14:06:32.533: D/dalvikvm(828): GC_CONCURRENT freed 32K, 3% free 9027K/9223K, paused 81ms+111ms, total 343ms
08-14 14:06:32.813: I/Choreographer(828): Skipped 71 frames! The application may be doing too much work on its main thread.
08-14 14:06:33.303: I/Choreographer(828): Skipped 38 frames! The application may be doing too much work on its main thread.
08-14 14:06:39.854: D/InputEventConsistencyVerifier(828): KeyEvent: ACTION_UP but key was not down.
08-14 14:06:39.854: D/InputEventConsistencyVerifier(828): in android.widget.EditText#412b2f68
08-14 14:06:39.854: D/InputEventConsistencyVerifier(828): 0: sent at 1614282000000, KeyEvent { action=ACTION_UP, keyCode=KEYCODE_M, scanCode=50, metaState=0, flags=0x8, repeatCount=0, eventTime=1614282, downTime=1614282, deviceId=0, source=0x301 }
08-14 14:06:39.874: D/InputEventConsistencyVerifier(828): KeyEvent: ACTION_UP but key was not down.
08-14 14:06:39.874: D/InputEventConsistencyVerifier(828): in android.widget.EditText#412b2f68
08-14 14:06:39.874: D/InputEventConsistencyVerifier(828): 0: sent at 1614392000000, KeyEvent { action=ACTION_UP, keyCode=KEYCODE_TAB, scanCode=15, metaState=0, flags=0x8, repeatCount=0, eventTime=1614392, downTime=1614282, deviceId=0, source=0x301 }
08-14 14:06:39.874: D/InputEventConsistencyVerifier(828): -- recent events --
08-14 14:06:39.874: D/InputEventConsistencyVerifier(828): 1: sent at 1614282000000, (unhandled) KeyEvent { action=ACTION_UP, keyCode=KEYCODE_M, scanCode=50, metaState=0, flags=0x80000008, repeatCount=0, eventTime=1614282, downTime=1614282, deviceId=0, source=0x301 }
08-14 14:07:02.362: D/AndroidRuntime(828): Shutting down VM
08-14 14:07:02.362: W/dalvikvm(828): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
**08-14 14:07:02.472: E/AndroidRuntime(828): FATAL EXCEPTION: main
08-14 14:07:02.472: E/AndroidRuntime(828): android.os.NetworkOnMainThreadException
08-14 14:07:02.472: E/AndroidRuntime(828): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
08-14 14:07:02.472: E/AndroidRuntime(828): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
08-14 14:07:02.472: E/AndroidRuntime(828): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
08-14 14:07:02.472: E/AndroidRuntime(828): at libcore.io.IoBridge.connect(IoBridge.java:112)
08-14 14:07:02.472: E/AndroidRuntime(828): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
08-14 14:07:02.472: E/AndroidRuntime(828): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
08-14 14:07:02.472: E/AndroidRuntime(828): at java.net.Socket.connect(Socket.java:842)
08-14 14:07:02.472: E/AndroidRuntime(828): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
08-14 14:07:02.472: E/AndroidRuntime(828): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
08-14 14:07:02.472: E/AndroidRuntime(828): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-14 14:07:02.472: E/AndroidRuntime(828): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-14 14:07:02.472: E/AndroidRuntime(828): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-14 14:07:02.472: E/AndroidRuntime(828): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-14 14:07:02.472: E/AndroidRuntime(828): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-14 14:07:02.472: E/AndroidRuntime(828): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-14 14:07:02.472: E/AndroidRuntime(828): at library.JSONParser.getJSONFromUrl(JSONParser.java:41)
08-14 14:07:02.472: E/AndroidRuntime(828): at library.UserFunctions.loginUser(UserFunctions.java:40)
08-14 14:07:02.472: E/AndroidRuntime(828): at com.thryfting.www.LoginActivity.onClick(LoginActivity.java:66)
08-14 14:07:02.472: E/AndroidRuntime(828): at android.view.View.performClick(View.java:4084)
08-14 14:07:02.472: E/AndroidRuntime(828): at android.view.View$PerformClick.run(View.java:16966)
08-14 14:07:02.472: E/AndroidRuntime(828): at android.os.Handler.handleCallback(Handler.java:615)
08-14 14:07:02.472: E/AndroidRuntime(828): at android.os.Handler.dispatchMessage(Handler.java:92)
08-14 14:07:02.472: E/AndroidRuntime(828): at android.os.Looper.loop(Looper.java:137)
08-14 14:07:02.472: E/AndroidRuntime(828): at android.app.ActivityThread.main(ActivityThread.java:4745)
08-14 14:07:02.472: E/AndroidRuntime(828): at java.lang.reflect.Method.invokeNative(Native Method)
08-14 14:07:02.472: E/AndroidRuntime(828): at java.lang.reflect.Method.invoke(Method.java:511)
08-14 14:07:02.472: E/AndroidRuntime(828): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
08-14 14:07:02.472: E/AndroidRuntime(828): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-14 14:07:02.472: E/AndroidRuntime(828): at dalvik.system.NativeStart.main(Native Method)**
Updated code for register activity:
package com.thryfting.www;
import org.json.JSONException;
import org.json.JSONObject;
import library.DatabaseHandler;
import library.UserFunctions;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockActivity;
public class RegisterActivity extends SherlockActivity implements OnClickListener{
Button btnRegister;
EditText inputFullName;
EditText inputEmail;
EditText inputPassword;
TextView registerErrorMsg;
TextView loginScreen;
//JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
loginScreen = (TextView) findViewById(R.id.link_to_login);
inputEmail = (EditText) findViewById(R.id.etemailSignup);
inputPassword = (EditText) findViewById(R.id.etPasswordSignup);
inputFullName = (EditText) findViewById(R.id.etFullnameSignup);
btnRegister = (Button) findViewById(R.id.btnRegister);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
loginScreen.setOnClickListener(this);
btnRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.btnRegister:
new register().execute(KEY_SUCCESS);
break;
case R.id.link_to_login:
Intent i = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(i);
//Close Registration View
finish();
break;
}
}
public class register extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
try{
if(json.getString(KEY_SUCCESS) != null){
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
//user successfully registered
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
//Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
}else{
//Error in registration
registerErrorMsg.setText("Error occured in registration");
}
}
} catch(JSONException e){
e.printStackTrace();
} finally{
//Launch Dashboard
Intent dashboard = new Intent (getApplicationContext(), Timeline.class);
//Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//Close registration screen
finish();
}
return null;
}
}
}
New error messages below:
08-15 14:53:32.940: W/dalvikvm(865): threadid=11: thread exiting with uncaught exception (group=0x40a13300)
08-15 14:53:33.060: E/AndroidRuntime(865): FATAL EXCEPTION: AsyncTask #1
08-15 14:53:33.060: E/AndroidRuntime(865): java.lang.RuntimeException: An error occured while executing doInBackground()
08-15 14:53:33.060: E/AndroidRuntime(865): at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-15 14:53:33.060: E/AndroidRuntime(865): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-15 14:53:33.060: E/AndroidRuntime(865): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-15 14:53:33.060: E/AndroidRuntime(865): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-15 14:53:33.060: E/AndroidRuntime(865): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-15 14:53:33.060: E/AndroidRuntime(865): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-15 14:53:33.060: E/AndroidRuntime(865): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-15 14:53:33.060: E/AndroidRuntime(865): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-15 14:53:33.060: E/AndroidRuntime(865): at java.lang.Thread.run(Thread.java:856)
08-15 14:53:33.060: E/AndroidRuntime(865): Caused by: java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=register
08-15 14:53:33.060: E/AndroidRuntime(865): at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:591)
08-15 14:53:33.060: E/AndroidRuntime(865): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:293)
08-15 14:53:33.060: E/AndroidRuntime(865): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-15 14:53:33.060: E/AndroidRuntime(865): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-15 14:53:33.060: E/AndroidRuntime(865): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-15 14:53:33.060: E/AndroidRuntime(865): at library.JSONParser.getJSONFromUrl(JSONParser.java:41)
08-15 14:53:33.060: E/AndroidRuntime(865): at library.UserFunctions.registerUser(UserFunctions.java:63)
08-15 14:53:33.060: E/AndroidRuntime(865): at com.thryfting.www.RegisterActivity$register.doInBackground(RegisterActivity.java:89)
08-15 14:53:33.060: E/AndroidRuntime(865): at com.thryfting.www.RegisterActivity$register.doInBackground(RegisterActivity.java:1)
08-15 14:53:33.060: E/AndroidRuntime(865): at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-15 14:53:33.060: E/AndroidRuntime(865): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-15 14:53:33.060: E/AndroidRuntime(865): ... 5 more
08-15 14:53:34.812: I/Choreographer(865): Skipped 93 frames! The application may be doing too much work on its main thread.
08-15 14:53:36.512: I/Process(865): Sending signal. PID: 865 SIG: 9
public JSONObject registerUser(String name, String email, String password){
//building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
//Getting JSON object
JSONObject json = jsonParser.getJSONFromUrl(register_tag, params);
//return json
return json;
}

Your getting a StrictMode violation. This means that you are doing something blocking on the UI Thread. Hence the reason for
android.os.NetworkOnMainThreadException
From the rest of your LOG it appears your performing a web request.
Make sure that HTTP request is wrapped in an AsyncTask (or something similar)

It seems like you are trying to do your login and registration on the main Thread. First of all this is bad practice, and it can't be done on recent API levels.
All you need to do is make your network connections in a separate thread, be it an AsyncTask or just a plain old Thread()
as an example :
use this
public void login()
{
new Thread(new Runnable() {
#Override
public void run() {
//your network connection goes here
}
}).start();
}
instead of :
public void login()
{
//your network connection goes here
}

Try to check the same in a mobile with internet connectivity.
The logcat also displays that the emulator doesnt has a GPS connectivity.

Related

Android NetworkOnMainThreadException exception

I had this Networkonmainthread exception in my activity. I searched for a solution for the problem. While I was searching, I found that I should use AsyncTask. After I tried AsyncTask, I am still facing the same problem.
This is my register activity:
private class MyAsyncTask extends AsyncTask<String, Void, JSONObject> {
protected JSONObject doInBackground(String... params) {
UserFunctions userFunction = new UserFunctions();
if (params.length != 3)
return null;
JSONObject json = userFunction.registerUser(params[0], params[1], params[2]);
return json;
}
protected void onPostExecute(JSONObject json) {
// check for login response
try {
if (json != null && json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
UserFunctions userFunction = new UserFunctions();
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in registration
registerErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.registerName);
inputEmail = (EditText) findViewById(R.id.registerEmail);
inputPassword = (EditText) findViewById(R.id.registerPassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
new MyAsyncTask().execute(name, email, password);
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in registration
registerErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
// Close Registration View
finish();
}
});
}
}
This is my logcat:
09-26 00:56:23.865: D/AndroidRuntime(791): Shutting down VM
09-26 00:56:23.875: W/dalvikvm(791): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
09-26 00:56:23.925: E/AndroidRuntime(791): FATAL EXCEPTION: main
09-26 00:56:23.925: E/AndroidRuntime(791): android.os.NetworkOnMainThreadException
09-26 00:56:23.925: E/AndroidRuntime(791): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
09-26 00:56:23.925: E/AndroidRuntime(791): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
09-26 00:56:23.925: E/AndroidRuntime(791): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
09-26 00:56:23.925: E/AndroidRuntime(791): at libcore.io.IoBridge.connect(IoBridge.java:112)
09-26 00:56:23.925: E/AndroidRuntime(791): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
09-26 00:56:23.925: E/AndroidRuntime(791): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
09-26 00:56:23.925: E/AndroidRuntime(791): at java.net.Socket.connect(Socket.java:842)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
09-26 00:56:23.925: E/AndroidRuntime(791): at library.JSONParser.getJSONFromUrl(JSONParser.java:45)
09-26 00:56:23.925: E/AndroidRuntime(791): at library.UserFunctions.registerUser(UserFunctions.java:62)
09-26 00:56:23.925: E/AndroidRuntime(791): at com.example.bustracker.RegisterActivity$1.onClick(RegisterActivity.java:105)
09-26 00:56:23.925: E/AndroidRuntime(791): at android.view.View.performClick(View.java:4084)
09-26 00:56:23.925: E/AndroidRuntime(791): at android.view.View$PerformClick.run(View.java:16966)
09-26 00:56:23.925: E/AndroidRuntime(791): at android.os.Handler.handleCallback(Handler.java:615)
09-26 00:56:23.925: E/AndroidRuntime(791): at android.os.Handler.dispatchMessage(Handler.java:92)
09-26 00:56:23.925: E/AndroidRuntime(791): at android.os.Looper.loop(Looper.java:137)
09-26 00:56:23.925: E/AndroidRuntime(791): at android.app.ActivityThread.main(ActivityThread.java:4745)
09-26 00:56:23.925: E/AndroidRuntime(791): at java.lang.reflect.Method.invokeNative(Native Method)
09-26 00:56:23.925: E/AndroidRuntime(791): at java.lang.reflect.Method.invoke(Method.java:511)
09-26 00:56:23.925: E/AndroidRuntime(791): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
09-26 00:56:23.925: E/AndroidRuntime(791): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-26 00:56:23.925: E/AndroidRuntime(791): at dalvik.system.NativeStart.main(Native Method)
09-26 00:56:24.215: W/System.err(791): org.apache.http.conn.HttpHostConnectException: Connection to http:// refused
09-26 00:56:24.436: W/System.err(791): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
09-26 00:56:24.546: W/System.err(791): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-26 00:56:24.786: W/System.err(791): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-26 00:56:24.967: W/System.err(791): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
09-26 00:56:24.995: W/System.err(791): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
09-26 00:56:25.017: W/System.err(791): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-26 00:56:25.017: W/System.err(791): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
09-26 00:56:25.165: W/System.err(791): at library.JSONParser.getJSONFromUrl(JSONParser.java:45)
09-26 00:56:25.235: W/System.err(791): at library.UserFunctions.registerUser(UserFunctions.java:62)
09-26 00:56:25.264: W/System.err(791): at com.example.bustracker.RegisterActivity$MyAsyncTask.doInBackground(RegisterActivity.java:43)
09-26 00:56:25.265: W/System.err(791): at com.example.bustracker.RegisterActivity$MyAsyncTask.doInBackground(RegisterActivity.java:1)
09-26 00:56:25.285: W/System.err(791): at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-26 00:56:25.305: W/System.err(791): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
09-26 00:56:25.535: W/System.err(791): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
09-26 00:56:25.535: W/System.err(791): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-26 00:56:25.675: W/System.err(791): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
09-26 00:56:25.956: W/System.err(791): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
09-26 00:56:26.115: W/System.err(791): at java.lang.Thread.run(Thread.java:856)
09-26 00:56:26.147: W/System.err(791): Caused by: java.net.ConnectException: failed to connect to /127.0.0.1 (port 8888): connect failed: ECONNREFUSED (Connection refused)
09-26 00:56:26.226: W/System.err(791): at libcore.io.IoBridge.connect(IoBridge.java:114)
09-26 00:56:26.226: W/System.err(791): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
09-26 00:56:26.236: W/System.err(791): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
09-26 00:56:26.236: W/System.err(791): at java.net.Socket.connect(Socket.java:842)
09-26 00:56:26.246: W/System.err(791): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
09-26 00:56:26.255: W/System.err(791): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
09-26 00:56:26.255: W/System.err(791): ... 17 more
09-26 00:56:26.266: W/System.err(791): Caused by: libcore.io.ErrnoException: connect failed: ECONNREFUSED (Connection refused)
09-26 00:56:26.276: W/System.err(791): at libcore.io.Posix.connect(Native Method)
09-26 00:56:26.286: W/System.err(791): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
09-26 00:56:26.286: W/System.err(791): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
09-26 00:56:26.286: W/System.err(791): at libcore.io.IoBridge.connect(IoBridge.java:112)
09-26 00:56:26.296: W/System.err(791): ... 22 more
09-26 00:56:26.296: E/Buffer Error(791): Error converting result java.lang.NullPointerException
09-26 00:56:26.305: E/JSON Parser(791): Error parsing data org.json.JSONException: End of input at character 0 of
09-26 00:56:27.146: I/Process(791): Sending signal. PID: 791 SIG: 9
What am I doing wrong?
The stacktrace says you're calling a network operation in getJSONFromUrl() and calling that on the UI thread in registerUser(). The code here looks to be the culprit:
new MyAsyncTask().execute(name, email, password);
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
You're first invoking the registerUser() in a background asynctask (good!) and then only a couple of lines later doing the same again on the main thread (bad!). Remove the latter.
I bet userFunction.logoutUser(getApplicationContext()); issues network request to logout user thus error caused by accessing network on main thread (onPostResult runs on ui thread, in contrary to doInBackground)
According to the code in your post, you're still calling userFunction.registerUser directly from inside of the onClickListener handler - right after calling MyAsyncTask.execute. It's that registerUser call that the logcat output is complaining about, not the one in the AsyncTask. Did you mean to delete the duplicate call from the onClickListener handler after you moved that logic to the AsyncTask?

Location based android application error

When i run app it give message unfortunately loca has stopped and close app
Java coding
package com.example.loca;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener {
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat, place1, currentlocation, btn_text;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
Toast.makeText(getApplicationContext(), currentlocation , Toast.LENGTH_LONG).show();
}
#Override
public void onLocationChanged(Location location) {
Toast.makeText(getApplicationContext(), currentlocation , Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
AND LOGCAT is
05-14 01:20:39.210: D/AndroidRuntime(1177): Shutting down VM
05-14 01:20:39.210: W/dalvikvm(1177): threadid=1: thread exiting with uncaught exception (group=0xb3aebb90)
05-14 01:20:39.230: E/AndroidRuntime(1177): FATAL EXCEPTION: main
05-14 01:20:39.230: E/AndroidRuntime(1177): Process: com.example.loca, PID: 1177
05-14 01:20:39.230: E/AndroidRuntime(1177): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.loca/com.example.loca.MainActivity}: java.lang.SecurityException: "gps" location provider requires ACCESS_FINE_LOCATION permission.
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.app.ActivityThread.access$700(ActivityThread.java:135)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.os.Handler.dispatchMessage(Handler.java:102)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.os.Looper.loop(Looper.java:137)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.app.ActivityThread.main(ActivityThread.java:4998)
05-14 01:20:39.230: E/AndroidRuntime(1177): at java.lang.reflect.Method.invokeNative(Native Method)
05-14 01:20:39.230: E/AndroidRuntime(1177): at java.lang.reflect.Method.invoke(Method.java:515)
05-14 01:20:39.230: E/AndroidRuntime(1177): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
05-14 01:20:39.230: E/AndroidRuntime(1177): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
05-14 01:20:39.230: E/AndroidRuntime(1177): at dalvik.system.NativeStart.main(Native Method)
05-14 01:20:39.230: E/AndroidRuntime(1177): Caused by: java.lang.SecurityException: "gps" location provider requires ACCESS_FINE_LOCATION permission.
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.os.Parcel.readException(Parcel.java:1461)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.os.Parcel.readException(Parcel.java:1415)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.location.ILocationManager$Stub$Proxy.requestLocationUpdates(ILocationManager.java:540)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.location.LocationManager.requestLocationUpdates(LocationManager.java:860)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.location.LocationManager.requestLocationUpdates(LocationManager.java:454)
05-14 01:20:39.230: E/AndroidRuntime(1177): at com.example.loca.MainActivity.onCreate(MainActivity.java:34)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.app.Activity.performCreate(Activity.java:5243)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
05-14 01:20:39.230: E/AndroidRuntime(1177): ... 11 more
05-14 01:20:47.040: I/Process(1177): Sending signal. PID: 1177 SIG: 9
You need to request the FINE_LOCATION permission, just like the exception says.
Your logcat clearly said
Caused by: java.lang.SecurityException: "gps" location provider
requires ACCESS_FINE_LOCATION permission. 05-14 01:20:39.230:
E/AndroidRuntime(1177):
You need to add below permission in your manifest.xml file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
The log says it all :
location provider requires ACCESS_FINE_LOCATION permission.
Add this permission in AndroidManifest.xml and your app will work fine.

AChartEngine - Charts with data from parse.com won't display

I would like to create applications forming charts based on data from parse.com. I have read some examples and tutorials but still have problem with displaying charts. Below is my code:
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import java.util.ArrayList;
public class LineGraph {
public ArrayList<Integer> dataArray;
XYMultipleSeriesDataset dataset;
XYMultipleSeriesRenderer renderer;
public static boolean ClickEnabled = true;
public Intent getIntent(Context context) {
ArrayList<Integer> y = this.dataArray;
XYSeries seriesY = new XYSeries("Y");
for (int i = 0; i < y.size(); i++) {
seriesY.add(i, y.get(i));
}
dataset = new XYMultipleSeriesDataset();
dataset.addSeries(seriesY);
renderer.setPanEnabled(true, false);
renderer.setClickEnabled(ClickEnabled);
renderer.setBackgroundColor(Color.WHITE);
renderer.setApplyBackgroundColor(true);
renderer.setChartTitle("Simple data");
renderer.setAxesColor(Color.BLACK);
XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
XYSeriesRenderer renderer = new XYSeriesRenderer();
renderer.setColor(Color.RED);
renderer.setPointStyle(PointStyle.DIAMOND);
mRenderer.addSeriesRenderer(renderer);
Intent intent = ChartFactory.getLineChartIntent(context, dataset, mRenderer, "Line Graph Title");
return intent;
}
public void getData() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Counters_data");
query.getInBackground("lxFzCTeOcl", new GetCallback<ParseObject>() {
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
String object = parseObject.getString("value");
Integer objectValue = Integer.parseInt(object);
if (dataArray == null) {
dataArray = new ArrayList<Integer>();
dataArray.add(objectValue);
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
}
And there is how I invoke charts:
public void lineGraphHandler(View view) {
LineGraph line = new LineGraph();
line.getData();
Intent lineIntent = line.getIntent(this);
startActivity(lineIntent);
}
And XML part:
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/counters"
android:onClick="lineGraphHandler"
android:text="Charts"
android:id="#+id/charts"/>
There is my logcat:
03-26 08:42:13.096 1229-1229/com.example.tst D/dalvikvm﹕ Late-enabling
CheckJNI 03-26 08:42:13.487 1229-1229/com.example.tst D/libEGL﹕ loaded
/system/lib/egl/libEGL_genymotion.so 03-26 08:42:13.491
1229-1229/com.example.tst D/﹕ HostConnection::get() New Host
Connection established 0xb94f4270, tid 1229 03-26 08:42:13.551
1229-1229/com.example.tst D/libEGL﹕ loaded
/system/lib/egl/libGLESv1_CM_genymotion.so 03-26 08:42:13.551
1229-1229/com.example.tst D/libEGL﹕ loaded
/system/lib/egl/libGLESv2_genymotion.so 03-26 08:42:14.035
1229-1229/com.example.tst W/EGL_genymotion﹕ eglSurfaceAttrib not
implemented 03-26 08:42:14.039 1229-1229/com.example.tst
E/OpenGLRenderer﹕ Getting MAX_TEXTURE_SIZE from GradienCache 03-26
08:42:14.043 1229-1229/com.example.tst E/OpenGLRenderer﹕
MAX_TEXTURE_SIZE: 4096 03-26 08:42:14.055 1229-1229/com.example.tst
E/OpenGLRenderer﹕ Getting MAX_TEXTURE_SIZE from
Caches::initConstraints() 03-26 08:42:14.063 1229-1229/com.example.tst
E/OpenGLRenderer﹕ MAX_TEXTURE_SIZE: 4096 03-26 08:42:14.063
1229-1229/com.example.tst D/OpenGLRenderer﹕ Enabling debug mode 0
03-26 08:42:50.327 1229-1229/com.example.tst D/dalvikvm﹕ GC_FOR_ALLOC
freed 200K, 8% free 2975K/3228K, paused 10ms, total 13ms 03-26
08:42:51.675 1229-1229/com.example.tst D/dalvikvm﹕ GC_FOR_ALLOC freed
431K, 14% free 3056K/3540K, paused 22ms, total 28ms 03-26 08:42:52.043
1229-1229/com.example.tst W/EGL_genymotion﹕ eglSurfaceAttrib not
implemented 03-26 08:42:53.543 1229-1229/com.example.tst
I/Choreographer﹕ Skipped 89 frames! The application may be doing too
much work on its main thread. 03-26 08:43:01.747
1229-1229/com.example.tst D/AndroidRuntime﹕ Shutting down VM 03-26
08:43:01.747 1229-1229/com.example.tst W/dalvikvm﹕ threadid=1: thread
exiting with uncaught exception (group=0xa4d8fb20) 03-26 08:43:01.767
1229-1229/com.example.tst E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.tst, PID: 1229 java.lang.IllegalStateException:
Could not execute method of the activity at
android.view.View$1.onClick(View.java:3823) at
android.view.View.performClick(View.java:4438) at
android.view.View$PerformClick.run(View.java:18422) at
android.os.Handler.handleCallback(Handler.java:733) at
android.os.Handler.dispatchMessage(Handler.java:95) at
android.os.Looper.loop(Looper.java:136) at
android.app.ActivityThread.main(ActivityThread.java:5017) 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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) at
dalvik.system.NativeStart.main(Native Method) Caused by:
java.lang.reflect.InvocationTargetException at
java.lang.reflect.Method.invokeNative(Native Method) at
java.lang.reflect.Method.invoke(Method.java:515) at
android.view.View$1.onClick(View.java:3818) at
android.view.View.performClick(View.java:4438) at
android.view.View$PerformClick.run(View.java:18422) at
android.os.Handler.handleCallback(Handler.java:733) at
android.os.Handler.dispatchMessage(Handler.java:95) at
android.os.Looper.loop(Looper.java:136) at
android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method) Caused by:
java.lang.NullPointerException at
com.example.tst.LineGraph.getIntent(LineGraph.java:36) at
com.example.tst.MainActivity.lineGraphHandler(MainActivity.java:44)
at java.lang.reflect.Method.invokeNative(Native Method) at
java.lang.reflect.Method.invoke(Method.java:515) at
android.view.View$1.onClick(View.java:3818) at
android.view.View.performClick(View.java:4438) at
android.view.View$PerformClick.run(View.java:18422) at
android.os.Handler.handleCallback(Handler.java:733) at
android.os.Handler.dispatchMessage(Handler.java:95) at
android.os.Looper.loop(Looper.java:136) at
android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method) 03-26 08:43:04.507
1229-1229/com.example.tst I/Process﹕ Sending signal. PID: 1229 SIG: 9
I don't understand where the problem is. My app starts but crashes immediately when I push "chart" button. Is it data type of problem or because I misunderstand something?
Thank you in advance.
I tried like this but still got crash:
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
String object = parseObject.getString("value");
Integer objectValue = Integer.parseInt(object);
if (dataArray == null) {
dataArray = new ArrayList<Integer>();
dataArray.add(objectValue);
ArrayList<Integer> y = dataArray;
XYSeries seriesY = new XYSeries("Y");
for (int i = 0; i < y.size(); i++) {
seriesY.add(i, y.get(i));
dataset = new XYMultipleSeriesDataset();
dataset.addSeries(seriesY);
}
}
Your getData() retrieves the data asynchronously. dataArray won't be initialized immediately when you call getIntent().
Wait for the async operation to complete before using the data there. For example, call the code requiring that data from the done() callback.

App stops when i want to open another class from a clickable listview

I am trying to make a listview and when i click to an item i want to opwn another class. The second class is actually for opening a file from raw folder.
my class is
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Cod_rutier extends MainActivity2A {
private ListView lv1;
private String lv_arr[]={"CAP.1: Dispozitii generale",
"CAP.2: Vehiculele",
"CAP.3: Conducatorii de vehicule",
"CAP.4: Semnalizarea rutiera",
"CAP.5: Reguli de circulatie",
"CAP.6: Infractiuni si pedepse",
"CAP.7: Raspunderea contraventionala",
"CAP.8: Cai de atac impotriva procesului-verbal de constatare a contraventiei",
"CAP.9: Atributii ale unor ministere si ale altor autoritati ale administratiei publice",
"CAP.10: Dispozitii finale"};
/** Called when the activity is first created. */
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.legislatie);
lv1=(ListView)findViewById(R.id.listView1);
// By using setAdpater method in listview we an add string array in list.
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
final TextView mTextView = (TextView)view;
switch (position) {
case 0:
Intent newActivity0 = new Intent(Cod_rutier.this, Legislatie1.class);
startActivity(newActivity0);
break;
case 1:
Intent newActivity1 = new Intent(Cod_rutier.this, Legislatie2.class);
startActivity(newActivity1);
break;
case 2 :
Intent newActivity2 = new Intent(Cod_rutier.this, Legislatie3.class);
startActivity(newActivity2);
break;
case 3:
Intent newActivity3 = new Intent(Cod_rutier.this, Legislatie4.class);
startActivity(newActivity3);
break;
default:
}
}
});
}}
i put it into the manifest file but when i run it the app stops. This is my logcat
03-16 18:58:35.373: E/AndroidRuntime(828): FATAL EXCEPTION: main
03-16 18:58:35.373: E/AndroidRuntime(828): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.vreaucarnet/com.example.vreaucarnet.Cod_rutier}: android.util.AndroidRuntimeException: requestFeature() must be called before adding content
03-16 18:58:35.373: E/AndroidRuntime(828): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
03-16 18:58:35.373: E/AndroidRuntime(828): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-16 18:58:35.373: E/AndroidRuntime(828): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-16 18:58:35.373: E/AndroidRuntime(828): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-16 18:58:35.373: E/AndroidRuntime(828): at android.os.Handler.dispatchMessage(Handler.java:99)
03-16 18:58:35.373: E/AndroidRuntime(828): at android.os.Looper.loop(Looper.java:123)
03-16 18:58:35.373: E/AndroidRuntime(828): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-16 18:58:35.373: E/AndroidRuntime(828): at java.lang.reflect.Method.invokeNative(Native Method)
03-16 18:58:35.373: E/AndroidRuntime(828): at java.lang.reflect.Method.invoke(Method.java:521)
03-16 18:58:35.373: E/AndroidRuntime(828): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-16 18:58:35.373: E/AndroidRuntime(828): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-16 18:58:35.373: E/AndroidRuntime(828): at dalvik.system.NativeStart.main(Native Method)
03-16 18:58:35.373: E/AndroidRuntime(828): Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content
03-16 18:58:35.373: E/AndroidRuntime(828): at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:172)
03-16 18:58:35.373: E/AndroidRuntime(828): at android.app.Activity.requestWindowFeature(Activity.java:2719)
03-16 18:58:35.373: E/AndroidRuntime(828): at com.example.vreaucarnet.Cod_rutier.onCreate(Cod_rutier.java:33)
03-16 18:58:35.373: E/AndroidRuntime(828): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-16 18:58:35.373: E/AndroidRuntime(828): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
03-16 18:58:35.373: E/AndroidRuntime(828): ... 11 more
Can someone tell my where is my mistake?
Requesting any requestWindowFeature calls are done before super.onCreate calls in your activity
i.e
requestWindowFeature(Window.FEATURE_NO_TITLE); this should be called before super.onCreate()
change like
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
It is here:
Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content

FATAL EXCEPTION: main on Android 4.x but not Android 2.X

I am getting some errors when trying to run my android app on an emulator that is running any version of Android 4.x but it works fine on any version of Android 2.X.
package com.EXCLUDED_FOR_PRIVACY.EXCLUDED_FOR_PRIVACY;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.ImageView;
import android.graphics.Color;
public class EXCLUDED_FOR_PRIVACY extends Activity {
public int WebView1Bool=0;
public int WebView2Bool=0;
public int WebView3Bool=0;
public int WebView4Bool=0;
private TabHost tabs;
private void setupTabHost() {
tabs = (TabHost) findViewById(R.id.my_tabhost);
tabs.setup();
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupTabHost();
tabs.getTabWidget().setDividerDrawable(R.drawable.tab_divider);
setupTab(new ImageView(this), 1);
setupTab(new ImageView(this), 2);
setupTab(new ImageView(this), 3);
setupTab(new ImageView(this), 4);
WebView mWebView1;
mWebView1 = (WebView) findViewById(R.id.webview1);
mWebView1.setBackgroundColor(Color.parseColor("#a3a3a3"));
mWebView1.setBackgroundColor(0);
mWebView1.getSettings().setJavaScriptEnabled(true);
mWebView1.setWebViewClient(new MobileClient());
mWebView1.loadUrl("EXCLUDED_FOR_PRIVACY");
WebView1Bool=1;
tabs.getTabWidget().getChildAt(0).setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
tabs.setCurrentTab(0);
if(WebView1Bool==0){
WebView mWebView1;
mWebView1 = (WebView) findViewById(R.id.webview1);
mWebView1.setBackgroundColor(Color.parseColor("#a3a3a3"));
mWebView1.setBackgroundColor(0);
mWebView1.getSettings().setJavaScriptEnabled(true);
mWebView1.setWebViewClient(new MobileClient());
mWebView1.loadUrl("EXCLUDED_FOR_PRIVACY");
WebView1Bool=1;
}
}
});
tabs.getTabWidget().getChildAt(2).setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
tabs.setCurrentTab(1);
if(WebView2Bool==0){
WebView mWebView2;
mWebView2 = (WebView) findViewById(R.id.webview2);
mWebView2.setBackgroundColor(Color.parseColor("#a3a3a3"));
mWebView2.setBackgroundColor(0);
mWebView2.getSettings().setJavaScriptEnabled(true);
mWebView2.setWebViewClient(new MobileClient());
mWebView2.loadUrl("EXCLUDED_FOR_PRIVACY");
WebView2Bool=1;
}
}
});
tabs.getTabWidget().getChildAt(4).setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
tabs.setCurrentTab(2);
if(WebView3Bool==0){
WebView mWebView3 = (WebView) findViewById(R.id.webview3);
mWebView3.setBackgroundColor(Color.parseColor("#a3a3a3"));
mWebView3.setBackgroundColor(0);
mWebView3.getSettings().setJavaScriptEnabled(true);
mWebView3.setWebViewClient(new MobileClient());
mWebView3.loadUrl("EXCLUDED_FOR_PRIVACY");
WebView3Bool=1;
}
}
});
tabs.getTabWidget().getChildAt(6).setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
tabs.setCurrentTab(3);
if(WebView4Bool==0){
WebView mWebView4;
mWebView4 = (WebView) findViewById(R.id.webview4);
mWebView4.setBackgroundColor(Color.parseColor("#a3a3a3"));
mWebView4.setBackgroundColor(0);
mWebView4.getSettings().setJavaScriptEnabled(true);
mWebView4.setWebViewClient(new MobileClient());
mWebView4.loadUrl("EXCLUDED_FOR_PRIVACY");
WebView4Bool=1;
}
}
});
}
private class MobileClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
private void setupTab(final View view, final int i) {
View createTabView_view = LayoutInflater.from(tabs.getContext()).inflate(R.layout.tabs_bg, null);
ImageView createTabView_tv = (ImageView) createTabView_view.findViewById(R.id.tabsImage);
if(i==1){
TabSpec tabSpec = tabs.newTabSpec("EXCLUDED_FOR_PRIVACY");
createTabView_tv.setImageResource(R.drawable.ic_discounts);
tabSpec.setIndicator(createTabView_view);
tabSpec.setContent(R.id.webview1);
tabs.addTab(tabSpec);
} else if(i==2){
TabSpec tabSpec = tabs.newTabSpec("EXCLUDED_FOR_PRIVACY");
createTabView_tv.setImageResource(R.drawable.ic_specials);
tabSpec.setIndicator(createTabView_view);
tabSpec.setContent(R.id.webview2);
tabs.addTab(tabSpec);
} else if(i==3){
TabSpec tabSpec = tabs.newTabSpec("EXCLUDED_FOR_PRIVACY");
createTabView_tv.setImageResource(R.drawable.ic_directory);
tabSpec.setIndicator(createTabView_view);
tabSpec.setContent(R.id.webview3);
tabs.addTab(tabSpec);
} else if(i==4){
TabSpec tabSpec = tabs.newTabSpec("EXCLUDED_FOR_PRIVACY");
createTabView_tv.setImageResource(R.drawable.ic_membership);
tabSpec.setIndicator(createTabView_view);
tabSpec.setContent(R.id.webview4);
tabs.addTab(tabSpec);
}
}
}
Here are the errors I am seeing
09-24 13:11:25.329: E/Trace(1151): error opening trace file: No such file or directory (2)
09-24 13:11:25.539: D/dalvikvm(1151): GC_FOR_ALLOC freed 43K, 4% free 8316K/8583K, paused 42ms, total 45ms
09-24 13:11:25.549: I/dalvikvm-heap(1151): Grow heap (frag case) to 8.829MB for 691216-byte allocation
09-24 13:11:25.669: D/dalvikvm(1151): GC_CONCURRENT freed <1K, 4% free 8990K/9287K, paused 75ms+6ms, total 124ms
09-24 13:11:25.829: D/gralloc_goldfish(1151): Emulator without GPU emulation detected.
09-24 13:11:26.209: I/Choreographer(1151): Skipped 42 frames! The application may be doing too much work on its main thread.
09-24 13:11:26.379: I/Choreographer(1151): Skipped 44 frames! The application may be doing too much work on its main thread.
09-24 13:11:27.509: I/Choreographer(1151): Skipped 54 frames! The application may be doing too much work on its main thread.
09-24 13:11:28.319: D/AndroidRuntime(1151): Shutting down VM
09-24 13:11:28.319: W/dalvikvm(1151): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
09-24 13:11:28.379: E/AndroidRuntime(1151): FATAL EXCEPTION: main
09-24 13:11:28.379: E/AndroidRuntime(1151): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.EXCLUDED.EXCLUDED/com.EXCLUDED.EXCLUDED.EXCLUDED}: java.lang.NullPointerException
09-24 13:11:28.379: E/AndroidRuntime(1151): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
09-24 13:11:28.379: E/AndroidRuntime(1151): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
09-24 13:11:28.379: E/AndroidRuntime(1151): at android.app.ActivityThread.access$600(ActivityThread.java:130)
09-24 13:11:28.379: E/AndroidRuntime(1151): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
09-24 13:11:28.379: E/AndroidRuntime(1151): at android.os.Handler.dispatchMessage(Handler.java:99)
09-24 13:11:28.379: E/AndroidRuntime(1151): at android.os.Looper.loop(Looper.java:137)
09-24 13:11:28.379: E/AndroidRuntime(1151): at android.app.ActivityThread.main(ActivityThread.java:4745)
09-24 13:11:28.379: E/AndroidRuntime(1151): at java.lang.reflect.Method.invokeNative(Native Method)
09-24 13:11:28.379: E/AndroidRuntime(1151): at java.lang.reflect.Method.invoke(Method.java:511)
09-24 13:11:28.379: E/AndroidRuntime(1151): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
09-24 13:11:28.379: E/AndroidRuntime(1151): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-24 13:11:28.379: E/AndroidRuntime(1151): at dalvik.system.NativeStart.main(Native Method)
09-24 13:11:28.379: E/AndroidRuntime(1151): Caused by: java.lang.NullPointerException
09-24 13:11:28.379: E/AndroidRuntime(1151): at com.EXCLUDED.EXCLUDED.EXCLUDED.onCreate(EXCLUDED.java:85)
09-24 13:11:28.379: E/AndroidRuntime(1151): at android.app.Activity.performCreate(Activity.java:5008)
09-24 13:11:28.379: E/AndroidRuntime(1151): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
09-24 13:11:28.379: E/AndroidRuntime(1151): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
09-24 13:11:28.379: E/AndroidRuntime(1151): ... 11 more
09-24 13:11:30.289: I/Process(1151): Sending signal. PID: 1151 SIG: 9
I apologize if this is something really simple that any java developer would know, I have to admit I barely know what I am doing in Java but am under the gun to get this built. Thank you very much for any help.
Get rid of all the tabs.getTabWidget().getChildAt(...).setOnClickListener() crap, replacing it with a single TabHost.OnTabChangeListener that you register with your TabHost, to find out when the user changes tabs. Your existing code assumes a particular internal structure of a TabWidget, and that assumption is unreliable, as you are discovering.

Categories