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?
Related
after taking a photo, my photo display in activity, but when i check into folder, the size from my photo is 0kb, i have no idea why this happen, and when i take a photo again, the new photo not save in the folder that i wanted, this is my code :
{
File sdCard= Environment.getExternalStorageDirectory();
File path = new File (sdCard.getAbsolutePath() + "/android/data/spaj_foto");
path.mkdir();
File file= new File (path,"spaj_foto.png");
outputFileUri = Uri.fromFile(file);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri );
startActivityForResult(cameraIntent,TAKE_PHOTO_CODE );
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == TAKE_PHOTO_CODE) {
Bundle extras = data.getExtras();
Bitmap photo = (Bitmap) extras.get("data");
image_spaj.setImageBitmap(photo);
}
else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
}
}
}
EDIT
this is my logcat :
09-26 17:57:38.072: E/AndroidRuntime(12498): FATAL EXCEPTION: main
09-26 17:57:38.072: E/AndroidRuntime(12498): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=null} to activity {org.example.touch/org.example.touch.FormSpaj}: java.lang.NullPointerException
09-26 17:57:38.072: E/AndroidRuntime(12498): at android.app.ActivityThread.deliverResults(ActivityThread.java:3179)
09-26 17:57:38.072: E/AndroidRuntime(12498): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3222)
09-26 17:57:38.072: E/AndroidRuntime(12498): at android.app.ActivityThread.access$1100(ActivityThread.java:140)
09-26 17:57:38.072: E/AndroidRuntime(12498): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1276)
09-26 17:57:38.072: E/AndroidRuntime(12498): at android.os.Handler.dispatchMessage(Handler.java:99)
09-26 17:57:38.072: E/AndroidRuntime(12498): at android.os.Looper.loop(Looper.java:137)
09-26 17:57:38.072: E/AndroidRuntime(12498): at android.app.ActivityThread.main(ActivityThread.java:4895)
09-26 17:57:38.072: E/AndroidRuntime(12498): at java.lang.reflect.Method.invokeNative(Native Method)
09-26 17:57:38.072: E/AndroidRuntime(12498): at java.lang.reflect.Method.invoke(Method.java:511)
09-26 17:57:38.072: E/AndroidRuntime(12498): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
09-26 17:57:38.072: E/AndroidRuntime(12498): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
09-26 17:57:38.072: E/AndroidRuntime(12498): at dalvik.system.NativeStart.main(Native Method)
09-26 17:57:38.072: E/AndroidRuntime(12498): Caused by: java.lang.NullPointerException
09-26 17:57:38.072: E/AndroidRuntime(12498): at org.example.touch.FormSpaj.onActivityResult(FormSpaj.java:990)
09-26 17:57:38.072: E/AndroidRuntime(12498): at android.app.Activity.dispatchActivityResult(Activity.java:5347)
09-26 17:57:38.072: E/AndroidRuntime(12498): at android.app.ActivityThread.deliverResults(ActivityThread.java:3175)
09-26 17:57:38.072: E/AndroidRuntime(12498): ... 11 more
You have created a new file. (blank)
And then started a camera intent.
But what you have not done, is told the camera intent where to save the image.
Thus, leaving you with a blank file.
File file= new File (path,"spaj_foto.png");
outputFileUri = Uri.fromFile(file);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri );
startActivityForResult(cameraIntent,TAKE_PHOTO_CODE );
Note, you do Not need to create the file, android camera intent will do that for you.
What you do need to do is pass the extra, so the intent knows where to save.
(you do still need to create the directory)
I have an app that's supposed to get some string from a server depending on the webpage, and it crashes every time I run it. I don't understand how to even debug it, and I've tried numerous changes. It started crashing ever since I messed with the GUI, and added the ability to switch views if that provides any sort of help.
Here is the code:
public class MainActivity extends Activity implements TextToSpeech.OnInitListener, OnClickListener{
private WebView mWebview;
EditText addressBar;
String currentWebpage = "http://www.aljazeera.com/news/americas/2013/07/20137113200544375.html";
LinearLayout viewGroup = (LinearLayout) findViewById(R.id.linearview);
View main = (View) findViewById(R.layout.activity_main);
View readOut = (View) findViewById(R.layout.read_out);
#Override
public void onCreate(Bundle savedInstanceState) {
System.out.println("Showing Activity_Main...");
viewGroup.addView(View.inflate(this, R.layout.activity_main, null));
super.onCreate(savedInstanceState);
//setContentView(R.menu.main);
addressBar = (EditText)findViewById(R.id.addressBar);
addressBar.setText(currentWebpage);
mWebview = (WebView)findViewById(R.id.webview);
mWebview.getSettings().setJavaScriptEnabled(true); // enables javascript
mWebview.setWebViewClient(new WebViewClient());
System.out.println("Loading Webpage...");
mWebview.loadUrl(currentWebpage);
}
public void speakOut(String text) {
TextToSpeech tts = new TextToSpeech(this, this);
System.out.println("Speaking");
if(tts.isLanguageAvailable(Locale.ENGLISH) != -1){
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
public int speakFull(String text){
switchToRead();
String[] sentences = text.split("\n|\\.(?!\\d)|(?<!\\d)\\."); // Regex that splits the body of text into the sentences of that body which are stored in a String array.
for(int i = 0; i < sentences.length; i++){
speakOut(sentences[i]);
if(i == sentences.length - 1){
return 1;
}
}
return 0;
}
public String getText(String webPage) throws ParseException, IOException{
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://someserver.net:8080/" + webPage));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String responseBody = "No text found on webpage.";
int responseCode = response.getStatusLine().getStatusCode();
switch(responseCode) {
case 200:
HttpEntity entity = response.getEntity();
if(entity != null) {
responseBody = EntityUtils.toString(entity);
}
}
System.out.println("Returning Response..");
System.out.println(responseBody);
return responseBody;
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
}
private class tts extends AsyncTask<String, Void, String>{//Async http request to get text
#Override
protected String doInBackground(String... arg0) {
try {
System.out.println("Running seperate thread for TTS.");
int complete = 0;
while(complete == 0){
System.out.println("Speaking full..");
complete = speakFull(getText(mWebview.getUrl()));
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result){
}
}
public void clickPlay(View v){
new tts().execute("");
}
public void clickGo(View v){
if(addressBar.getText() != null){
currentWebpage = addressBar.getText().toString();
System.out.println("Current webpage changed to: " + currentWebpage);
mWebview.loadUrl(currentWebpage);
}
}
public void clickPause(View v){
System.out.println("Clicked pause.");
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
public void switchToRead(){// Switches to the reading view which displays the text that the tts engine reads off.
System.out.println("Swtiching view to Read.");
viewGroup.removeView(main);
viewGroup.addView(View.inflate(this, R.layout.read_out, null));
}
public void switchToMain(){
System.out.println("Switching view to Main.");
viewGroup.removeView(readOut);
viewGroup.addView(View.inflate(this, R.layout.activity_main, null));
}
}
Also here are the numerous errors I encounter when launching my app:
08-01 14:53:10.210: E/Trace(812): error opening trace file: No such file or directory (2)
08-01 14:53:10.600: D/AndroidRuntime(812): Shutting down VM
08-01 14:53:10.631: W/dalvikvm(812): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
08-01 14:53:10.660: E/AndroidRuntime(812): FATAL EXCEPTION: main
08-01 14:53:10.660: E/AndroidRuntime(812): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.webview/com.example.webview.MainActivity}: java.lang.NullPointerException
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.os.Looper.loop(Looper.java:137)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-01 14:53:10.660: E/AndroidRuntime(812): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 14:53:10.660: E/AndroidRuntime(812): at java.lang.reflect.Method.invoke(Method.java:511)
08-01 14:53:10.660: E/AndroidRuntime(812): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-01 14:53:10.660: E/AndroidRuntime(812): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-01 14:53:10.660: E/AndroidRuntime(812): at dalvik.system.NativeStart.main(Native Method)
08-01 14:53:10.660: E/AndroidRuntime(812): Caused by: java.lang.NullPointerException
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.Activity.findViewById(Activity.java:1839)
08-01 14:53:10.660: E/AndroidRuntime(812): at com.example.webview.MainActivity.<init>(MainActivity.java:39)
08-01 14:53:10.660: E/AndroidRuntime(812): at java.lang.Class.newInstanceImpl(Native Method)
08-01 14:53:10.660: E/AndroidRuntime(812): at java.lang.Class.newInstance(Class.java:1319)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
08-01 14:53:10.660: E/AndroidRuntime(812): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
08-01 14:53:10.660: E/AndroidRuntime(812): ... 11 more
08-01 14:53:27.439: D/AndroidRuntime(860): Shutting down VM
08-01 14:53:27.439: W/dalvikvm(860): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
08-01 14:53:27.449: E/AndroidRuntime(860): FATAL EXCEPTION: main
08-01 14:53:27.449: E/AndroidRuntime(860): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.webview/com.example.webview.MainActivity}: java.lang.NullPointerException
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.os.Looper.loop(Looper.java:137)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-01 14:53:27.449: E/AndroidRuntime(860): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 14:53:27.449: E/AndroidRuntime(860): at java.lang.reflect.Method.invoke(Method.java:511)
08-01 14:53:27.449: E/AndroidRuntime(860): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-01 14:53:27.449: E/AndroidRuntime(860): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-01 14:53:27.449: E/AndroidRuntime(860): at dalvik.system.NativeStart.main(Native Method)
08-01 14:53:27.449: E/AndroidRuntime(860): Caused by: java.lang.NullPointerException
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.Activity.findViewById(Activity.java:1839)
08-01 14:53:27.449: E/AndroidRuntime(860): at com.example.webview.MainActivity.<init>(MainActivity.java:39)
08-01 14:53:27.449: E/AndroidRuntime(860): at java.lang.Class.newInstanceImpl(Native Method)
08-01 14:53:27.449: E/AndroidRuntime(860): at java.lang.Class.newInstance(Class.java:1319)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
08-01 14:53:27.449: E/AndroidRuntime(860): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
08-01 14:53:27.449: E/AndroidRuntime(860): ... 11 more
Move your view initialization inside onCreate after setContentView
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
LinearLayout viewGroup = (LinearLayout) findViewById(R.id.linearview);
...// rest of the code
I have been working on an app to use a phone's/tablet's camera flash as a flashlight. Everything seemed to be working fine but when I tested it on my Droid Bionic running Android 4.1.2, the app failed to turn on the flash even though it said it did. Here is the java code I used:
package com.example.flash;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private boolean isFlashOn = false;
private Camera camera;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.buttonFlashlight);
Context context = this;
PackageManager pm = context.getPackageManager();
if(!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Log.e("err", "Device has no camera!");
Toast.makeText(getApplicationContext(),
"Your device doesn't have camera!",Toast.LENGTH_SHORT).show();
return;
}
camera = Camera.open();
final Parameters p = camera.getParameters();
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (isFlashOn) {
Log.i("info", "torch is turned off!");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
isFlashOn = false;
button.setText("Tap to turn flashlight on.");
}
else {
Log.i("info", "torch is turned on!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
isFlashOn = true;
button.setText("Tap to turn flashlight off.");
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
}
}}
Is this code correct or did I miss something?
Logcat:
07-03 18:48:29.064: E/Trace(773): error opening trace file: No such file or directory (2)
07-03 18:48:30.535: D/Camera(773): app passed NULL surface
07-03 18:48:31.023: D/libEGL(773): loaded /system/lib/egl/libEGL_emulation.so
07-03 18:48:31.073: D/(773): HostConnection::get() New Host Connection established 0x2a13c3c0, tid 773
07-03 18:48:31.123: D/libEGL(773): loaded /system/lib/egl/libGLESv1_CM_emulation.so
07-03 18:48:31.173: D/libEGL(773): loaded /system/lib/egl/libGLESv2_emulation.so
07-03 18:48:31.406: W/EGL_emulation(773): eglSurfaceAttrib not implemented
07-03 18:48:31.433: D/OpenGLRenderer(773): Enabling debug mode 0
07-03 18:48:31.723: I/Choreographer(773): Skipped 58 frames! The application may be doing too much work on its main thread.
07-03 18:49:05.923: D/dalvikvm(773): GC_CONCURRENT freed 202K, 12% free 2623K/2956K, paused 74ms+25ms, total 234ms
07-03 18:49:06.216: W/EGL_emulation(773): eglSurfaceAttrib not implemented
07-03 18:49:09.584: D/Camera(773): app passed NULL surface
07-03 18:49:09.853: W/EGL_emulation(773): eglSurfaceAttrib not implemented
07-03 18:49:11.813: I/info(773): torch is turned on!
07-03 18:49:13.467: I/info(773): torch is turned off!
07-03 18:49:16.263: W/EGL_emulation(773): eglSurfaceAttrib not implemented
07-03 18:49:16.713: D/AndroidRuntime(773): Shutting down VM
07-03 18:49:16.713: W/dalvikvm(773): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
07-03 18:49:16.936: E/AndroidRuntime(773): FATAL EXCEPTION: main
07-03 18:49:16.936: E/AndroidRuntime(773): java.lang.RuntimeException: Method called after release()
07-03 18:49:16.936: E/AndroidRuntime(773): at android.hardware.Camera._stopPreview(Native Method)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.hardware.Camera.stopPreview(Camera.java:543)
07-03 18:49:16.936: E/AndroidRuntime(773): at com.example.flash.MainActivity.surfaceDestroyed(MainActivity.java:140)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.SurfaceView.updateWindow(SurfaceView.java:553)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:231)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.View.dispatchWindowVisibilityChanged(View.java:7544)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1039)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1039)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1039)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1039)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1211)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.Choreographer.doCallbacks(Choreographer.java:562)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.Choreographer.doFrame(Choreographer.java:532)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.os.Handler.handleCallback(Handler.java:725)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.os.Handler.dispatchMessage(Handler.java:92)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.os.Looper.loop(Looper.java:137)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-03 18:49:16.936: E/AndroidRuntime(773): at java.lang.reflect.Method.invokeNative(Native Method)
07-03 18:49:16.936: E/AndroidRuntime(773): at java.lang.reflect.Method.invoke(Method.java:511)
07-03 18:49:16.936: E/AndroidRuntime(773): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-03 18:49:16.936: E/AndroidRuntime(773): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-03 18:49:16.936: E/AndroidRuntime(773): at dalvik.system.NativeStart.main(Native Method)
07-03 18:49:24.854: E/Trace(811): error opening trace file: No such file or directory (2)
07-03 18:49:25.413: D/libEGL(811): loaded /system/lib/egl/libEGL_emulation.so
07-03 18:49:25.567: D/(811): HostConnection::get() New Host Connection established 0x2a15f570, tid 811
07-03 18:49:25.643: D/libEGL(811): loaded /system/lib/egl/libGLESv1_CM_emulation.so
07-03 18:49:25.663: D/libEGL(811): loaded /system/lib/egl/libGLESv2_emulation.so
07-03 18:49:25.934: W/EGL_emulation(811): eglSurfaceAttrib not implemented
07-03 18:49:25.963: D/OpenGLRenderer(811): Enabling debug mode 0
07-03 18:53:12.298: D/Camera(811): app passed NULL surface
07-03 18:53:12.723: D/dalvikvm(811): GC_CONCURRENT freed 172K, 11% free 2600K/2904K, paused 9ms+165ms, total 421ms
07-03 18:53:12.934: E/EGL_emulation(811): rcCreateWindowSurface returned 0
07-03 18:53:12.934: E/EGL_emulation(811): tid 811: eglCreateWindowSurface(631): error 0x3003 (EGL_BAD_ALLOC)
07-03 18:53:12.943: D/AndroidRuntime(811): Shutting down VM
07-03 18:53:12.943: W/dalvikvm(811): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
07-03 18:53:13.033: E/AndroidRuntime(811): FATAL EXCEPTION: main
07-03 18:53:13.033: E/AndroidRuntime(811): java.lang.RuntimeException: createWindowSurface failed EGL_BAD_ALLOC
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.HardwareRenderer$GlRenderer.createSurface(HardwareRenderer.java:1064)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.HardwareRenderer$GlRenderer.createEglSurface(HardwareRenderer.java:961)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.HardwareRenderer$GlRenderer.initialize(HardwareRenderer.java:787)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1502)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.Choreographer.doCallbacks(Choreographer.java:562)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.Choreographer.doFrame(Choreographer.java:532)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.os.Handler.handleCallback(Handler.java:725)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.os.Handler.dispatchMessage(Handler.java:92)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.os.Looper.loop(Looper.java:137)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-03 18:53:13.033: E/AndroidRuntime(811): at java.lang.reflect.Method.invokeNative(Native Method)
07-03 18:53:13.033: E/AndroidRuntime(811): at java.lang.reflect.Method.invoke(Method.java:511)
07-03 18:53:13.033: E/AndroidRuntime(811): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-03 18:53:13.033: E/AndroidRuntime(811): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-03 18:53:13.033: E/AndroidRuntime(811): at dalvik.system.NativeStart.main(Native Method)
UPDATE
I think the key is you are running Android 4.1.2. Since Android 4.0, if you want to use the Camera Device, even if you only want to use the flash, you are forced to use a SurfaceView.
In the previous answer (below), I gave you a link to a Torch app which uses SurfaceView. Try it or adapt it to your code.
PREVIOUS ANSWER:
As stated in many other cases (like this one), you may be facing a Device-Specific issue that is quite common in the Android world.
Although getSupportedFlashModes() may return FLASH_MODE_TORCH on nearly every device, many of them don't actually support it.
Anyway, you could try these:
Use camera.startPreview(); after camera = Camera.open();
Try setting FLASH_MODE_OFF initially (before camera.startPreview();).
Check if this Torch app works in your device. In case it does, you have the source code to compare it to yours.
Download a Torch app from the Play Store to test if it's a device issue or not.
Post the issue in a Droid Bionic support forum.
UPDATE: I would say the final keyword is a problem in your code. Try changing it to:
//camera = Camera.open();
//final Parameters p = camera.getParameters();
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (isFlashOn) {
Log.i("info", "torch is turned off!");
cam.stopPreview();
cam.release();
isFlashOn = false;
button.setText("Tap to turn flashlight on.");
}
else {
Log.i("info", "torch is turned on!");
camera = Camera.open();
Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.startPreview();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
isFlashOn = true;
button.setText("Tap to turn flashlight off.");
}
}
});
user the permission "android.permission.FLASHLIGHT" in the manifest
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.CAMERA" />
When I try to run this line in order to hide the keyboard (I get the InputMethodManager):
this.context = context;
InputMethodManager mgr = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); //this line crashes the app
What should I do to fix it?
(I am running it from a fragment by the way)
Crash Log:
11-03 16:20:26.700: D/AndroidRuntime(2809): Shutting down VM
11-03 16:20:26.700: W/dalvikvm(2809): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
11-03 16:20:26.710: E/AndroidRuntime(2809): FATAL EXCEPTION: main
11-03 16:20:26.710: E/AndroidRuntime(2809): java.lang.NullPointerException
11-03 16:20:26.710: E/AndroidRuntime(2809): at co.emuze.tabtest1.Tab1$1.onClick(Tab1.java:32)
11-03 16:20:26.710: E/AndroidRuntime(2809): at android.view.View.performClick(View.java:4084)
11-03 16:20:26.710: E/AndroidRuntime(2809): at android.view.View$PerformClick.run(View.java:16966)
11-03 16:20:26.710: E/AndroidRuntime(2809): at android.os.Handler.handleCallback(Handler.java:615)
11-03 16:20:26.710: E/AndroidRuntime(2809): at android.os.Handler.dispatchMessage(Handler.java:92)
11-03 16:20:26.710: E/AndroidRuntime(2809): at android.os.Looper.loop(Looper.java:137)
11-03 16:20:26.710: E/AndroidRuntime(2809): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-03 16:20:26.710: E/AndroidRuntime(2809): at java.lang.reflect.Method.invokeNative(Native Method)
11-03 16:20:26.710: E/AndroidRuntime(2809): at java.lang.reflect.Method.invoke(Method.java:511)
11-03 16:20:26.710: E/AndroidRuntime(2809): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-03 16:20:26.710: E/AndroidRuntime(2809): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-03 16:20:26.710: E/AndroidRuntime(2809): at dalvik.system.NativeStart.main(Native Method)
Full on click method:
public void onClick(View v) {
text1.setText(editText1.getText().toString());
InputMethodManager mgr = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(editText1.getWindowToken(), 0);
}
It would appear context is null - you show the line this.context = context, and if the right hand side context is not a variable local to that method you're doing nothing. I think what you may be looking for is context = getApplicationContext()
Dont forget to use try catch blog because in case when your keyboard not open and if you use key key board hide code app crashed
User below code in Fragment
try {
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
} catch (Exception e) {
// TODO: handle exception
}
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.