NullPointerException error. I cannot seem to spot the issue - java

Logcat error message.
I receive this error when I attempt to register an account on the application, the app crashes momentarily and returns to the login page.
02-14 13:11:19.857 31983-31983/example.com.androidim E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: example.com.androidim, PID: 31983
java.lang.NullPointerException
at example.com.androidim.SignUp$2$1$1.run(SignUp.java:126)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606
at dalvik.system.NativeStart.main(Native Method)
The following is line 111-142 in the SignUp activity.
if (passwordText.getText().toString().equals(passwordAgainText.getText().toString())){
if (usernameText.length() >= 5 && passwordText.length() >= 5) {
Thread thread = new Thread(){
String result = new String();
#Override
public void run() {
result = imService.signUpUser(usernameText.getText().toString(),
passwordText.getText().toString(),
eMailText.getText().toString());
handler.post(new Runnable(){
public void run() {
if (result.equals(SERVER_RES_RES_SIGN_UP_SUCCESFULL)) {
Toast.makeText(getApplicationContext(),R.string.signup_successfull, Toast.LENGTH_LONG).show();
showDialog(SIGN_UP_SUCCESSFULL);
}
else if (result.equals(SERVER_RES_SIGN_UP_USERNAME_CRASHED)){
Toast.makeText(getApplicationContext(),R.string.signup_username_crashed, Toast.LENGTH_LONG).show();
showDialog(SIGN_UP_USERNAME_CRASHED);
}
else //if (result.equals(SERVER_RES_SIGN_UP_FAILED))
{
Toast.makeText(getApplicationContext(),R.string.signup_failed, Toast.LENGTH_LONG).show();
showDialog(SIGN_UP_FAILED);
}
}
});
}

When calling equals on your result variable, result is null. You have to do a null-check before calling equals.
public void run() {
if(result != null){
if (result.equals(SERVER_RES_RES_SIGN_UP_SUCCESFULL)) {
Toast.makeText(getApplicationContext(),R.string.signup_successfull, Toast.LENGTH_LONG).show();
showDialog(SIGN_UP_SUCCESSFULL);
}
else if (result.equals(SERVER_RES_SIGN_UP_USERNAME_CRASHED)){
Toast.makeText(getApplicationContext(),R.string.signup_username_crashed, Toast.LENGTH_LONG).show();
showDialog(SIGN_UP_USERNAME_CRASHED);
}
else //if (result.equals(SERVER_RES_SIGN_UP_FAILED))
{
Toast.makeText(getApplicationContext(),R.string.signup_failed, Toast.LENGTH_LONG).show();
showDialog(SIGN_UP_FAILED);
}else{
//result == null
}
}
}

Related

The api isApiSupported return true but SipManager newInstance still return null in Android native Sip

I used Android native Sip api to initialize Sip client.Because I am confused to Sip protocol,I read the android developer document about sip and follow it.When I run my application on Nexus5,it work normally,but when I run it on other device like coolpad, it throw NullPointException from SipManager.The following is my code.For some reason,the username,passwd and domain is private.
public static SipManager manager;
public static SipProfile me;
public static String username;
public static String passwd;
public static void initializeSip(Context context) {
System.out.println("initializeSip");
if (manager == null) {
manager = SipManager.newInstance(context);
}
if (me != null) {
closeLocalProfile();
}
username = SharedPreferences.getLoginInfo().getModel().getVos_phone();
passwd = SharedPreferences.getLoginInfo().getModel().getVos_phone_pwd();
try {
if (!(SipManager.isApiSupported(context) && SipManager.isVoipSupported(context))) {
System.out.println("cannot support");
return;
}
System.out.println("isApiSupported="+SipManager.isApiSupported(context));
System.out.println("SipManager="+SipManager.newInstance(context));
SipProfile.Builder builder = new SipProfile.Builder(username, domain);
builder.setPassword(passwd);
me = builder.build();
manager.open(me);
SipRegistrationListener listener = new SipRegistrationListener() {
#Override
public void onRegistering(String localProfileUri) {
System.out.println("Registering with SIP Server");
}
#Override
public void onRegistrationDone(String localProfileUri, long expiryTime) {
System.out.println("Register success");
}
#Override
public void onRegistrationFailed(String localProfileUri, int errorCode, String errorMessage) {
System.out.println("Registeration failed.Please check Settings.");
System.out.println("errorCode="+errorCode);
System.out.println("errorMessage="+errorMessage);
}
};
manager.setRegistrationListener(me.getUriString(),listener);
manager.register(me,3000,listener);
} catch (ParseException e) {
e.printStackTrace();
} catch (SipException e) {
e.printStackTrace();
}
}
The following is my logcat. Most strangely,I find that the api isApiSupported return true and the SipManager object is not null.I cannot find the reason about it.
1.741 30654-30654/com.dev.goldunion I/System.out: initializeSip
05-18 20:11:41.741 30654-30654/com.dev.goldunion I/System.out: isApiSupported=true
05-18 20:11:41.751 30654-30654/com.dev.goldunion I/System.out: SipManager=android.net.sip.SipManager#426af938
05-18 20:11:41.751 30654-30654/com.dev.goldunion D/AndroidRuntime: Shutting down VM
05-18 20:11:41.751 30654-30654/com.dev.goldunion W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41692970)
05-18 20:11:41.751 30654-30654/com.dev.goldunion E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dev.goldunion/com.dev.goldunion.activity.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2227)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2282)
at android.app.ActivityThread.access$600(ActivityThread.java:147)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5265)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:760)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.net.sip.SipManager.open(SipManager.java:180)
at com.dev.goldunion.util.RegisterSipAccountUtils.initializeSip(RegisterSipAccountUtils.java:49)
at com.dev.goldunion.activity.MainActivity.onCreate(MainActivity.java:77)
at android.app.Activity.performCreate(Activity.java:5146)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1090)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2191)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2282) 
at android.app.ActivityThread.access$600(ActivityThread.java:147) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:5265) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:525) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:760) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576) 
at dalvik.system.NativeStart.main(Native Method) 

