How to change Pin Number using sharedpreferences in Android? - java

I'm having implement android demo for application pin using shared preferences which i enter pin and confirm the pin.The problem is that when I am accessing this values, it is not returning updated values, it gives me NullPointerException.
String strGetPin;
public final String pref_filename = "settings";
String myPassword;
static SharedPreferences shaedPref;
public static String strdataReturned = "";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_list);
activity = this;
edtxt_EnterPin = (EditText) findViewById(R.id.edtxt_Pin);
edtxt_NewPin = (EditText) findViewById(R.id.edtxt_NewPin);
edtxt_ConfirmPin = (EditText) findViewById(R.id.edtxt_ConfirmPin);
shaedPref = getSharedPreferences(pref_filename, 0);
strdataReturned = shaedPref.getString("user", "");
if (strdataReturned.equals("")) {
SharedPreferences.Editor editor = shaedPref.edit();
editor.putString("user", "1234"); // newData is new pass,passwordKey is key
editor.commit();
}
btnChangePin = (Button) findViewById(R.id.btn_ChangePin);
btnChangePin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
myDialog = new Dialog(Settings_Activity.this);
myDialog.setContentView(R.layout.pin_change);
myDialog.setTitle("Application PIN Change");
myDialog.setCancelable(false);
//Button For Change Pin save
Button btnChange = (Button) myDialog.findViewById(R.id.btn_Save);
btnChange.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String stringData = edtxt_EnterPin.getText().toString().trim();
strdataReturned = shaedPref.getString("user", ""); // key/def message
// if stored password is equal to entered password
if (strdataReturned.equals(stringData)) {
String newData = edtxt_NewPin.getText().toString().trim();
SharedPreferences.Editor editor = shaedPref.edit();
editor.putString("user", newData); // newData is new pass, passwordKey is key
editor.commit();
Toast.makeText(getApplicationContext(), "PIN Change successfully", Toast.LENGTH_LONG).show();
edtxt_EnterPin.setText("");
edtxt_NewPin.setText("");
} else {
Toast.makeText(getApplicationContext(), "Wrong Pin!", Toast.LENGTH_LONG).show();
edtxt_EnterPin.setText("");
edtxt_NewPin.setText("");
}
}
});
Button btnCancel = (Button) myDialog.findViewById(R.id.btn_Cancel);
btnCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
myDialog.dismiss();
}
});
myDialog.show();
}
});
}
Logcat:
04-09 18:42:12.694: D/(29235): onClick: Stoping Service
04-09 18:42:12.781: E/(29235): Service Stopped
04-09 18:42:19.861: D/dalvikvm(29235): GREF has increased to 201
04-09 18:42:50.712: D/AndroidRuntime(29235): Shutting down VM
04-09 18:42:50.712: W/dalvikvm(29235): threadid=1: thread exiting with uncaught exception (group=0x40015560)
04-09 18:42:50.721: E/AndroidRuntime(29235): FATAL EXCEPTION: main
04-09 18:42:50.721: E/AndroidRuntime(29235): java.lang.NullPointerException
04-09 18:42:50.721: E/AndroidRuntime(29235): at com.sms_alert.Settings_Activity$1$1.onClick(Settings_Activity.java:95)
04-09 18:42:50.721: E/AndroidRuntime(29235): at android.view.View.performClick(View.java:2485)
04-09 18:42:50.721: E/AndroidRuntime(29235): at android.view.View$PerformClick.run(View.java:9080)
04-09 18:42:50.721: E/AndroidRuntime(29235): at android.os.Handler.handleCallback(Handler.java:587)
04-09 18:42:50.721: E/AndroidRuntime(29235): at android.os.Handler.dispatchMessage(Handler.java:92)
04-09 18:42:50.721: E/AndroidRuntime(29235): at android.os.Looper.loop(Looper.java:123)
04-09 18:42:50.721: E/AndroidRuntime(29235): at android.app.ActivityThread.main(ActivityThread.java:3683)
04-09 18:42:50.721: E/AndroidRuntime(29235): at java.lang.reflect.Method.invokeNative(Native Method)
04-09 18:42:50.721: E/AndroidRuntime(29235): at java.lang.reflect.Method.invoke(Method.java:507)
04-09 18:42:50.721: E/AndroidRuntime(29235): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-09 18:42:50.721: E/AndroidRuntime(29235): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-09 18:42:50.721: E/AndroidRuntime(29235): at dalvik.system.NativeStart.main(Native Method)
04-09 18:42:53.932: I/Process(29235): Sending signal. PID: 29235 SIG: 9

