Android Exception handling on EditText - java

I am going through an Android course online and have hit a stumbling block.
When an EditText (Number) field is submitted without any content, my app crashes.
I have tried adding exception handlers to the code, to my understanding. Nut I still have the same problem. I am handling the exceptions that show up in my logs, shown below.
The InvocationTargetException entry flags in Android Studio as Cannot resolve symbol InvocationTargetException.
I'm not sure what the problem is with that or if it might be related.
Code:
package com.example.richardcurteis.higherorlower;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import java.lang.reflect.Method;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
int randomNumber;
EditText getUserInput;
public int getRandomNumber() {
Random randomGenerator = new Random();
randomNumber = randomGenerator.nextInt(10) +1;
return randomNumber;
}
public void higherOrLower(View view) {
String exceptionMessage = "";
try {
getUserInput = (EditText) findViewById(R.id.userInput);
} catch (InvocationTargetException e) {
exceptionMessage = "InvocationTargetException";
} catch (NumberFormatException e) {
exceptionMessage = "NumberFormatException";
} catch (IllegalStateException e) {
exceptionMessage = "IllegalStateException";
}
Toast.makeText(this, exceptionMessage, Toast.LENGTH_LONG).show();
int userInteger = Integer.parseInt(getUserInput.getText().toString());
String message = "";
if (userInteger > randomNumber) {
message = "Lower!";
getUserInput.getText().clear();
} else if (userInteger < randomNumber) {
message = "Higher!";
getUserInput.getText().clear();
} else {
message = "You win!";
getUserInput.getText().clear();
getRandomNumber();
}
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
randomNumber = getRandomNumber();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Errors:
12-28 16:36:23.985 5035-5035/com.example.richardcurteis.higherorlower E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.richardcurteis.higherorlower, PID: 5035
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:275)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:270)
at android.view.View.performClick(View.java:5198) 
at android.view.View$PerformClick.run(View.java:21147) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Caused by: java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at com.example.richardcurteis.higherorlower.MainActivity.higherOrLower(MainActivity.java:40)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:270) 
at android.view.View.performClick(View.java:5198) 
at android.view.View$PerformClick.run(View.java:21147) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

Use this helper method to convert string to integer
public static Integer toInteger(final String str, final Integer defaultValue) {
if (str == null) {
return defaultValue;
}
try {
return Integer.valueOf(str);
} catch (NumberFormatException nfe) {
return defaultValue;
}
}
Something like this
Integer userInteger = toInteger(getUserInput.getText().toString(), null);
if (userInteger == null) {
Toast.makeText(getApplicationContext(), "Invalid input", Toast.LENGTH_SHORT).show();
return;
}

Move into the "try" block this line of your code:
int userInteger = Integer.parseInt(getUserInput.getText().toString());

Looking through the error log it shows you're trying to parse a blank string to an int.
Caused by: java.lang.NumberFormatException: Invalid int: ""
InvocationTargetException is just a wrapper for an exception that's thrown within a dynamic invocation.
The exceptions are thrown because you're try catching around the wrong snippet of code.

Related

Unfortunately, the app has stopped Android Studio