How do I solve IabHelper Error

I have an error on 264 and 163 of two file but in editor it's look fine
line 264 :
if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {
line 163 :
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
I can't find why my activity unable to start
Logcat:
1266-1266/com.exercise.AndroidHTML E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exercise.AndroidHTML/com.company.clipboard.AndroidHTMLActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.company.clipboard.util.IabHelper.startSetup(IabHelper.java:264)
at com.company.clipboard.AndroidHTMLActivity.onCreate(AndroidHTMLActivity.java:163)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at android.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
This is the whole block of payment that contain line 163:
//=====================================================
String base64EncodedPublicKey = "MIHNMA0GCSqGSIb3DQEBAQUAA4G7ADCBtwKBrwDtUWVdLt6clZldCQGZxcyyWeeBp8vF/6qm7qCKuQPdXg6HB71hVu8lmcEO0VcyS2xpzXt03iW7LhKXRtDsxi5H9wHLESfY9SQUc0ugPD+n5nE+I6zCiB/RB2WscvZFa3JCiYRbmsvez+DwaQSHfq6CNUawl0fbz4NfJntZHKYHanm6PtjquO9JSj+Pa9PV38C3o5Y3ALCvPMCAwEAAQ==";
mHelper = new IabHelper(this, base64EncodedPublicKey);
mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
Log.d(TAG, "Query inventory finished.");
if (result.isFailure()) {
Log.d(TAG, "Failed to query inventory: " + result);
return;
}
else {
Log.d(TAG, "Query inventory was successful.");
// does the user have the premium upgrade?
mIsPremium = inventory.hasPurchase(SKU_PREMIUM);
if (mIsPremium){
MasrafSeke(inventory.getPurchase(SKU_PREMIUM));
}
// update UI accordingly
Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM"));
}
Log.d(TAG, "Initial inventory query finished; enabling main UI.");
}
};
mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
if (result.isFailure()) {
Log.d(TAG, "Error purchasing: " + result);
return;
}
else if (purchase.getSku().equals(SKU_PREMIUM)) {
// give user access to premium content and update the UI
Toast.makeText(AndroidHTMLActivity.this,"خرید موفق",Toast.LENGTH_SHORT).show();
MasrafSeke(purchase);
}
}
};
Log.d(TAG, "Starting setup.");
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
Log.d(TAG, "Setup finished.");
if (!result.isSuccess()) {
// Oh noes, there was a problem.
Log.d(TAG, "Problem setting up In-app Billing: " + result);
}
// Hooray, IAB is fully set up!
mHelper.queryInventoryAsync(mGotInventoryListener);
}
});
Seems an issue of IabHelper. The method queryIntentServices returns a null, instead an empty list.
Try to update the code from this:
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {
// service available to handle that Intent
mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
}
else {
// no service available to handle that Intent
if (listener != null) {
listener.onIabSetupFinished(
new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE,
"Billing service unavailable on device."));
}
}
to this:
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
List<ResolveInfo> intentServices = mContext.getPackageManager().queryIntentServices(serviceIntent, 0);
if (intentServices != null && intentServices.isEmpty() == false) {
// service available to handle that Intent
mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
}
else {
// no service available to handle that Intent
if (listener != null) {
listener.onIabSetupFinished(
new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE,
"Billing service unavailable on device."));
}
}

