This code I am working on requires the user to press a button after entering a phone number into a text box. The button is made to save the number.
When I run the code I want to have it present the user with an alert dialog asking them to enter a number if they pressed the button with no number present.
Instead of getting the alert dialog the app crashes. But with a number entered the app works just fine.
Any advice on this would be awesome - Here is the code with the stack trace under that.
-Thank you!
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Create an if statement that brings up an alert dialog if there is no number entered into the field.
switch (v.getId()) {
case R.id.btnwidgetconfig: {
if (sharedData == null)
{
AlertDialog.Builder alert = new AlertDialog.Builder(c);
alert.setTitle("No number entered");
alert.setMessage("Please enter a phone number using the the text box");
alert.setCancelable(false);
alert.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivityForResult(
new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
0);
}
});
}
else
{
String stringData = sharedData.getText().toString();
Long l = Long.parseLong(stringData);
SharedPreferences.Editor editor = prefs.edit();
prefs.edit().putLong(constants.KEY, l).commit();
Toast.makeText(c, "Your number has been saved!",
Toast.LENGTH_LONG).show();
svNum.setText("Saved Number: " + prefs.getLong(constants.KEY, 411));
break;
}
}
}
}
});
////Stack Trace:
05-14 12:29:07.679: W/dalvikvm(30842): threadid=1: thread exiting with uncaught exception (group=0x40018560)
05-14 12:29:07.679: E/AndroidRuntime(30842): FATAL EXCEPTION: main
05-14 12:29:07.679: E/AndroidRuntime(30842): java.lang.NumberFormatException:
05-14 12:29:07.679: E/AndroidRuntime(30842): at java.lang.Long.parseLong(Long.java:337)
05-14 12:29:07.679: E/AndroidRuntime(30842): at java.lang.Long.parseLong(Long.java:311)
05-14 12:29:07.679: E/AndroidRuntime(30842): at example.save.phonenum.Settings$1.onClick(WWSettings.java:106)
05-14 12:29:07.679: E/AndroidRuntime(30842): at android.view.View.performClick(View.java:2485)
05-14 12:29:07.679: E/AndroidRuntime(30842): at android.view.View$PerformClick.run(View.java:9080)
05-14 12:29:07.679: E/AndroidRuntime(30842): at android.os.Handler.handleCallback(Handler.java:587)
05-14 12:29:07.679: E/AndroidRuntime(30842): at android.os.Handler.dispatchMessage(Handler.java:92)
05-14 12:29:07.679: E/AndroidRuntime(30842): at android.os.Looper.loop(Looper.java:130)
05-14 12:29:07.679: E/AndroidRuntime(30842): at android.app.ActivityThread.main(ActivityThread.java:3683)
05-14 12:29:07.679: E/AndroidRuntime(30842): at java.lang.reflect.Method.invokeNative(Native Method)
05-14 12:29:07.679: E/AndroidRuntime(30842): at java.lang.reflect.Method.invoke(Method.java:507)
05-14 12:29:07.679: E/AndroidRuntime(30842): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
05-14 12:29:07.679: E/AndroidRuntime(30842): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
05-14 12:29:07.679: E/AndroidRuntime(30842): at dalvik.system.NativeStart.main(Native Method)
05-14 12:29:15.569: W/IInputConnectionWrapper(30870): showStatusIcon on inactive InputConnection
I'm guessing this sharedData is a TextView. Which you are still trying to parse the result when it is null, hence the NFE. Put in a check to only run that code if there is a valid number. You are checking if it is null, which the TextView may not be but the contents are an empty String which you are trying to parse
Change
if (sharedData == null)
to something like
if (sharedData == null || sharedData.getText().toString().equals(""))
{
...
I would try to get the text before that line into your stringData variable then check if that is empty. Also, you will want to put a try/catch around the parsing code in case they try to enter a non-digit and display a message, unless you've already done that
Related
I got problem with my first Android application. Just after running, my app crashes in emulator with "Unfortunately has stopped." message. I checked many threads on Stack and I read pretty much of official documentation and I really do not know what's a cause...
I use AVD with Android 4.4.2, API Level 19. CPU/ABI - ARM. Use Host GPU - checked (without this one emulator works very slowly).
My app should play a song after pressing the button. I would be really grateful for any ideas. Cheers.
Java file:
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.os.Build;
import android.media.MediaPlayer;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
Button one = (Button) findViewById(R.id.button1);
final MediaPlayer mediaPlayer1 = MediaPlayer.create(this, R.raw.elements6);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer1.start();
}
});
}
#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
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
And XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
Errors:
05-14 17:29:21.740: D/AndroidRuntime(1145): Shutting down VM
05-14 17:29:21.740: W/dalvikvm(1145): threadid=1: thread exiting with uncaught exception (group=0xb2abcba8)
05-14 17:29:21.750: E/AndroidRuntime(1145): FATAL EXCEPTION: main
05-14 17:29:21.750: E/AndroidRuntime(1145): Process: com.example.beatzlooper, PID: 1145
05-14 17:29:21.750: E/AndroidRuntime(1145): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.beatzlooper/com.example.beatzlooper.MainActivity}: java.lang.NullPointerException
05-14 17:29:21.750: E/AndroidRuntime(1145): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
05-14 17:29:21.750: E/AndroidRuntime(1145): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-14 17:29:21.750: E/AndroidRuntime(1145): at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-14 17:29:21.750: E/AndroidRuntime(1145): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-14 17:29:21.750: E/AndroidRuntime(1145): at android.os.Handler.dispatchMessage(Handler.java:102)
05-14 17:29:21.750: E/AndroidRuntime(1145): at android.os.Looper.loop(Looper.java:136)
05-14 17:29:21.750: E/AndroidRuntime(1145): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-14 17:29:21.750: E/AndroidRuntime(1145): at java.lang.reflect.Method.invokeNative(Native Method)
05-14 17:29:21.750: E/AndroidRuntime(1145): at java.lang.reflect.Method.invoke(Method.java:515)
05-14 17:29:21.750: E/AndroidRuntime(1145): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-14 17:29:21.750: E/AndroidRuntime(1145): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-14 17:29:21.750: E/AndroidRuntime(1145): at dalvik.system.NativeStart.main(Native Method)
05-14 17:29:21.750: E/AndroidRuntime(1145): Caused by: java.lang.NullPointerException
05-14 17:29:21.750: E/AndroidRuntime(1145): at com.example.beatzlooper.MainActivity.onCreate(MainActivity.java:31)
05-14 17:29:21.750: E/AndroidRuntime(1145): at android.app.Activity.performCreate(Activity.java:5231)
05-14 17:29:21.750: E/AndroidRuntime(1145): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-14 17:29:21.750: E/AndroidRuntime(1145): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-14 17:29:21.750: E/AndroidRuntime(1145): ... 11 more
You are working with fragments.
The Fragment cannot be added to the R.id.container View because it doesn't exists.
Just delete the whole if-clause in the onCreate() and also delete the Placeholder Class you don't need it actually.
Comment this code
/*if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}*/
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.
I try to change 3 textviews in a class called UserProfile() calling the method update() from the class UpdateProfile(), the class UserProfile do something like this:
package com.safm;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class UserProfile extends Activity {
TextView username, usersurname, useremail;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
username = (TextView) findViewById(R.id.username);
usersurname = (TextView) findViewById(R.id.usersurname);
useremail = (TextView) findViewById(R.id.useremail);
}
public void updateButton(View view){
Intent i = new Intent(this, UpdateProfile.class);
startActivity(i);
}
public void update(String nname, String nusername, String nemail){
System.out.println("2");
System.out.println(nname);
username.setText(nname);
usersurname.setText(nusername);
useremail.setText(nemail);
System.out.println("3");
}
}
The updateButton method invoke the UpdateProfile class:
package com.safm;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class UpdateProfile extends Activity {
EditText newusernametxt, newsurnametxt, newemailtxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_actualizarperfil);
newusernametxt = (EditText) findViewById(R.id.newusernametxt);
newsurnametxt = (EditText) findViewById(R.id.newsurnametxt );
newemailtxt = (EditText) findViewById(R.id.newemailtxt );
}
public void updateInfo(View view){
String nname = newusernametxt .getText().toString();
String nsurname = newsurnametxt .getText().toString();
String nemail = newemailtxt .getText().toString();
if(nname.compareTo("") != 0 && nsurname.compareTo("") != 0 && nemail.compareTo("") != 0){
UserProfile profile = new UserProfile();
System.out.println("1");
profile.update(nname, nsurname, nemail);
System.out.println("4");
Toast.makeText(this, "Success, the profile has been updated", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "You can't empty fields", Toast.LENGTH_SHORT).show();
}
}
This is my logcat file, as you can see, the first 2 flags are printed correctly, the error is when I try to set another text on the TextView, but the value of the strings (nname, nsurname and nemail) are not empty cause also is printed in the console HELP!
05-14 21:43:31.140: I/System.out(878): 1
05-14 21:43:31.140: I/System.out(878): 2
05-14 21:43:31.150: I/System.out(878): TextEditValue
05-14 21:43:31.150: D/AndroidRuntime(878): Shutting down VM
05-14 21:43:31.150: W/dalvikvm(878): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
05-14 21:43:31.310: E/AndroidRuntime(878): FATAL EXCEPTION: main
05-14 21:43:31.310: E/AndroidRuntime(878): java.lang.IllegalStateException: Could not execute method of the activity
05-14 21:43:31.310: E/AndroidRuntime(878): at android.view.View$1.onClick(View.java:3599)
05-14 21:43:31.310: E/AndroidRuntime(878): at android.view.View.performClick(View.java:4204)
05-14 21:43:31.310: E/AndroidRuntime(878): at android.view.View$PerformClick.run(View.java:17355)
05-14 21:43:31.310: E/AndroidRuntime(878): at android.os.Handler.handleCallback(Handler.java:725)
05-14 21:43:31.310: E/AndroidRuntime(878): at android.os.Handler.dispatchMessage(Handler.java:92)
05-14 21:43:31.310: E/AndroidRuntime(878): at android.os.Looper.loop(Looper.java:137)
05-14 21:43:31.310: E/AndroidRuntime(878): at android.app.ActivityThread.main(ActivityThread.java:5041)
05-14 21:43:31.310: E/AndroidRuntime(878): at java.lang.reflect.Method.invokeNative(Native Method)
05-14 21:43:31.310: E/AndroidRuntime(878): at java.lang.reflect.Method.invoke(Method.java:511)
05-14 21:43:31.310: E/AndroidRuntime(878): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-14 21:43:31.310: E/AndroidRuntime(878): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-14 21:43:31.310: E/AndroidRuntime(878): at dalvik.system.NativeStart.main(Native Method)
05-14 21:43:31.310: E/AndroidRuntime(878): Caused by: java.lang.reflect.InvocationTargetException
05-14 21:43:31.310: E/AndroidRuntime(878): at java.lang.reflect.Method.invokeNative(Native Method)
05-14 21:43:31.310: E/AndroidRuntime(878): at java.lang.reflect.Method.invoke(Method.java:511)
05-14 21:43:31.310: E/AndroidRuntime(878): at android.view.View$1.onClick(View.java:3594)
05-14 21:43:31.310: E/AndroidRuntime(878): ... 11 more
05-14 21:43:31.310: E/AndroidRuntime(878): Caused by: java.lang.NullPointerException
05-14 21:43:31.310: E/AndroidRuntime(878): at com.safm.UserProfile.update(UserProfile.java:31)
05-14 21:43:31.310: E/AndroidRuntime(878): at com.safm.UserProfile.updateInfo(UpdateProfile.java:33)
05-14 21:43:31.310: E/AndroidRuntime(878): ... 14 more
NOTE: I've clean the project and defined the TextView in ProfileUser class and the TextEdit in UpdateProfile outside the onCreate method but doesn't work.
Thanks.
Activities in Android are separate containers, that are in no way allowed to directly touch eachother. This is because the application stack behind Android 'freezes' the activities when they are no longer on the foreground, and could even be swapped to hard storage to save on RAM at the operating system's discretion.
Your UserProfile encapsulation should just reload its data after the UpdateProfile activity is closed, or request communication back the proper way via startActivityForResult.
Your current implementation is technically incorrect from each perspective, since you're hardcoding the UpdateProfile activity to always be called from a UserProfile activity. What if some day you introduce a new menu option to call it directly from the home screen? Activities are always separate, and should not make such assumptions.
I want to stop a running thread while click on the splash screen, if I don't click on screen, after the thread execution, it will launch another Activity. But getting UnSupportedException, how do I solve it?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
iImage = (ImageView) findViewById(R.id.iIcon);
splashImage = (ImageView) findViewById(R.id.splash_image);
iImage.setOnClickListener(this);
splashImage.setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
splashTimer = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
startActivity(new Intent(SplashActivity.this, LoginAuthenticationActivity.class));
finish();
}
});
splashTimer.start();
}
#Override
public void onClick(View view) {
if(splashTimer.isAlive())
splashTimer.stop();
switch (view.getId()) {
case R.id.iIcon:
startActivity(new Intent(this, AboutUsActivity.class));
break;
case R.id.splash_image:
startActivity(new Intent(this, LoginAuthenticationActivity.class));
break;
default:
break;
}
finish();
}
Log:
01-27 03:27:01.189: W/dalvikvm(1080): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
01-27 03:27:01.209: E/AndroidRuntime(1080): FATAL EXCEPTION: main
01-27 03:27:01.209: E/AndroidRuntime(1080): java.lang.UnsupportedOperationException
01-27 03:27:01.209: E/AndroidRuntime(1080): at java.lang.Thread.stop(Thread.java:1076)
01-27 03:27:01.209: E/AndroidRuntime(1080): at java.lang.Thread.stop(Thread.java:1063)
01-27 03:27:01.209: E/AndroidRuntime(1080): at com.app.wooqer.SplashActivity.onClick(SplashActivity.java:48)
01-27 03:27:01.209: E/AndroidRuntime(1080): at android.view.View.performClick(View.java:3511)
01-27 03:27:01.209: E/AndroidRuntime(1080): at android.view.View$PerformClick.run(View.java:14105)
01-27 03:27:01.209: E/AndroidRuntime(1080): at android.os.Handler.handleCallback(Handler.java:605)
01-27 03:27:01.209: E/AndroidRuntime(1080): at android.os.Handler.dispatchMessage(Handler.java:92)
01-27 03:27:01.209: E/AndroidRuntime(1080): at android.os.Looper.loop(Looper.java:137)
01-27 03:27:01.209: E/AndroidRuntime(1080): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-27 03:27:01.209: E/AndroidRuntime(1080): at java.lang.reflect.Method.invokeNative(Native Method)
01-27 03:27:01.209: E/AndroidRuntime(1080): at java.lang.reflect.Method.invoke(Method.java:511)
01-27 03:27:01.209: E/AndroidRuntime(1080): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-27 03:27:01.209: E/AndroidRuntime(1080): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-27 03:27:01.209: E/AndroidRuntime(1080): at dalvik.system.NativeStart.main(Native Method)
What you're doing is very wasteful (any splash screen is wasteful, but using Threads like this is more so), but to fix your issue:
use interrrupt(); intead of stop();
As the docs say for stop()
Throws UnsupportedOperationException.
And to fix the duplicate issue, move the startActivity() inside the try so it looks like this:
public void run() {
try {
Thread.sleep(5000);
startActivity(new Intent(SplashActivity.this, LoginAuthenticationActivity.class));
} catch (InterruptedException e) {
e.printStackTrace();
}
finish();
}
That way when you call interrupt() all your Activity does is finish() and the duplicate startActivity() is not called.
To further explain:
Very first issue: stop() throws an exception by default, since it's an unsafe method which you're not supposed to use.
Then when you used interrupt(), you had startActivity() in the run method after the catch block. When you interrupted, startActivity() was called once in run() and once in onClick(). By moving startActivity() inside the try block to right after Thread.sleep(), when interrupt() interrupts the Thread, the rest of the try block isn't executed. This means that you now only have one startActivity() call instead of two. For more information, read up on exceptions.
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.