Try clearing the SharedPreferences before writing to it.
editor.clear();

Related

java.lang.NullPointerException error help me [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
it's my logCat.
04-09 09:11:18.178: E/AndroidRuntime(829): FATAL EXCEPTION: main
04-09 09:11:18.178: E/AndroidRuntime(829): java.lang.NullPointerException
04-09 09:11:18.178: E/AndroidRuntime(829): at com.example.androidresim.Activitygiris.onLoadScene(Activitygiris.java:84)
04-09 09:11:18.178: E/AndroidRuntime(829): at org.anddev.andengine.ui.activity.BaseGameActivity.doResume(BaseGameActivity.java:158)
04-09 09:11:18.178: E/AndroidRuntime(829): at org.anddev.andengine.ui.activity.BaseGameActivity.onWindowFocusChanged(BaseGameActivity.java:82)
04-09 09:11:18.178: E/AndroidRuntime(829): at com.android.internal.policy.impl.PhoneWindow$DecorView.onWindowFocusChanged(PhoneWindow.java:2462)
04-09 09:11:18.178: E/AndroidRuntime(829): at android.view.View.dispatchWindowFocusChanged(View.java:7578)
04-09 09:11:18.178: E/AndroidRuntime(829): at android.view.ViewGroup.dispatchWindowFocusChanged(ViewGroup.java:962)
04-09 09:11:18.178: E/AndroidRuntime(829): at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:3115)
04-09 09:11:18.178: E/AndroidRuntime(829): at android.os.Handler.dispatchMessage(Handler.java:99)
04-09 09:11:18.178: E/AndroidRuntime(829): at android.os.Looper.loop(Looper.java:137)
04-09 09:11:18.178: E/AndroidRuntime(829): at android.app.ActivityThread.main(ActivityThread.java:5103)
04-09 09:11:18.178: E/AndroidRuntime(829): at java.lang.reflect.Method.invokeNative(Native Method)
04-09 09:11:18.178: E/AndroidRuntime(829): at java.lang.reflect.Method.invoke(Method.java:525)
04-09 09:11:18.178: E/AndroidRuntime(829): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
04-09 09:11:18.178: E/AndroidRuntime(829): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-09 09:11:18.178: E/AndroidRuntime(829): at dalvik.system.NativeStart.main(Native Method)
and it's my class.
public class Activitygiris extends BaseGameActivity {
private static final int CAMERA_WIDTH=800;
private static final int CAMERA_HEIGHT=480;
private Camera camera;
private Engine engine;
Scene sahne;
private Texture texSaha,texOyuncu1,texOyuncu2,texRedWins,texBlueWins;
private TextureRegion texRegSaha,texRegOyuncu1,texRegOyuncu2,texRegRedWins,texRegBlueWins;
private Sprite spriteSaha,spriteOyuncu1,spriteOyuncu2,spriteRedWins,spriteBlueWins;
private TimerHandler timerBeklet;
#Override
public Engine onLoadEngine() {
// TODO Auto-generated method stub
camera= new Camera(0,0,CAMERA_WIDTH,CAMERA_HEIGHT);
final EngineOptions engineoptions = new EngineOptions(true,ScreenOrientation.LANDSCAPE,new FillResolutionPolicy(),camera);
engineoptions.getTouchOptions().setRunOnUpdateThread(true);
engine = new Engine(engineoptions);
return engine;
}
#Override
public void onLoadResources() {
// TODO Auto-generated method stub
texSaha=new Texture(1024,512,TextureOptions.BILINEAR_PREMULTIPLYALPHA);
texOyuncu1 = new Texture(128,128,TextureOptions.BILINEAR_PREMULTIPLYALPHA);
texOyuncu2 = new Texture(128,128,TextureOptions.BILINEAR_PREMULTIPLYALPHA);
texRedWins = new Texture(64,256,TextureOptions.BILINEAR_PREMULTIPLYALPHA);
texBlueWins = new Texture(64,256,TextureOptions.BILINEAR_PREMULTIPLYALPHA);
texRegSaha = TextureRegionFactory.createFromAsset(texSaha, this, "gfx/Arkaplan.jpg",0,0);
texRegOyuncu1 = TextureRegionFactory.createFromAsset(texOyuncu1, this, "gfx/kol1.png",0,0);
texRegOyuncu2 = TextureRegionFactory.createFromAsset(texOyuncu2, this, "gfx/kol2.png",0,0);
texRegBlueWins = TextureRegionFactory.createFromAsset(texBlueWins, this, "gfx/bluewins.png",0,0);
texRegRedWins = TextureRegionFactory.createFromAsset(texRedWins, this, "gfx/redwins.png",0,0);
Texture [] textures = {texSaha,texOyuncu1,texOyuncu2,texBlueWins,texRedWins };
mEngine.getTextureManager().loadTextures(textures);
}
#Override
public Scene onLoadScene() {
// TODO Auto-generated method stub
this.engine.registerUpdateHandler(new FPSLogger());
this.sahne=new Scene();
spriteSaha = new Sprite(0, 0, texRegSaha);
spriteOyuncu1 = new Sprite(600, CAMERA_HEIGHT/2-64, texRegOyuncu1);
spriteOyuncu2 = new Sprite(50, CAMERA_HEIGHT/2-64, texRegOyuncu2);
spriteRedWins = new Sprite(CAMERA_HEIGHT-128,CAMERA_HEIGHT/2-128,texRegRedWins);
spriteRedWins = new Sprite(CAMERA_HEIGHT+32,CAMERA_HEIGHT/2-128,texRegBlueWins.clone());
spriteBlueWins.setVisible(false);
mEngine.registerUpdateHandler(timerBeklet = new TimerHandler(3, false,new ITimerCallback() {
#Override
public void onTimePassed(TimerHandler pTimerHandler) {
// TODO Auto-generated method stub
spriteRedWins.setRotation(180);
mEngine.registerUpdateHandler(timerBeklet= new TimerHandler(3,false, new ITimerCallback() {
#Override
public void onTimePassed(TimerHandler pTimerHandler) {
// TODO Auto-generated method stub
spriteBlueWins.setVisible(true);
spriteRedWins.setVisible(false);
}
}));
}
}));
this.sahne.attachChild(spriteSaha);
this.sahne.attachChild(spriteOyuncu1);
this.sahne.attachChild(spriteOyuncu2);
this.sahne.attachChild(spriteBlueWins);
this.sahne.attachChild(spriteRedWins);
return this.sahne;
}
#Override
public void onLoadComplete() {
// TODO Auto-generated method stub
}
}
Help me, please..
You get a nullPointerException because the reference variable spriteBlueWin is referencing null.
You are not initializing the spriteBlueWins, you should initialize it as you did with the others.
As pointed by #Dirk Lachowski, you probably copied and pasted the spriteRedWins and forgot to replace it to spriteBlueWins:
spriteSaha = new Sprite(0, 0, texRegSaha);
spriteOyuncu1 = new Sprite(600, CAMERA_HEIGHT/2-64, texRegOyuncu1);
spriteOyuncu2 = new Sprite(50, CAMERA_HEIGHT/2-64, texRegOyuncu2);
spriteRedWins = new Sprite(CAMERA_HEIGHT-128,CAMERA_HEIGHT/2-128,texRegRedWins);
spriteRedWins = new Sprite(CAMERA_HEIGHT+32,CAMERA_HEIGHT/2-128,texRegBlueWins.clone());
The last line should be:
spriteBlueWins = new Sprite(CAMERA_HEIGHT+32,CAMERA_HEIGHT/2-128,texRegBlueWins.clone());