I am pretty sure there is no problem in my XML or manifest. The problem has to be in my code (because I had altered my code slightly and it stopped working). The app crashes before it even begins. The error I got is:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.trainer.braintrainer/com.trainer.braintrainer.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Button.setText(java.lang.CharSequence)' on a null
object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void android.widget.Button.setText(java.lang.CharSequence)' on
a null object reference
at
com.trainer.braintrainer.MainActivity.generateQuestion(MainActivity.java:60)
at
com.trainer.braintrainer.MainActivity.onCreate(MainActivity.java:101)
at android.app.Activity.performCreate(Activity.java:6237)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  06-16
08:01:16.547 24091-24091/com.trainer.braintrainer I/Process: Sending
signal. PID: 24091 SIG: 9
Below is my Main java code:
package com.trainer.braintrainer;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
ArrayList<Integer> answers=new ArrayList<Integer>();
Random rand = new Random();
int locationOfCorrectAnswer;
Button startButton;
Button button0;
Button button1;
Button button2;
Button button3;
int score=0;
int numberOfQuestions=0;
TextView answerMessage;
String message;
TextView scoreText;
TextView sumTextView;
TextView timerText;
public void generateQuestion(){
int a=rand.nextInt(21);
int b=rand.nextInt(21);
sumTextView.setText(Integer.toString(a) + " + " + Integer.toString(b));
locationOfCorrectAnswer=rand.nextInt(4);
answers.clear();
int inCorrectAns;
for (int i=0;i<=3;i++){
if (i==locationOfCorrectAnswer){
answers.add(a+b);
}else{
inCorrectAns=rand.nextInt(50);
while (inCorrectAns==a+b){
inCorrectAns=rand.nextInt(50);
}
answers.add(inCorrectAns);
}
}
button0.setText(Integer.toString(answers.get(0)));
button1.setText(Integer.toString(answers.get(1)));
button2.setText(Integer.toString(answers.get(2)));
button3.setText(Integer.toString(answers.get(3)));
}
public void startButton(View view){
startButton.setVisibility(View.INVISIBLE);
}
public void answerFunction(View view){
int tappedLocation= (int)view.getTag();
if (tappedLocation==locationOfCorrectAnswer){
message="Correct!";
score++;
}else{
message="Wrong!";
}
answerMessage.setText(message);
scoreText.setText(Integer.toString(score) + "/" + Integer.toString(numberOfQuestions));
numberOfQuestions++;
generateQuestion();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton=(Button)findViewById(R.id.button5);
answerMessage=(TextView)findViewById(R.id.messageView);
sumTextView=(TextView)findViewById(R.id.sumTextView);
scoreText=(TextView)findViewById(R.id.scoreText);
timerText=(TextView)findViewById(R.id.timerText);
generateQuestion();
new CountDownTimer(30100,1000){
#Override
public void onTick(long millisUntilFinished) {
int seconds=(int) millisUntilFinished/1000;
timerText.setText(Integer.toString(seconds)+"s");
}
#Override
public void onFinish() {
answerMessage.setText("Done");
}
}.start();
button0=(Button)findViewById(R.id.ans1);
button1=(Button)findViewById(R.id.ans2);
button2=(Button)findViewById(R.id.ans3);
button3=(Button)findViewById(R.id.ans4);
}
}
You are calling the method generateQuestion(); before assigning value to the buttons: button1, button2 etc. When you do setText on these buttons, it throws a null object reference error. what you can do is:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton=(Button)findViewById(R.id.button5);
answerMessage=(TextView)findViewById(R.id.messageView);
sumTextView=(TextView)findViewById(R.id.sumTextView);
scoreText=(TextView)findViewById(R.id.scoreText);
timerText=(TextView)findViewById(R.id.timerText);
button0=(Button)findViewById(R.id.ans1);
button1=(Button)findViewById(R.id.ans2);
button2=(Button)findViewById(R.id.ans3);
button3=(Button)findViewById(R.id.ans4);
generateQuestion();
new CountDownTimer(30100,1000){
#Override
public void onTick(long millisUntilFinished) {
int seconds=(int) millisUntilFinished/1000;
timerText.setText(Integer.toString(seconds)+"s");
}
#Override
public void onFinish() {
answerMessage.setText("Done");
}
}.start();
}
}
That is assign the respective views to the button before calling the generateQuestion()

Error receiving broadcast intent using BatteryManager