runOnUiThread: Cant touch the View, Exception

I know this has been posted multiple times now, but nothing seemed to fix my problem. I create a Loading Dialog on the UI thread, then start another thread which is doing some networking stuff and via interface, the class gets a callback, when networking is done. The problem is, after its done, i cant remove the loading dialog, even with "runOnUIThread". Here is the code:
public void onClickLoginButton (View view) {
if (!((EditText)findViewById(R.id.textNickname)).getText().toString().isEmpty() &&
!((EditText)findViewById(R.id.textPassword)).getText().toString().isEmpty()) {
loggingIn = new ProgressDialog(this);
loggingIn.setTitle("Login");
loggingIn.setMessage("Wait while logging in...");
loggingIn.show();
final LoginInterface callbackInterface = this;
new Thread(new Runnable() {
public void run() {
Networking net = new Networking();
net.Login(((EditText) findViewById(R.id.textNickname)).getText().toString(), ((EditText) findViewById(R.id.textPassword)).getText().toString(), callbackInterface);
}
}).start();
}
}
And this is the function that gets called by the networking stuff, after its done:
#Override
public void LoginCallback(final boolean loginSuccess, final boolean isActivated) {
loggingIn.hide();
loggingIn = null;
final Context context = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
if (loginSuccess && isActivated) {
loggingIn.hide();
loggingIn = null;
finish();
} else if (loginSuccess == false) {
Toast.makeText(context, "Login failed! User/Password wrong", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Login failed! Account not activated", Toast.LENGTH_SHORT).show();
}
}
});
}
And this is the stack trace:
04-17 17:06:11.313 13018-13121/com.assigame.nidhoegger.assigame E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-1422
Process: com.assigame.nidhoegger.assigame, PID: 13018
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6122)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:850)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.setFlags(View.java:8908)
at android.view.View.setVisibility(View.java:6036)
at android.app.Dialog.hide(Dialog.java:299)
at com.assigame.nidhoegger.assigame.Login.LoginCallback(Login.java:72)
at com.assigame.nidhoegger.assigame.Networking.Login(Networking.java:134)
at com.assigame.nidhoegger.assigame.Login$1.run(Login.java:64)
at java.lang.Thread.run(Thread.java:841)
04-17 17:06:11.719 13018-13018/com.assigame.nidhoegger.assigame E/WindowManager﹕ android.view.WindowLeaked: Activity com.assigame.nidhoegger.assigame.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42284588 G.E..... R......D 0,0-684,324} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:366)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at com.assigame.nidhoegger.assigame.Login.onClickLoginButton(Login.java:56)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3818)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
You are calling the loggingIn.hide() method twice, and the first time not on the UI thread. Change your code to this:
#Override
public void LoginCallback(final boolean loginSuccess, final boolean isActivated) {
final Context context = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
if (loginSuccess && isActivated) {
loggingIn.hide();
loggingIn = null;
finish();
} else if (loginSuccess == false) {
Toast.makeText(context, "Login failed! User/Password wrong", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Login failed! Account not activated", Toast.LENGTH_SHORT).show();
}
}
});
}