Start activity from service isn't working (Android)

I created an overlay "always on top button", which is a service HUD, and I can't start an activity screen from there, it gives the error: "Unfortunately App has stopped". In the beginning, all I used to know if there was any TouchEventwas a toast, and that toast was created, but it was created several times, so I don't know if it gives that error because this code, which is on TouchEvent body , is repeated several times too.
here is my code:
public class HUD extends Service implements OnClickListener, OnTouchListener, OnLongClickListener {
Button mButton;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
//mView = new HUDView(this);
mButton = new Button(this);
mButton.setId(1);
mButton.setText("Button");
mButton.setClickable(true);
mButton.setOnTouchListener(this);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.OPAQUE);
params.gravity = Gravity.LEFT | Gravity.TOP;
params.setTitle("Load Average");
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.addView(mButton, params);
}
#Override
public void onDestroy() {
super.onDestroy();
if(mButton != null)
{
((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(mButton);
mButton = null;
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getX()<mButton.getWidth() & event.getY()>0)
{
Toast.makeText(this,"Overlay button event", Toast.LENGTH_SHORT).show(); //this my toast
Intent i = new Intent(); //this is my new acivity (intent)
i.setClass(HUD.this, screen.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
HUD.this.stopSelf();
}
return false;
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(this,"Click", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
System.exit(1);
return false;
}
}
So my question is, is this code on TouchEvent body being repeated several times? If it is, is that the cause of the error?
log cat:
07-20 22:11:06.962: I/Choreographer(1620): Skipped 52 frames! The application may be doing too much work on its main thread.
07-20 22:11:08.062: D/AndroidRuntime(1620): Shutting down VM
07-20 22:11:08.062: W/dalvikvm(1620): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
07-20 22:11:08.132: E/AndroidRuntime(1620): FATAL EXCEPTION: main
07-20 22:11:08.132: E/AndroidRuntime(1620): android.app.SuperNotCalledException: Activity {com.example.screenshot/com.example.screenshot.screen} did not call through to super.onCreate()
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2146)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.os.Handler.dispatchMessage(Handler.java:99)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.os.Looper.loop(Looper.java:137)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-20 22:11:08.132: E/AndroidRuntime(1620): at java.lang.reflect.Method.invokeNative(Native Method)
07-20 22:11:08.132: E/AndroidRuntime(1620): at java.lang.reflect.Method.invoke(Method.java:511)
07-20 22:11:08.132: E/AndroidRuntime(1620): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-20 22:11:08.132: E/AndroidRuntime(1620): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-20 22:11:08.132: E/AndroidRuntime(1620): at dalvik.system.NativeStart.main(Native Method)
screen.java:
public class screen extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
Toast.makeText(getApplicationContext(), "Made it", 0).show();
finish();
}
}
See android start activity from service
Intent i= new Intent(getBaseContext(), screen.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(i);
You error seems to be inside screen activity. There are many thread which might help to figure out the error that you are getting for the activity:
Error in Android "SuperNotCalledException:Activity did not call through to super.OnCreate()"
android.app.SuperNotCalledException: Activity did not call through to super.onStop()
Update
The error is because you haven't called: super.onCreate(savedInstanceState); in your screen activity's onCreate(). That should be the first thing to be called in onCreate(). Do something like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//.... other stuff
}
Hope this helps.