I am getting Error in receiving broadcast intent i am using BatteryManager for it. I have no clue why I am getting this error.
Someone please help.
thanks in advance
Let me know if you need more code.
Here is the error:
> Error receiving broadcast Intent {
> act=android.intent.action.BATTERY_CHANGED flg=0x60000010 (has extras)
> } in com.example.android.login.MainActivity$1#260e12dc
> at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:933)
> at android.os.Handler.handleCallback(Handler.java:739)
> at android.os.Handler.dispatchMessage(Handler.java:95)
> at android.os.Looper.loop(Looper.java:145)
> at android.app.ActivityThread.main(ActivityThread.java:5972)
> at java.lang.reflect.Method.invoke(Native Method)
> at java.lang.reflect.Method.invoke(Method.java:372)
> at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
> at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
> Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
> android.widget.TextView.setText(java.lang.CharSequence)' on a null
> object reference
> at com.example.android.login.MainActivity$1.onReceive(MainActivity.java:37)
> at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:923)
>             at android.os.Handler.handleCallback(Handler.java:739)
>             at android.os.Handler.dispatchMessage(Handler.java:95)
>             at android.os.Looper.loop(Looper.java:145)
>             at android.app.ActivityThread.main(ActivityThread.java:5972)
>             at java.lang.reflect.Method.invoke(Native Method)
>             at java.lang.reflect.Method.invoke(Method.java:372)
Activity Class
package com.example.android.login;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.BatteryManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.LogOutCallback;
import com.parse.Parse;
import com.parse.ParseObject;
import com.parse.ParseUser;
import com.parse.ParseException;
public class MainActivity extends ActionBarActivity {
private TextView batteryTxt;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context ctxt, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
batteryTxt.setText(String.valueOf(level) + "%");
}
};
private Toolbar toolbar;
public Button logoutButton;
public int level;
#Override
public void onCreate(Bundle savedInstanceState) {
batteryTxt = (TextView) this.findViewById(R.id.percent);
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_appbar);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawerLayout), toolbar);
logoutButton = (Button) findViewById(R.id.logoutButton);
logoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Set up a progress dialog
final ProgressDialog logout = new ProgressDialog(MainActivity.this);
logout.setTitle("Please wait.");
logout.setMessage("Logging out. Please wait.");
logout.show();
ParseUser.logOutInBackground(new LogOutCallback() {
public void done(ParseException e) {
logout.dismiss();
if (e == null) {
Intent logoutDone = new Intent(MainActivity.this, DispatchActivity.class);
startActivity(logoutDone);
} else {
Toast.makeText(MainActivity.this, "Logout Unsuccessful", Toast.LENGTH_LONG).show();
}
}
});
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Based on your stack trace, it looks like it is throwing a NullPointerException because the batteryTxt field is null at the time that the intent was received. As Daniel Nugent pointed out, this is because the receiver is registered before calling setContentView(). However, it looks like you're also never unregistering your receiver, so I suggest moving the code to register the receiver to the onResume() method, and adding an unregister call in the onPause() method to prevent this same NullPointerException from occurring when your activity is stopped.
#Override
protected void onResume() {
super.onResume();
registerReceiver(mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
#Override
protected void onPause() {
unregisterReceiver(mBatInfoReceiver);
super.onPause();
}
do this
batteryTxt = (TextView) this.findViewById(R.id.percent);
after this
setContentView(R.layout.activity_main_appbar);
always read this section in your error log
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
Write the code like that
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_appbar);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
batteryTxt = (TextView) this.findViewById(R.id.percent);
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

ClassNotFoundException with Parse and Facebook

I am hoping you can help me with a problem I am facing. I am trying to integrate Facebook login to my app using Parse, and I get a ClassNotFoundException error, when I call the method
ParseFacebookUtils.logInWithReadPermissionsInBackground(LoginActivity.this, permissions, new LogInCallback()
The error stack trace:
05-15 10:36:00.749 3936-3936/kstr14.tipper E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: kstr14.tipper, PID: 3936
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4007)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/parse/ParseTaskUtils;
at com.parse.ParseFacebookUtils.logInWithReadPermissionsInBackground(ParseFacebookUtils.java:173)
at kstr14.tipper.Activities.LoginActivity.facebookLoginPressed(LoginActivity.java:170)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.parse.ParseTaskUtils" on path: DexPathList[[zip file "/data/app/kstr14.tipper-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at com.parse.ParseFacebookUtils.logInWithReadPermissionsInBackground(ParseFacebookUtils.java:173)
at kstr14.tipper.Activities.LoginActivity.facebookLoginPressed(LoginActivity.java:170)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Suppressed: java.lang.ClassNotFoundException: com.parse.ParseTaskUtils
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 16 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
I have the following jar files in my lib folder:
Parse-1.9.1.jar
javax.mail.jar
bolts-android-1.2.0.jar
ParseFacebookUtilsV4-1.9.2.jar
I have tried various things with the dependencies part of the build.gradle file, as I suspect this error is due to some library not being included correctly, but none of what I have tried have worked. I've tried different ways of specifying compiling the jar files as well as specifying the jars in different orders.
Currently my build.gradle file looks like this:
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "kstr14.tipper"
minSdkVersion 21
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
debug {
debuggable true
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
repositories {
mavenCentral()
}
dependencies {
compile fileTree(include: ['*.jar'] ,dir: 'libs')
compile files('libs/bolts-android-1.2.0.jar')
compile 'com.parse.bolts:bolts-android:1.2.0'
compile files('libs/Parse-1.9.1.jar')
compile files('libs/ParseFacebookUtilsV4-1.9.2.jar')
compile files('libs/javax.mail.jar')
compile 'com.android.support:appcompat-v7:22.0.0'
compile 'com.facebook.android:facebook-android-sdk:4.0.0'
compile 'com.google.android.gms:play-services:7.0.0'
}
Anyone have any suggestions?
Oh and by the way, when my app crashes due to the error, I press OK, and then the Facebook login screen shows up anyway.. So I suppose the facebook jar is being imported fine, and the problem is within the Parse jars. However, I have been using the Pars jar before I tried to integrate Facebook, and it worked just fine. I imported the bolts jar at the same time I imported the Facebook jar, as I read somewhere that it was necessary, so it might be a problem with the bolts jar?
EDIT: Added code for LoginActivity:
package kstr14.tipper.Activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.Toast;
import com.facebook.FacebookSdk;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseFacebookUtils;
import com.parse.ParseObject;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
import java.util.ArrayList;
import java.util.List;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import kstr14.tipper.Data.Category;
import kstr14.tipper.Data.Group;
import kstr14.tipper.Data.Tip;
import kstr14.tipper.R;
public class LoginActivity extends ActionBarActivity {
// UI elements for default login fragment
private EditText usernameDefaultLogin;
private EditText passwordDefaultLogin;
// UI elements for sign up fragment
private EditText usernameSignup;
private EditText emailSignup;
private EditText passwordSignup;
private EditText reenterPasswordSignup;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
// initalize facebook
FacebookSdk.sdkInitialize(getApplicationContext());
// Initialize Parse
ParseObject.registerSubclass(Tip.class);
ParseObject.registerSubclass(Category.class);
ParseObject.registerSubclass(Group.class);
ParseObject.registerSubclass(ParseUser.class);
// check cache for current user - if found go directly to MainActivity
ParseUser currentUser = ParseUser.getCurrentUser();
if(currentUser != null) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
// otherwise set fragment to the default login screen
DefaultLoginFragment defaultLoginFragment = new DefaultLoginFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, defaultLoginFragment).commit();
}
// Required for making Facebook login work
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ParseFacebookUtils.onActivityResult(requestCode, resultCode, data);
}
/**
* Method called when sign up button pressed on the default login fragment
* Switches the default login fragment with a sign up fragment
* #param view
*/
public void defaultSignUpPressed(View view) {
SignUpFragment signUpFragment = new SignUpFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Replace the default login fragment with the sign up fragment,
// and add the transaction to the back stack so the user can navigate back
fragmentTransaction.replace(R.id.fragment_container, signUpFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
/**
* Method called when login button pressed on the default login fragment
* Attempts to log in the user, if successful goes to MainActivity
* #param view
*/
public void defaultLoginPressed(View view) {
// initialize UI elements for default login fragment
usernameDefaultLogin = (EditText) findViewById(R.id.usernameDefaultLoginFragment);
passwordDefaultLogin = (EditText) findViewById(R.id.passwordDefaultLoginFragment);
// fetch input and attempt login
String username = usernameDefaultLogin.getText().toString();
String password = passwordDefaultLogin.getText().toString();
ParseUser.logInInBackground(username, password, new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Login failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Method called when sign up button pressed in sign up fragment
* Attempts to register the user, if successful goes to MainActivity
* #param view
*/
public void signupPressed(View view) {
// UI elements for sign up fragment
usernameSignup = (EditText) findViewById(R.id.usernameSignupFragment);
emailSignup = (EditText) findViewById(R.id.emailSignupFragment);
passwordSignup = (EditText) findViewById(R.id.passwordSignupFragment);
reenterPasswordSignup = (EditText) findViewById(R.id.reenterPasswordSignupFragment);
String username = usernameSignup.getText().toString();
String email = emailSignup.getText().toString();
String password1 = passwordSignup.getText().toString();
String password2 = reenterPasswordSignup.getText().toString();
// validate passwords and email
if(!validatePassword(password1, password2)) {
Toast.makeText(getApplicationContext(), "Passwords do not match, try again.", Toast.LENGTH_SHORT).show();
} else if (!validateEmail(email)) {
Toast.makeText(getApplicationContext(), "Please enter a valid email.", Toast.LENGTH_SHORT).show();
} else {
ParseUser user = new ParseUser();
user.setUsername(username);
user.setPassword(password1);
user.setEmail(email);
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Sign up failed. Please try again.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
public void facebookLoginPressed(View view) {
List<String> permissions = new ArrayList<String>();
permissions.add("public_profile");
ParseFacebookUtils.logInWithReadPermissionsInBackground(LoginActivity.this, permissions, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
Log.d("MyApp", "Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
Log.d("MyApp", "User signed up and logged in through Facebook!");
} else {
Log.d("MyApp", "User logged in through Facebook!");
}
}
});
}
/**
* Validates that two passwords are equal
* #param password1
* #param password2
* #return
*/
public boolean validatePassword(String password1, String password2) {
if(password1.equals(password2)) return true;
else return false;
}
/**
* Validates the structure of an email address
* #param email
* #return
*/
public boolean validateEmail(String email) {
boolean result = true;
try {
InternetAddress internetAddress = new InternetAddress(email);
internetAddress.validate();
} catch (AddressException e) {
e.printStackTrace();
result = false;
}
return result;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I actually just ran into this same problem. Hopefully I can save a lot of headache for anyone searching for this issue. The answer is not to use an older SDK. Actually all you needed to do was be sure that you were using the same version of Parse and ParseFacebookUtils. Look at your gradle file above
compile 'com.parse.bolts:bolts-android:1.2.0'
compile files('libs/Parse-1.9.1.jar')
compile files('libs/ParseFacebookUtilsV4-1.9.2.jar')
You were using Parse-1.9.1 and ParseFacebookUtilsV4-1.9.2. I actually made the same mistake. I pulled the Parse-1.9.1 from another project and downloaded the SDK again to pull the FacebookUtils library out.
After trying a bunch of different things, including upgrading AndroidStudio and gradle, I solved this by using an older version of the Parse libraries. I was using the newest version 1.9.2, and now I am using 1.9.0, and it works! So there must be some bug in the new version..

Android Studio SeekBar Error

Hello I'm trying to get the value of a SeekBar in android studio. If i run app it is crashing. There is no syntax error.
package prosis.guiaturistico;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private static SeekBar seek_bar;
private static TextView text_view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekbar();
}
public void seekbar(){
seek_bar = (SeekBar)findViewById(R.id.seekbar);
text_view = (TextView)findViewById(R.id.seekbarValue);
text_view.setText("Covered : " + seek_bar.getProgress() + " / " +seek_bar.getMax());
seek_bar.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener(){
int progress_value;
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progress_value = progress;
text_view.setText("Covered : " + progress + " / " +seek_bar.getMax());
Toast.makeText(MainActivity.this,"SeekBar in progress",Toast.LENGTH_LONG).show();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
Toast.makeText(MainActivity.this,"SeekBar in start",Toast.LENGTH_LONG).show();
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
text_view.setText("Covered : " + progress_value + " / " +seek_bar.getMax());
Toast.makeText(MainActivity.this,"SeekBar in stop",Toast.LENGTH_LONG).show();
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my layout.
<SeekBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/seekbar"
android:layout_above="#+id/bt_pes"
android:layout_alignParentStart="true"
android:layout_alignEnd="#+id/bt_mon"
android:max="5000" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/seekbarValue"
android:layout_above="#+id/seekbar"
android:layout_below="#+id/bt_caf"
android:layout_alignEnd="#+id/bt_pes"
android:layout_alignStart="#+id/bt_pes" />
When I run I get these error messages and the emulator says that unfortunatly your program has stopped.
04-27 16:26:18.615 2846-2846/prosis.guiaturistico E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: prosis.guiaturistico, PID: 2846
java.lang.RuntimeException: Unable to start activity ComponentInfo{prosis.guiaturistico/prosis.guiaturistico.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.SeekBar.getProgress()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at a android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.SeekBar.getProgress()' on a null object reference
at prosis.guiaturistico.MainActivity.seekbar(MainActivity.java:27)
at prosis.guiaturistico.MainActivity.onCreate(MainActivity.java:21)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
    
The problem is this line:
text_view.setText("Covered : " + seek_bar.getProgress() + " / " +seek_bar.getMax());
Both seek_bar.getProgress() and seek_bar.getMax() return primitive int values. The TextView.setText() method tends to assume primitive int values to be Resource IDs.
To avoid this, use String.valueof() to convert primitive values to a String representation. Or better yet, use a StringBuilder instead of plain String concatenation.

Android Studio can't find Resuorces

This is the error message which shows up when I run the apk on my virtual device.
05-03 13:00:03.652 2354-2354/de.hochrad.hochradapp I/art﹕ Not late-enabling -Xcheck:jni (already on)
05-03 13:00:05.966 2354-2354/de.hochrad.hochradapp D/AndroidRuntime﹕ Shutting down VM
05-03 13:00:05.970 2354-2354/de.hochrad.hochradapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: de.hochrad.hochradapp, PID: 2354
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.hochrad.hochradapp/de.hochrad.hochradapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:250)
at de.hochrad.hochradapp.MainActivity.onCreate(MainActivity.java:26)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
        at android.app.ActivityThread.access$800(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
05-03 13:00:08.238 2354-2354/de.hochrad.hochradapp I/Process﹕ Sending signal. PID: 2354 SIG: 9
Somehow it cannot find the required Resources.
I hope you can help me!!!
Thx for all answers!!!
package de.hochrad.hochradapp;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
ArrayAdapter<String> klassen_adapter;
Vertretungsplan vertretungsplan;
Spinner klassen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(null, "Laden...", Toast.LENGTH_SHORT).show();
klassen_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
klassen = (Spinner) findViewById(R.id.klassenspinner);
Thread downloadThread = new Thread() {
public void run() {
vertretungsplan = new Vertretungsplan("1");
runOnUiThread(new Runnable() {
#Override
public void run() {
if (vertretungsplan.Ex != null) {
klassen_adapter.add("Fehler!");
} else {
klassen_adapter.add("Wähle deine Klasse!");
for (Klassenvertretung s : vertretungsplan.Klassen) {
klassen_adapter.add(s.Bezeichnung);
}
}
}
});
}
};
downloadThread.start();
klassen.setAdapter(klassen_adapter);
klassen.setSelection(0);
klassen.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
package de.hochrad.hochradapp;
import java.util.ArrayList;
import java.util.List;
public class Klassenvertretung {
public String Bezeichnung;
public List<Vertretung> Vertretungen = new ArrayList<Vertretung>();
public void Hinzufügen(Vertretung neuesElement) {
Vertretungen.add(neuesElement);
}
}
package de.hochrad.hochradapp;
public class Vertretung {
public String Klasse;
public String Stunde;
public String Art;
public String Fach;
public String Raum;
public String stattFach;
public String stattRaum;
public String Informationen;
}
package de.hochrad.hochradapp;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Vertretungsplan {
public Vertretungsplan(String woche) {
Woche = woche;
Einlesen(woche);
}
public String Woche;
public Exception Ex;
public List<Klassenvertretung> Klassen = new ArrayList<Klassenvertretung>();
private void Hinzufügen(Klassenvertretung neuesElement) {
Klassen.add(neuesElement);
}
private void Einlesen(String woche) {
try {
for (int webseite = 1; webseite < 10000; webseite++) {
Klassenvertretung klassenvertretung = new Klassenvertretung();
String teilseite = "0000";
if (webseite < 10)
teilseite = teilseite + "0";
teilseite = teilseite + webseite;
Connection connection = Jsoup
.connect("www.gymnasium-hochrad.de/Vertretungsplan/Vertretungsplan_Internet/"
+ woche + "/w/w" + teilseite + ".htm");
Document doc = connection.get();
Element h2 = doc.select("h2").get(0);
klassenvertretung.Bezeichnung = h2.text();
Element table = doc.select("table").get(1);
Element[] elemente = table.select("tr").toArray(new Element[0]);
for (int i = 1; i < elemente.length; i++) {
Element[] tds = elemente[i].select("td").toArray(
new Element[0]);
Vertretung vertretung = new Vertretung();
vertretung.Klasse = tds[0].text();
vertretung.Stunde = tds[1].text();
vertretung.Art = tds[2].text();
vertretung.Fach = tds[3].text();
vertretung.Raum = tds[4].text();
vertretung.stattFach = tds[5].text();
vertretung.stattRaum = tds[6].text();
vertretung.Informationen = tds[7].text();
klassenvertretung.Hinzufügen(vertretung);
}
Hinzufügen(klassenvertretung);
}
} catch (IOException io) {
if (Klassen.size() == 0) {
Ex = io;
}
} finally {
}
}
}
okay here is my code. I am form germany and so lots of Names are german (i hope thats not a problem.
Maybe it helps.
I guess the error must be in the main activity in one of the toasts. But dont hesitate to look at the other lines.
A/c to logcat error your are getting null reference error. try to update this line
Toast.makeText(parent.getContext(),
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
with the following code
Toast.makeText(MainActivity.this,
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
You have not initialised your adapter namely "klassen_adapter" in your main activity. It's null and invoking any method on it will be null pointer exception

Categories

Resources