NullPointException on algorithm but don't get NPE on same algorithm in another spot in same class [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
In my app, the user has 3 different types of quizzes they can choose. When they choose one of quiz types called "levels", I get a NullPointerException. The order of the algorithm for "levels" is the same as when the game type is "original". You can see this in the code below. It is hard to explain why the algorithms are the same so I will spare you those details but just accept the algorithms are the same for now. :)
Why am I getting this NPE exception with the quiz/game type is "levels" but not when the quiz/game type is "original" even though the code/algorithm for them are the same?
public class QuestionView extends Activity {
int correctAnswers = 0;
int wrongAnswers = 0;
int answer = 0;
int i = 0;
long score = 0;
long startTime = 20000;
long interval = 1000;
long points;
boolean timerHasStarted = false;
String category;
Button answer1, answer2, answer3, answer4;
TextView question, pointCounter, questionNumber, timeCounter, timeremaining;
ArrayList<Question> queries;
public static ArrayList<Long> pointsPerQuestion = new ArrayList<Long>(10);
Timer cdTimer;
ProgressBar bar;
Context c;
Singleton singleton = Singleton.getInstance();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.questionview);
c = this;
answer1 = (Button)findViewById(R.id.answer1);
answer2 = (Button)findViewById(R.id.answer2);
answer3 = (Button)findViewById(R.id.answer3);
answer4 = (Button)findViewById(R.id.answer4);
question = (TextView)findViewById(R.id.question);
questionNumber = (TextView)findViewById(R.id.questionnumber);
timeremaining = (TextView)findViewById(R.id.timeremaining);
category = getIntent().getStringExtra("category");
queries = getIntent().getParcelableArrayListExtra("queries");
pointsPerQuestion.clear();
if(singleton.getGameType() == "levels") {
if(singleton.getLevel() <= 10) {
cdTimer = new Timer(startTime, interval);
bar = (ProgressBar)findViewById(R.id.progressbar);
bar.setIndeterminate(false);
bar.setMax(20000);
loadLevelsQuizTen();
}
//...
} else if (singleton.getGameType() == "original") {
cdTimer = new Timer(startTime, interval);
bar = (ProgressBar)findViewById(R.id.progressbar);
bar.setIndeterminate(false);
bar.setMax(20000);
loadOriginalQuiz();
} else if (singleton.getGameType() == "freeplay") {
loadFreeplayQuiz();
}
}
public void loadFreeplayQuiz() {
//...
}
public void loadLevelsQuizTen() {
if(i == 10) {
cdTimer.cancel();
endQuiz();
} else {
if(!timerHasStarted) {
cdTimer.start();
timerHasStarted = true;
} else {
cdTimer.start();
timerHasStarted = false;
}
//answer = queries.get(i).getCorrectAnswer(); //NULLPOINTEREXCEPTION HERE
answer = 2;
question.setText(queries.get(i).getQuery()); // I COMMENTED OUT ABOVE LINE OF CODE AND NOW NPE IS NOW HERE
answer1.setText(queries.get(i).getA1());
answer2.setText(queries.get(i).getA2());
answer3.setText(queries.get(i).getA3());
answer4.setText(queries.get(i).getA4());
answer1.setOnClickListener(new OnClickListener() {
//...
}
});
answer2.setOnClickListener(new OnClickListener() {
//...
});
answer3.setOnClickListener(new OnClickListener() {
//...
});
answer4.setOnClickListener(new OnClickListener() {
//...
});
}
}
public void loadOriginalQuiz() {
if(i == 10) {
cdTimer.cancel();
endQuiz();
} else {
if(!timerHasStarted) {
cdTimer.start();
timerHasStarted = true;
} else {
cdTimer.start();
timerHasStarted = false;
}
answer = queries.get(i).getCorrectAnswer();
question.setText(queries.get(i).getQuery());
answer1.setText(queries.get(i).getA1());
answer2.setText(queries.get(i).getA2());
answer3.setText(queries.get(i).getA3());
answer4.setText(queries.get(i).getA4());
answer1.setOnClickListener(new OnClickListener() {
//...
});
answer2.setOnClickListener(new OnClickListener() {
//...
});
answer3.setOnClickListener(new OnClickListener() {
//...
});
answer4.setOnClickListener(new OnClickListener() {
//...
});
}
}
public ArrayList<Question> getQueries() {
return queries;
}
public static ArrayList<Long> getPointsPerQuestion() {
//...
}
public void correct() {
pointsPerQuestion.add(points);
score = score + points;
i++;
if(singleton.getGameType() == "original") {
loadOriginalQuiz();
} else if(singleton.getGameType() == "levels") {
loadLevelsQuizTen();
}
}
public void incorrect() {
long zero = 0;
pointsPerQuestion.add(zero);
i++;
loadOriginalQuiz();
}
public class Timer extends CountDownTimer {
public Timer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
points = 0;
if(i >= 9) {
cdTimer.cancel();
pointsPerQuestion.add(points);
endQuiz();
} else {
wrongAnswers++;
incorrect();
}
}
#Override
public void onTick(long millisUntilFinished) {
bar.setProgress((int) millisUntilFinished);
points = (millisUntilFinished / 200) + 1;
timeremaining.setText("Score remaining: " + points);
if(i < 10) {
questionNumber.setText(c.getResources().getString(R.string.question) + " " + (i + 1) + " " + c.getResources().getString(R.string.of10));
}
}
}
public void endQuiz() {
Intent intent = new Intent(QuestionView.this, Results.class);
intent.putExtra("correctAnswers", correctAnswers);
intent.putExtra("wrongAnswers", wrongAnswers);
intent.putExtra("score", score);
intent.putExtra("pointsPerQuestion", pointsPerQuestion);
intent.putParcelableArrayListExtra("queries", queries);
intent.putExtra("category", category);
startActivity(intent);
}
public void onStop() {
super.onStop();
}
public void onResume() {
super.onResume();
}
}
LogCat
06-14 20:44:45.413: E/AndroidRuntime(1335): java.lang.RuntimeException: Unable to start activity ComponentInfo{matt.lyons.bibletrivia.lite/matt.lyons.bibletrivia.lite.QuestionView}: java.lang.NullPointerException
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.os.Handler.dispatchMessage(Handler.java:99)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.os.Looper.loop(Looper.java:137)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.ActivityThread.main(ActivityThread.java:5041)
06-14 20:44:45.413: E/AndroidRuntime(1335): at java.lang.reflect.Method.invokeNative(Native Method)
06-14 20:44:45.413: E/AndroidRuntime(1335): at java.lang.reflect.Method.invoke(Method.java:511)
06-14 20:44:45.413: E/AndroidRuntime(1335): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-14 20:44:45.413: E/AndroidRuntime(1335): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-14 20:44:45.413: E/AndroidRuntime(1335): at dalvik.system.NativeStart.main(Native Method)
06-14 20:44:45.413: E/AndroidRuntime(1335): Caused by: java.lang.NullPointerException
06-14 20:44:45.413: E/AndroidRuntime(1335): at matt.lyons.bibletrivia.lite.QuestionView.loadLevelsQuizTen(QuestionView.java:195)
06-14 20:44:45.413: E/AndroidRuntime(1335): at matt.lyons.bibletrivia.lite.QuestionView.onCreate(QuestionView.java:80)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.Activity.performCreate(Activity.java:5104)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
Why "accept"? That might be the fatal flaw in your argument.
Here's the problem:
Caused by: java.lang.NullPointerException
06-14 20:44:45.413: E/AndroidRuntime(1335): at matt.lyons.bibletrivia.lite.QuestionView.loadLevelsQuizTen(QuestionView.java:195)
Go to line 195 in the QuestionView.java file, look at the object references on that line, and see which one you failed to initialize.
The sooner you stop telling yourself that everything is fine and start looking at what's really happening, the sooner you'll fix the problem and move on.
You should not be duplicating any code. You should encapsulate it in a single method call and calling it in both places. This is a recipe for error.
You have lots of other issues. You use a private data member i to do different things in different methods. It's not synchronized in any way that I can see. I see no reason why that value couldn't be a method parameter and passed in. That would be more more thread safe.
When you're doing things like that, comparing Strings with ==, and duplicating code it puts everything you've done in doubt for me. No wonder you're having trouble. Voting to close.
Set a breakpoint where you are getting the NPE and check the values of your variables. I would guess either queries is null (not setting or getting from intent bundle correctly), or queries.get(i) is null.
you get the error because you are calling 2 different methods. In levels you call loadLevelsQuizTen();, in original you call loadOriginalQuiz();
Despite the fact you say they are the same, they aren't. I'd use a debugger to step through the method and figure out what is null and why.