insert spinner value in mysql db via soap ws in android

Hi i have to develop the app is insert the database from spinner in mysql database via soap webserices in android application...
i have use below webservice code:
public class Insertion {
public String insertData(String userName,String userPassword){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/androidlogin","root","");
PreparedStatement statement = con.prepareStatement("INSERT INTO user(status) VALUES ('"+userName+"');");
int result = statement.executeUpdate();
}
catch(Exception exc){
System.out.println(exc.getMessage());
}
return "Insertion successfull!!";
}
}
i have use below code for android spinner example:
public class InsertionExample extends Activity{
private final String NAMESPACE = "http://xcart.com";
private final String URL = "http://192.168.1.168:8085/XcartLogin/services/Insertion?wsdl";
private final String SOAP_ACTION = "http://xcart.com/insertData";
private final String METHOD_NAME = "insertData";
Button btninsert;
private Spinner spnMusketeers;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btninsert = (Button)findViewById(R.id.btn_insert);
btninsert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
insertValues();
}
});
}
public void insertValues(){
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
Spinner userName = (Spinner) findViewById(R.id.spnMusketeers);
List<String> lsMusketeers = new ArrayList<String>();
lsMusketeers.add("Q");
lsMusketeers.add("P");
lsMusketeers.add("C");
ArrayAdapter<String> aspnMusketeers =
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
lsMusketeers);
aspnMusketeers.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
spnMusketeers.setAdapter(aspnMusketeers);
// Set up a callback for the spinner
spnMusketeers.setOnItemSelectedListener(
new OnItemSelectedListener() {
public void onNothingSelected(AdapterView<?> arg0) { }
public void onItemSelected(AdapterView<?> parent, View v,
int position, long id) {
// Code that does something when the Spinner value changes
}
});
String user_Name = userName.getContext().toString();
//Pass value for userName variable of the web service
PropertyInfo unameProp =new PropertyInfo();
unameProp.setName("userName");//Define the variable name in the web service method
unameProp.setValue(user_Name);//Define value for fname variable
unameProp.setType(String.class);//Define the type of the variable
request.addProperty(unameProp);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try{
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
TextView result = (TextView) findViewById(R.id.textView2);
result.setText(response.toString());
}
catch(Exception e){
}
// Code that does something when the Spinner value changes
}
}
Here how is change my code for this question.
my logcat window says:
08-23 02:48:40.030: D/AndroidRuntime(4055): Shutting down VM
08-23 02:48:40.030: W/dalvikvm(4055): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
08-23 02:48:40.060: E/AndroidRuntime(4055): FATAL EXCEPTION: main
08-23 02:48:40.060: E/AndroidRuntime(4055): java.lang.NullPointerException
08-23 02:48:40.060: E/AndroidRuntime(4055): at com.android.soap.InsertionExample.insertValues(InsertionExample.java:63)
08-23 02:48:40.060: E/AndroidRuntime(4055): at com.android.soap.InsertionExample$1.onClick(InsertionExample.java:43)
08-23 02:48:40.060: E/AndroidRuntime(4055): at android.view.View.performClick(View.java:2408)
08-23 02:48:40.060: E/AndroidRuntime(4055): at android.view.View$PerformClick.run(View.java:8816)
08-23 02:48:40.060: E/AndroidRuntime(4055): at android.os.Handler.handleCallback(Handler.java:587)
08-23 02:48:40.060: E/AndroidRuntime(4055): at android.os.Handler.dispatchMessage(Handler.java:92)
08-23 02:48:40.060: E/AndroidRuntime(4055): at android.os.Looper.loop(Looper.java:123)
08-23 02:48:40.060: E/AndroidRuntime(4055): at android.app.ActivityThread.main(ActivityThread.java:4627)
08-23 02:48:40.060: E/AndroidRuntime(4055): at java.lang.reflect.Method.invokeNative(Native Method)
08-23 02:48:40.060: E/AndroidRuntime(4055): at java.lang.reflect.Method.invoke(Method.java:521)
08-23 02:48:40.060: E/AndroidRuntime(4055): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-23 02:48:40.060: E/AndroidRuntime(4055): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-23 02:48:40.060: E/AndroidRuntime(4055): at dalvik.system.NativeStart.main(Native Method)
please help me....what error is occurred here.give me solution...
use this code for this insert function:
String selectedItem = parent.getItemAtPosition(pos).toString();