Twitter: After giving username and password the app gets crash

In my android application the data has to be shared using twitter so had followed this link http://androidcodeexamples.blogspot.in/2011/12/how-to-integrate-twitter-in-android.html, everything works fine, but after giving username and password, getting force close option.
here's the logcat output
01-17 17:07:54.118: E/AndroidRuntime(383): FATAL EXCEPTION: main
01-17 17:07:54.118: E/AndroidRuntime(383): java.lang.NullPointerException
01-17 17:07:54.118: E/AndroidRuntime(383): com.twitter.android.TwitterApp$1.handleMessage(TwitterApp.java:237)
01-17 17:07:54.118: E/AndroidRuntime(383): at android.os.Handler.dispatchMessage(Handler.java:99)
01-17 17:07:54.118: E/AndroidRuntime(383): at android.os.Looper.loop(Looper.java:123)
01-17 17:07:54.118: E/AndroidRuntime(383): at android.app.ActivityThread.main(ActivityThread.java:3683)
01-17 17:07:54.118: E/AndroidRuntime(383): at java.lang.reflect.Method.invokeNative(Native Method)
01-17 17:07:54.118: E/AndroidRuntime(383): at java.lang.reflect.Method.invoke(Method.java:507)
01-17 17:07:54.118: E/AndroidRuntime(383): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-17 17:07:54.118: E/AndroidRuntime(383): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-17 17:07:54.118: E/AndroidRuntime(383): at dalvik.system.NativeStart.main(Native Method)
this is the code in mainactivity
public class Singlemenuitem extends Activity {
private TwitterApp mTwitter;
private static final String CONSUMER_KEY = "6JyIkj71ZqG4wk3YF0Y4hw";
private static final String CONSUMER_SECRET = "sJl9aRVqlEt7nxlKvpMVK6tLULz5FSQ2KUOW0yie4";
private enum FROM {
TWITTER_POST, TWITTER_LOGIN
};
private enum MESSAGE {
SUCCESS, DUPLICATE, FAILED, CANCELLED
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
mTwitter = new TwitterApp(this, CONSUMER_KEY, CONSUMER_SECRET);
//share twitter
final ImageView twitter = (ImageView) findViewById(R.id.twitter);
twitter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
mTwitter.resetAccessToken();
if (mTwitter.hasAccessToken() == true) {
try {
mTwitter.updateStatus(String.valueOf(Html
.fromHtml(TwitterApp.MESSAGE)));
// File f = new File("/mnt/sdcard/android.jpg");
// mTwitter.uploadPic(f, String.valueOf(Html
// .fromHtml(TwitterApp.MESSAGE)));
postAsToast(FROM.TWITTER_POST, MESSAGE.SUCCESS);
} catch (Exception e) {
if (e.getMessage().toString().contains("duplicate")) {
postAsToast(FROM.TWITTER_POST, MESSAGE.DUPLICATE);
}
e.printStackTrace();
}
mTwitter.resetAccessToken();
} else {
mTwitter.authorize();
}
}
private void postAsToast(FROM twitterPost, MESSAGE success) {
switch (twitterPost) {
case TWITTER_LOGIN:
switch (success) {
case SUCCESS:
Toast.makeText(Singlemenuitem.this, "Login Successful", Toast.LENGTH_LONG)
.show();
break;
case FAILED:
Toast.makeText(Singlemenuitem.this, "Login Failed", Toast.LENGTH_LONG).show();
default:
break;
}
break;
case TWITTER_POST:
switch (success) {
case SUCCESS:
Toast.makeText(Singlemenuitem.this, "Posted Successfully", Toast.LENGTH_LONG)
.show();
break;
case FAILED:
Toast.makeText(Singlemenuitem.this, "Posting Failed", Toast.LENGTH_LONG)
.show();
break;
case DUPLICATE:
Toast.makeText(Singlemenuitem.this,
"Posting Failed because of duplicate message...",
Toast.LENGTH_LONG).show();
default:
break;
}
break;
}
TwDialogListener mTwLoginDialogListener = new TwDialogListener() {
public void onError(String value) {
postAsToast(FROM.TWITTER_LOGIN, MESSAGE.FAILED);
Log.e("TWITTER", value);
mTwitter.resetAccessToken();
}
public void onComplete(String value) {
try {
mTwitter.updateStatus(TwitterApp.MESSAGE);
postAsToast(FROM.TWITTER_POST, MESSAGE.SUCCESS);
} catch (Exception e) {
if (e.getMessage().toString().contains("duplicate")) {
postAsToast(FROM.TWITTER_POST, MESSAGE.DUPLICATE);
}
e.printStackTrace();
}
mTwitter.resetAccessToken();
}

Categories