App Crashes on Launch, Trying to see if file exist's for login screen

I'm creating a Class that checks to see if the file has been created (Has username and passwords.) and if it does it creates an intent to go to another class to read the data and check it againts a server via FTP. For some reason, I can't get it to work, I've tried everything and read every single web page I could, but no luck.
My Code:
public class LogIn extends Activity implements OnClickListener {
Button send;
EditText user;
EditText pass;
CheckBox staySignedIn;
FileOutputStream Fos;
String a;
String b;
String string = a;
String string2 = b;
String FILENAME = "userandpass";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
send = (Button) findViewById(R.id.bLogIn);
user = (EditText) findViewById(R.id.eTuser);
pass = (EditText) findViewById(R.id.eTpassword);
staySignedIn = (CheckBox) findViewById(R.id.Cbstay);
send.setOnClickListener(this);
if (staySignedIn.isChecked()) {
String a = user.getText().toString();
String b = pass.getText().toString();
File f = new File(FILENAME);
try {
Fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
Fos.write(string.getBytes());
Fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File file = getBaseContext().getFileStreamPath(FILENAME);
if(file.exists());
Intent i = new Intent(LogIn.this, ChatService.class);
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bLogIn:
if (pass.length() == 0)
Toast.makeText(this,
"Try to type in your username and password again!",
Toast.LENGTH_LONG).show();
else if (user.length() == 0)
Toast.makeText(this,
"Try to type in your username and password again!",
Toast.LENGTH_LONG).show();
else {
String u = user.getText().toString();
String p = pass.getText().toString();
Bundle send = new Bundle();
send.putString("key", u);
send.putString("key1", p);
Intent a = new Intent(LogIn.this, logincheck.class);
a.putExtra("key", u);
a.putExtra("key1", p);
startActivity(a);
Toast.makeText(this, "Were signing you in!", Toast.LENGTH_LONG)
.show();
break;
}
}
}
}
LogCat:
01-19 11:37:17.601: W/dalvikvm(4411): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
01-19 11:37:17.621: E/AndroidRuntime(4411): FATAL EXCEPTION: main
01-19 11:37:17.621: E/AndroidRuntime(4411): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gta5news.bananaphone/com.gta5news.bananaphone.LogIn}: java.lang.NullPointerException
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.os.Handler.dispatchMessage(Handler.java:99)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.os.Looper.loop(Looper.java:123)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-19 11:37:17.621: E/AndroidRuntime(4411): at java.lang.reflect.Method.invokeNative(Native Method)
01-19 11:37:17.621: E/AndroidRuntime(4411): at java.lang.reflect.Method.invoke(Method.java:521)
01-19 11:37:17.621: E/AndroidRuntime(4411): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-19 11:37:17.621: E/AndroidRuntime(4411): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-19 11:37:17.621: E/AndroidRuntime(4411):
at dalvik.system.NativeStart.main(Native Method)
01-19 11:37:17.621: E/AndroidRuntime(4411): Caused by: java.lang.NullPointerException
01-19 11:37:17.621: E/AndroidRuntime(4411): at com.gta5news.bananaphone.LogIn.onCreate(LogIn.java:55)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
If line 55 is
Fos.write(string.getBytes());
then either Fos or string is uninitialized. Given that string is initialized to a which is itself uninitialized, that explains it. You need to assign a proper value to string.
Fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
It seems for some reason openFileOutput returning null which makes Fos null, which is throwing NullPointerException.
Add
if(Fos != null) {
Fos.write(string.getBytes());
Fos.close();
} check.
OR catch NullpointerException.

Code keeps thowing a NPE, cannot find the cause

i cannot find the null pointer exception in my code, i was wondering if anyone could help me find what is giving an error.
code:
package com.dingle.ubat;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.Display;
import android.view.MotionEvent;
import android.widget.Toast;
public class UltraBrightAndroidTorchActivity extends Activity {
/** Called when the activity is first created. */
PowerManager pm;
PowerManager.WakeLock wl;
public boolean flash = false;
public boolean enableFlash = false;
public boolean dimDisplay = false;
Display display = getWindowManager().getDefaultDisplay();
public int windowWidth = display.getWidth();
public int windowHeight = display.getHeight();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
flash = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(flash == true && enableFlash == true){
try {
DroidLED led = new DroidLED();
led.enable(!led.isEnabled());
}
catch(Exception e) {
Toast.makeText(this, "Error interacting with LED.", Toast.LENGTH_SHORT).show();
throw new RuntimeException(e);
} }
wl.acquire();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
//int tx = (int) event.getRawX();
int ty = (int) event.getRawY();
if (ty <= (windowHeight/2)){
dimDisplay = !dimDisplay;
}
if (ty >= (windowHeight/2)){
enableFlash = !enableFlash;
}
return super.onTouchEvent(event);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
wl.release();
}
#Override
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
super.onNewIntent(intent);
wl.release();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
wl.release();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
wl.release();
}
}
Error list:
12-10 20:40:42.224: W/dalvikvm(274): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
12-10 20:40:42.232: E/AndroidRuntime(274): Uncaught handler: thread main exiting due to uncaught exception
12-10 20:40:42.282: E/AndroidRuntime(274): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.dingle.ubat/com.dingle.ubat.UltraBrightAndroidTorchActivity}: java.lang.NullPointerException
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.os.Handler.dispatchMessage(Handler.java:99)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.os.Looper.loop(Looper.java:123)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.main(ActivityThread.java:4363)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.reflect.Method.invokeNative(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.reflect.Method.invoke(Method.java:521)
12-10 20:40:42.282: E/AndroidRuntime(274): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
12-10 20:40:42.282: E/AndroidRuntime(274): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
12-10 20:40:42.282: E/AndroidRuntime(274): at dalvik.system.NativeStart.main(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): Caused by: java.lang.NullPointerException
12-10 20:40:42.282: E/AndroidRuntime(274): at com.dingle.ubat.UltraBrightAndroidTorchActivity.<init>(UltraBrightAndroidTorchActivity.java:20)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.Class.newInstanceImpl(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.Class.newInstance(Class.java:1479)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)
12-10 20:40:42.282: E/AndroidRuntime(274): ... 11 more
any help and criticism is greatly appreciated
code is being compiled for android 2.1. code is a basic, crappily coded torch app.
thanx
The code is bailing out on one of these two lines:
Display display = getWindowManager().getDefaultDisplay();
public int windowWidth = display.getWidth();
Either getWindowManager() is returning a null and that first initializer will fail, or getDefaultDisplay() is, and the second one will.
You should probably move these initializations to the onCreate handler. Having them at instance initialization sounds a bit risky - the activity's "environment" might not be completely set up yet at that point.
(And check the return values.)
Activity is full available only after it has been created. This line does not do the intended purpose:
 Display display = getWindowManager().getDefaultDisplay();
Move this line and subsequent ones inside onCreate method.

Categories

Resources