This question already has answers here:
Android - Activity Not Found Exception
(13 answers)
Closed 7 years ago.
So I want to move to a new class using an Intent (from ClassicMode class to Person class) in the check() function. I create a new class but when I get to the startActivity(intent) line I get an error but I can't figure out why.
I used Log.d to try and find the problem with no luck. I hope you can help me. I will put stack trace below, thank you.
ClassicMode.java
public class ClassicMode extends Activity implements AnimationListener{//מהמשחק עצמו
String pic;//תמונה של הדגל
Button answer1;//תשובות
Button answer2;
Button answer3;
Button answer4;
Button hint;
TextView guess;
TextView numOfGuess;
TextView score;
TextView scorenum;
MediaPlayer mpHint;
MediaPlayer mpNext;
MediaPlayer mpWrong;
Animation animationfadein;
Animation animationfadeout;
String fn;
Guesses G;
Score s;
Button [] b = new Button[4];
DatabaseHandler db = new DatabaseHandler(this);
List<String>WrongAnswers=new ArrayList<String>();
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
score =(TextView)findViewById(R.id.score);
scorenum =(TextView)findViewById(R.id.scorenum);
scorenum.setText(String.valueOf(s.score));
guess =(TextView)findViewById(R.id.guesses);
numOfGuess=(TextView)findViewById(R.id.numOfGuesses);
numOfGuess.setText(String.valueOf(Guesses.numOfGuesses));
hint =(Button)findViewById(R.id.hint);
hint.setOnClickListener(hintOnClickListener);
mpHint = MediaPlayer.create(this,R.raw.hint_sound);
mpNext = MediaPlayer.create(this, R.raw.next_flag);
mpWrong = MediaPlayer.create(this, R.raw.wrong_answer);
animationfadein = AnimationUtils.loadAnimation(this, R.anim.fade_in);
animationfadeout = AnimationUtils.loadAnimation(this, R.anim.fade_out);
Flags f = new Flags();
Random r = new Random();//הדגל שיבחר לשאלה
int num = r.nextInt(160);//Up
f = db.getFlag(num);//הצגת הדגל הרנדומלי שיצא
fn = f.getName().toString();
pic = f.getImage().toString();
pic_view(pic);//מעבר לפונקציה להשמת התמונה של הדגל במשחק
//מערך ארבע כפתורים כנגד ארבע תשובות
b[0] = (Button)findViewById(R.id.button1);
b[1] = (Button)findViewById(R.id.button2);
b[2] = (Button)findViewById(R.id.button3);
b[3] = (Button)findViewById(R.id.button4);
List<String>Answers=new ArrayList<String>();//מערך תשובות
Answers.add(f.getName().toString());//הוספת התשובה הנכונה
for(int i=1;i<4;i++)
{
num = r.nextInt(200);
String valToAdd1 = db.getFlag(num).getName().toString();
if(!Answers.contains(valToAdd1)){
WrongAnswers.add(valToAdd1);
Answers.add(valToAdd1);
}
}
/*num = r.nextInt(30);
Answers.add(db.getFlag(num).getName().toString());//הוספת 3 תשובות רנדומליות
num = r.nextInt(30);
Answers.add(db.getFlag(num).getName().toString());
num = r.nextInt(30);
Answers.add(db.getFlag(num).getName().toString());*/
Collections.shuffle(Answers);//ערבוב התשובות
for(int i=0;i<Answers.size();i++)
{
b[i].setText(Answers.get(i));//השמת התשובות מהמהערך למערך הכפתורים
b[i].startAnimation(animationfadein);
}
}//end of OnCreat
public boolean onOptionsItemSelected(MenuItem item){//actionbar activity
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
return true;
}
#SuppressLint("NewApi")
public void resetQuiz()
{
recreate();
}
private OnClickListener hintOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mpHint.start();
if(Guesses.numOfGuesses==1)
{
G.setNumOfGuesses(3);
finish();//כאשר מספר הניחושים
return;
}
else
G.numOfGuesses--;
int invisblecount=0;
for(int i=0;i<b.length;i++){
if(invisblecount<2){
String buttonText = b[i].getText().toString();
if(buttonText.equals(WrongAnswers.get(0))||buttonText.equals(WrongAnswers.get(1)))
{
b[i].startAnimation(animationfadeout);
b[i].setVisibility(View.INVISIBLE);
invisblecount++;
}
}
}
}
};
public void check(View v)
{
Log.d("yes", fn);
Button b = (Button)v;
String text = b.getText().toString();
if(text.equals(fn))
{
mpNext.start();
s.score+=5;
resetQuiz();
}
else
{
mpWrong.start();
if(Guesses.numOfGuesses==1)
{
Log.d("kkk", "inside if");
G.setNumOfGuesses(3);
//finish();//כאשר מספר הניחושים
Intent person = new Intent(ClassicMode.this,Person.class);
String extra = scorenum.getText().toString();
Log.d("lll", "Get Extra");
person.putExtra("Score", extra);
Log.d("sss", "new activ");
startActivity(person);
Log.d("dasdas", "inside Activ");
Toast toast = Toast.makeText(getApplicationContext(), "No more guesses :( Lets see what you made so far...", Toast.LENGTH_SHORT);
toast.show();
/*Intent person = new Intent(ClassicMode.this,Person.class);
String extra = scorenum.getText().toString();
person.putExtra("Score",extra);
startActivity(person);
Log.d("kkk", "inside person");*/
//return;
}
Guesses.numOfGuesses--;
if(s.score>0)
s.score-=5;
scorenum.setText(String.valueOf(s.score));
numOfGuess.setText(String.valueOf(Guesses.numOfGuesses));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
private void pic_view(String pic2) {
// TODO Auto-generated method stub
//גישה לדגל לפי שמו וייבוא התמונה
Log.d("Result from pic function " , pic2);
ImageView imageView = (ImageView)findViewById(R.id.imageView1);
String uri ="#drawable/";
uri += pic2;
int imageResource = getResources().getIdentifier(uri, pic2, getPackageName());//הצוות התמונה
Drawable res= getResources().getDrawable(imageResource);//ציור התמונה
imageView.setImageDrawable(res);
}
#Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Animatoin Stoped", Toast.LENGTH_SHORT).show();
}
#Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
}
Person.java
public class Person extends Activity{
EditText name;
Button ok;
TextView enter;
String score;
Map<String,String>Names=new HashMap<String,String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_person);
Intent intent = getIntent();
score = intent.getStringExtra(score);
name =(EditText)findViewById(R.id.namep);
ok =(Button)findViewById(R.id.send);
enter =(TextView)findViewById(R.id.entername);
ok.setOnClickListener(SendActionListener);
}
private OnClickListener SendActionListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Names.put(name.getText().toString(),score);
}
};
}
stacktrace:
04-17 17:45:46.030: D/kkk(5537): inside if
04-17 17:45:46.030: D/lll(5537): Get Extra
04-17 17:45:46.030: D/sss(5537): new activ
04-17 17:45:46.030: I/Timeline(5537): Timeline: Activity_launch_request id:com.example.flagsgame time:93135823
04-17 17:45:46.030: D/AndroidRuntime(5537): Shutting down VM
04-17 17:45:46.030: W/dalvikvm(5537): threadid=1: thread exiting with uncaught exception (group=0x4162cdb8)
04-17 17:45:46.050: E/AndroidRuntime(5537): FATAL EXCEPTION: main
04-17 17:45:46.050: E/AndroidRuntime(5537): Process: com.example.flagsgame, PID: 5537
04-17 17:45:46.050: E/AndroidRuntime(5537): java.lang.IllegalStateException: Could not execute method of the activity
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.view.View$1.onClick(View.java:3830)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.view.View.performClick(View.java:4445)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.view.View$PerformClick.run(View.java:18446)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.os.Handler.handleCallback(Handler.java:733)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.os.Handler.dispatchMessage(Handler.java:95)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.os.Looper.loop(Looper.java:136)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.app.ActivityThread.main(ActivityThread.java:5146)
04-17 17:45:46.050: E/AndroidRuntime(5537): at java.lang.reflect.Method.invokeNative(Native Method)
04-17 17:45:46.050: E/AndroidRuntime(5537): at java.lang.reflect.Method.invoke(Method.java:515)
04-17 17:45:46.050: E/AndroidRuntime(5537): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
04-17 17:45:46.050: E/AndroidRuntime(5537): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
04-17 17:45:46.050: E/AndroidRuntime(5537): at dalvik.system.NativeStart.main(Native Method)
04-17 17:45:46.050: E/AndroidRuntime(5537): Caused by: java.lang.reflect.InvocationTargetException
04-17 17:45:46.050: E/AndroidRuntime(5537): at java.lang.reflect.Method.invokeNative(Native Method)
04-17 17:45:46.050: E/AndroidRuntime(5537): at java.lang.reflect.Method.invoke(Method.java:515)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.view.View$1.onClick(View.java:3825)
04-17 17:45:46.050: E/AndroidRuntime(5537): ... 11 more
04-17 17:45:46.050: E/AndroidRuntime(5537): Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.flagsgame/com.example.flagsgame.Person}; have you declared this activity in your AndroidManifest.xml?
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1628)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1424)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.app.Activity.startActivityForResult(Activity.java:3424)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.app.Activity.startActivityForResult(Activity.java:3385)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.app.Activity.startActivity(Activity.java:3627)
04-17 17:45:46.050: E/AndroidRuntime(5537): at android.app.Activity.startActivity(Activity.java:3595)
04-17 17:45:46.050: E/AndroidRuntime(5537): at com.example.flagsgame.ClassicMode.check(ClassicMode.java:188)
04-17 17:45:46.050: E/AndroidRuntime(5537): ... 14 more
The most likely problem is that the Activity is not declared in AndroidManifest.xml. Your error says:
have you declared this activity in your AndroidManifest.xml?
You should first do that.
From this answer on how to do it:
You put it inside of your application element, like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="your.package.name">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".Activity1" android:label="#string/app_name"></activity>
<activity android:name=".Activity2"></activity>
</application>
<uses-sdk android:minSdkVersion="4" />
</manifest>
Where .Activity2 is your second activity.
Your intent isn't declared in the Manifest file.
Related
I was using an integer for the money factor in this little test app but I realized that long was more appropriate and I changed the code so that money is a long instead of an int and I changed SharedPreferences appropriately as well, however it does not work wheras it did when I used int. Thank you for the help!
public class Home extends AppCompatActivity {
SharedPreferences pref;
SharedPreferences.Editor editor;
Intent intent;
TextView home_money_view;
long money; // this is the variable that is causing problems
int initial;
final long TEST = (long)-1;
int gold_pieces;
int gold_price = 50;
TimerTask timerTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
home_money_view = (TextView) findViewById(R.id.home_money_view)
pref = getApplicationContext().getSharedPreferences("MY_PREFS", MODE_PRIVATE);
editor = pref.edit();
money = pref.getLong("temp_money",Long.MIN_VALUE); // get value
if (money==Long.MIN_VALUE){
money=0;
}
gold_pieces = pref.getInt("temp_gold",-1);
if (gold_pieces==-1){
gold_pieces=0;
}
initial = pref.getInt("initial",0);
money+=initial;
editor.putInt("initial",0);
editor.commit();
home_money_view = (TextView) findViewById(R.id.home_money_view);
home_money_view.setText(money+"");
editor.commit();
}
public void backToSplash(View view){
intent = new Intent(Home.this,BusinessSelector.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
public void goToSecondView(View view){
long temp_money = money;
editor.putLong("temp_money",temp_money); // set value
int temp_gold = gold_pieces;
editor.putInt("temp_gold",temp_gold);
editor.commit();
intent = new Intent(Home.this,SecondView.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
public void goToOtherView(View view) {
long temp_money = money;
editor.putLong("temp_money",temp_money); // set value
int temp_gold = gold_pieces;
editor.putInt("temp_gold", temp_gold);
editor.commit();
intent = new Intent(Home.this, Next.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
Logcat:
04-13 19:01:03.675 12896-12896/com.exampleryancocuzzo.ryan.markettycoon E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exampleryancocuzzo.ryan.markettycoon/com.exampleryancocuzzo.ryan.markettycoon.Home}: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
at android.app.SharedPreferencesImpl.getLong(SharedPreferencesImpl.java:228)
at com.exampleryancocuzzo.ryan.markettycoon.Home.onCreate(Home.java:56)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText txtUserName = (EditText)findViewById(R.id.editText1);
final EditText txtPassword = (EditText)findViewById(R.id.editText2);
Button btnLogin = (Button)findViewById(R.id.button1);
btnLogin.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String username = txtUserName.getText().toString();
String password = txtPassword.getText().toString();
String foo = new String("131031001");
String foo2 = new String("131031002");
String foo3 = new String("131031003");
String foo4 = new String("131031004");
String foo5 = new String("131031005");
try{
if(username.length() > 0 && password.length() >0) {
DBUserAdapter dbUser = new DBUserAdapter(MainActivity.this);
dbUser.open();
dbUser.AddUser();
if(dbUser.Login(username, password))
{
Toast.makeText(MainActivity.this,"Successfully Logged In", Toast.LENGTH_LONG).show();
if(username.equals(foo))
{
Intent nextActivity2 = new Intent(getApplicationContext(),SecondActivity.class);
nextActivity2.putExtra("Second",username);
startActivity(nextActivity2);
}
else if(username.equals(foo2)) {
Intent nextActivity3 = new Intent(getBaseContext(),ThirdActivity.class);
nextActivity3.putExtra("Third",username);
startActivity(nextActivity3);
}
else if(username.equals(foo3))
{
Intent nextActivity4 = new Intent(getBaseContext(),FourthActivity.class);
nextActivity4.putExtra("Fourth",username);
startActivity(nextActivity4);
}
else if(username.equals(foo4)) {
Intent nextActivity5 = new Intent(getBaseContext(),FifthActivity.class);
nextActivity5.putExtra("Fifth",username);
startActivity(nextActivity5);
}
else if(username.equals(foo5)) {
Intent nextActivity6 = new Intent(getBaseContext(),SixthActivity.class);
nextActivity6.putExtra("Sixth",username);
startActivity(nextActivity6);
}
else {
Toast.makeText(MainActivity.this,"Result does not exist! Try later!!", Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(MainActivity.this,"Invalid Username/Password", Toast.LENGTH_LONG).show();
}
dbUser.close();
}
}catch(Exception e) {
Toast.makeText(MainActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
Button btreg = (Button)findViewById(R.id.button2);
btreg.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Intent nextActivity = new Intent(getApplicationContext(),Register.class);
startActivity(nextActivity);
}
});
}
}
SecondActivity.java
public class SecondActivity extends Activity {
Intent intent = getIntent();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
}
}
All other activities are coded similar to the above.
Here is my logcat.
10-28 14:53:10.688: E/AndroidRuntime(1196): Process: com.skcetresults, PID: 1196
10-28 14:53:10.688: E/AndroidRuntime(1196): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.skcetresults/com.skcetresults.SecondActivity}: java.lang.NullPointerException
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.access$700(ActivityThread.java:135)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.os.Handler.dispatchMessage(Handler.java:102)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.os.Looper.loop(Looper.java:137)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.main(ActivityThread.java:4998)
10-28 14:53:10.688: E/AndroidRuntime(1196): at java.lang.reflect.Method.invokeNative(Native Method)
10-28 14:53:10.688: E/AndroidRuntime(1196): at java.lang.reflect.Method.invoke(Method.java:515)
10-28 14:53:10.688: E/AndroidRuntime(1196): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
10-28 14:53:10.688: E/AndroidRuntime(1196): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
10-28 14:53:10.688: E/AndroidRuntime(1196): at dalvik.system.NativeStart.main(Native Method)
10-28 14:53:10.688: E/AndroidRuntime(1196): Caused by: java.lang.NullPointerException
10-28 14:53:10.688: E/AndroidRuntime(1196): at com.skcetresults.SecondActivity.onCreate(SecondActivity.java:15)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.Activity.performCreate(Activity.java:5243)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
10-28 14:53:10.688: E/AndroidRuntime(1196): ... 11 more
With just two intents the code worked fine, but when I'm comparing the value with strings, the app crashes, I don't know where the bug is.
Instead of getBaseContext() and getApplicationContext(), use MainActivity.this as context, will work everywhere.
You should put it like this
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
Intent i = getIntent();
}
}
If the extra data are strings you can get it like this:
String nameString = i.getStringExtra("nameExtra");
You can't use getIntent() before onCreate(), there's simply no Intent available at that point.
In your code, I suspect that you are trying to get StringExtras from Intent, But as intent is null, it is throwing NullPointerException.
In your Second Activity you can use getIntent() in onCreate() method.
public class SecondActivity extends Activity {
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
intent = getIntent();
String userName = intent.getStringExtra("Second");
...
}
}
Use little pieces of code checking, to ensure your intent behaves properly. For example, you could surround your getIntent code with an if statement. For which proper method to call, you have to wander around a bit, as this depends on what you want your app to do. Fortunately, Eclipse delivers you all the related documentation, when you write down some piece of Android resources, e.g. Intent.
I'm working on an android app that is supposed to load the gallery and grab an image and display it in an image view. I had it working but changed from Activities to Fragments to use the ViewPager and since then it has been crashing. I believe it is because I'm using a method intended for Activities on Fragments.
public class Fragment_1 extends Fragment {
private static int RESULT_LOAD_IMAGE = 1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Button buttonLoadImage = (Button) getView().findViewById(
R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Log.v("ButtonPress: ", "Pressed");
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Log.v("ButtonPress: ", "intent=" + i);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
return inflater.inflate(R.layout.fragment_1, container, false);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) getView().findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
The error I'm receiving is:
05-05 22:17:59.214: E/AndroidRuntime(32610): FATAL EXCEPTION: main
05-05 22:17:59.214: E/AndroidRuntime(32610): Process: com.example.hashtagged, PID: 32610
05-05 22:17:59.214: E/AndroidRuntime(32610): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.hashtagged/com.example.hashtagged.Fragment_1}: java.lang.ClassCastException: com.example.hashtagged.Fragment_1 cannot be cast to android.app.Activity
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2131)
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.app.ActivityThread.access$800(ActivityThread.java:145)
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.os.Handler.dispatchMessage(Handler.java:102)
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.os.Looper.loop(Looper.java:136)
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.app.ActivityThread.main(ActivityThread.java:5142)
05-05 22:17:59.214: E/AndroidRuntime(32610): at java.lang.reflect.Method.invokeNative(Native Method)
05-05 22:17:59.214: E/AndroidRuntime(32610): at java.lang.reflect.Method.invoke(Method.java:515)
05-05 22:17:59.214: E/AndroidRuntime(32610): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
05-05 22:17:59.214: E/AndroidRuntime(32610): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
05-05 22:17:59.214: E/AndroidRuntime(32610): at dalvik.system.NativeStart.main(Native Method)
05-05 22:17:59.214: E/AndroidRuntime(32610): Caused by: java.lang.ClassCastException: com.example.hashtagged.Fragment_1 cannot be cast to android.app.Activity
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
05-05 22:17:59.214: E/AndroidRuntime(32610): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2122)
05-05 22:17:59.214: E/AndroidRuntime(32610): ... 11 more
Try inflate the View first on OnCreateView, like this:
private Button mButtonLoadImage;
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_1, container, false);
mButtonLoadImage = (Button) view.findViewById(R.id.buttonLoadPicture);
return view;
}
And set onClickListener inside onViewCreated:
#Override public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mButtonLoadImage.setOnClickListener(onClickLoad);
}
//Good practice
private View.OnClickListener onClickLoad = new View.OnClickListener() {
#Override public void onClick(View view) {
//TODO action here
}
};
You are using onActivityResult() method of the activity class in your Fragment class. That is why you are getting this error. onActivityResult should be defined in your activity class of the your fragment class not on the fragment itself. See this link for how to do it.here
Hello I am just getting started in Android. Help please, read all posts about this, nothing cant help. Tried all combinations naming activities in manifest. This app showing lifecycle of the app.
Log
02-11 01:07:36.538: W/dalvikvm(20921): threadid=1: thread exiting with uncaught exception (group=0x40ab6228)
02-11 01:07:36.558: E/AndroidRuntime(20921): FATAL EXCEPTION: main
02-11 01:07:36.558: E/AndroidRuntime(20921): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.lab1/com.example.lab1.MainActivity}: java.lang.NullPointerException
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2240)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.app.ActivityThread.access$600(ActivityThread.java:139)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1262)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.os.Handler.dispatchMessage(Handler.java:99)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.os.Looper.loop(Looper.java:156)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.app.ActivityThread.main(ActivityThread.java:4977)
02-11 01:07:36.558: E/AndroidRuntime(20921): at java.lang.reflect.Method.invokeNative(Native Method)
02-11 01:07:36.558: E/AndroidRuntime(20921): at java.lang.reflect.Method.invoke(Method.java:511)
02-11 01:07:36.558: E/AndroidRuntime(20921): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
02-11 01:07:36.558: E/AndroidRuntime(20921): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
02-11 01:07:36.558: E/AndroidRuntime(20921): at dalvik.system.NativeStart.main(Native Method)
02-11 01:07:36.558: E/AndroidRuntime(20921): Caused by: java.lang.NullPointerException
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.content.ContextWrapper.getResources(ContextWrapper.java:81)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.view.View.<init>(View.java:2723)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.view.View.<init>(View.java:2771)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.widget.TextView.<init>(TextView.java:504)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.widget.TextView.<init>(TextView.java:494)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.widget.TextView.<init>(TextView.java:489)
02-11 01:07:36.558: E/AndroidRuntime(20921): at com.example.lab1.MainActivity.<init>(MainActivity.java:30)
02-11 01:07:36.558: E/AndroidRuntime(20921): at java.lang.Class.newInstanceImpl(Native Method)
02-11 01:07:36.558: E/AndroidRuntime(20921): at java.lang.Class.newInstance(Class.java:1319)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.app.Instrumentation.newActivity(Instrumentation.java:1039)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
02-11 01:07:36.558: E/AndroidRuntime(20921): ... 11 more
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lab1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="ActivityTwo"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
MainActivity
package com.example.lab1;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String RESTART_KEY = "restart";
private static final String RESUME_KEY = "resume";
private static final String START_KEY = "start";
private static final String CREATE_KEY = "create";
// String for LogCat documentation
private final static String TAG = "Lab-ActivityOne";
// Lifecycle counters
// TODO:
int mCreate=0;
int mResume=0;
int mRestart=0;
int mStart=0;
TextView textView1 = new TextView(this);
TextView textView2 = new TextView(this);
TextView textView3 = new TextView(this);
TextView textView4 = new TextView(this);
// TODO: Create variables for each of the TextViews, called
// mTvCreate, etc.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
// TODO: Assign the appropriate TextViews to the TextView variables
// Hint: Access the TextView by calling Activity's findViewById()
textView1 = (TextView) findViewById(R.id.create);
textView2 = (TextView) findViewById(R.id.start);
textView3 = (TextView) findViewById(R.id.resume);
textView4 = (TextView) findViewById(R.id.restart);
Button launchActivityTwoButton = new Button(this);
launchActivityTwoButton = (Button) findViewById(R.id.bLaunchActivityTwo);
launchActivityTwoButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view)
{
// TODO:
// Launch Activity Two
// Hint: use Context's startActivity() method
// Create an intent stating which Activity you would like to start
// Launch the Activity using the intent
Intent myIntent=new Intent(view.getContext(),ActivityTwo.class);
startActivity(myIntent);
}
});
// Check for previously saved state
if (savedInstanceState != null) {
mCreate=savedInstanceState.getInt(CREATE_KEY);
mResume=savedInstanceState.getInt(RESUME_KEY);
mRestart=savedInstanceState.getInt(RESTART_KEY);
mStart=savedInstanceState.getInt(START_KEY);
}
// TODO: Emit LogCat message
Log.i(TAG,"OnCreate");
// TODO:
mCreate++;
//displayCounts();
}
// Lifecycle callback overrides
#Override
public void onStart() {
super.onStart();
// TODO: Emit LogCat message
Log.i(TAG,"OnStart");
// TODO:
mStart++;
//displayCounts();
}
#Override
public void onResume() {
super.onResume();
// TODO: Emit LogCat message
Log.i(TAG,"OnResume");
// TODO:
mResume++;
displayCounts();
}
#Override
public void onPause() {
super.onPause();
// TODO: Emit LogCat message
Log.i(TAG,"OnPause");
}
#Override
public void onStop() {
super.onStop();
// TODO: Emit LogCat message
Log.i(TAG,"OnStop");
}
#Override
public void onRestart() {
super.onRestart();
// TODO: Emit LogCat message
Log.i(TAG,"OnRestart");
// TODO:
mRestart++;
displayCounts();
}
#Override
public void onDestroy() {
super.onDestroy();
// TODO: Emit LogCat message
Log.i(TAG,"OnDestroy");
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// TODO:
// Save state information with a collection of key-value pairs
// 4 lines of code, one for every count variable
savedInstanceState.putInt(RESTART_KEY,mRestart);
savedInstanceState.putInt(RESUME_KEY,mResume);
savedInstanceState.putInt(START_KEY,mStart);
savedInstanceState.putInt(CREATE_KEY,mCreate);
}
// Updates the displayed counters
public void displayCounts() {
textView1.setText("onCreate() calls: " + mCreate);
textView2.setText("onStart() calls: " + mStart);
textView3.setText("onResume() calls: " + mResume);
textView4.setText("onRestart() calls: " + mRestart);
}
}
ActivityTwo
package com.example.lab1;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ActivityTwo extends Activity {
private static final String RESTART_KEY = "restart";
private static final String RESUME_KEY = "resume";
private static final String START_KEY = "start";
private static final String CREATE_KEY = "create";
// String for LogCat documentation
private final static String TAG = "Lab-ActivityTwo";
// Lifecycle counters
// TODO:
int mCreate=0;
int mResume=0;
int mRestart=0;
int mStart=0;
TextView textView1 = new TextView(this);
TextView textView2 = new TextView(this);
TextView textView3 = new TextView(this);
TextView textView4 = new TextView(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
textView1 = (TextView) findViewById(R.id.create);
textView2 = (TextView) findViewById(R.id.start);
textView3 = (TextView) findViewById(R.id.resume);
textView4 = (TextView) findViewById(R.id.restart);
Button closeButton = new Button(this);
closeButton= (Button) findViewById(R.id.bClose);
closeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
// Check for previously saved state
if (savedInstanceState != null) {
// TODO:
// Restore value of counters from saved state
// Only need 4 lines of code, one for every count variable
mCreate=savedInstanceState.getInt(CREATE_KEY);
mResume=savedInstanceState.getInt(RESUME_KEY);
mRestart=savedInstanceState.getInt(RESTART_KEY);
mStart=savedInstanceState.getInt(START_KEY);
}
// TODO: Emit LogCat message
// TODO: Emit LogCat message
Log.i(TAG,"OnCreate");
// TODO:
mCreate++;
displayCounts();
// TODO:
// Update the appropriate count variable
// Update the user interface via the displayCounts() method
}
// Lifecycle callback methods overrides
#Override
public void onStart() {
super.onStart();
// TODO: Emit LogCat message
// TODO:
// Update the appropriate count variable
// Update the user interface
// TODO: Emit LogCat message
Log.i(TAG,"OnStart");
// TODO:
mStart++;
displayCounts();
}
#Override
public void onResume() {
super.onResume();
// TODO: Emit LogCat message
// TODO:
// Update the appropriate count variable
// Update the user interface
Log.i(TAG,"OnResume");
// TODO:
mResume++;
displayCounts();
}
#Override
public void onPause() {
super.onPause();
// TODO: Emit LogCat message
Log.i(TAG,"OnPause");
}
#Override
public void onStop() {
super.onStop();
// TODO: Emit LogCat message
Log.i(TAG,"OnStop");
}
#Override
public void onRestart() {
super.onRestart();
// TODO: Emit LogCat message
Log.i(TAG,"OnRestart");
// TODO:
mRestart++;
displayCounts();
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG,"OnDestroy");
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// TODO:
savedInstanceState.putInt(RESTART_KEY,mRestart);
savedInstanceState.putInt(RESUME_KEY,mResume);
savedInstanceState.putInt(START_KEY,mStart);
savedInstanceState.putInt(CREATE_KEY,mCreate);
}
// Updates the displayed counters
public void displayCounts() {
textView1.setText("onCreate() calls: " + mCreate);
textView2.setText("onStart() calls: " + mStart);
textView3.setText("onResume() calls: " + mResume);
textView4.setText("onRestart() calls: " + mRestart);
}
}
I am a bit new to this myself so I could be talking rubbish....
I would get rid of the member initialisation on textView1 -> textView4 and move it until after the setContentView. Next I would place a breakpoint on super.OnCreate and see if it gets there. If you do single step every line you can until you see the null pointer.
I'm trying to work on Google Analytics for Androi. I get the message, and I'm following the advanced configuration of Android Analytics in Google Android SDK.
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.secondapp/com.example.secondapp.MainActivity}:
java.lang.NullPointerException
And I get this error:
01-02 15:39:38.410: D/AndroidRuntime(1338): Shutting down VM
01-02 15:39:38.410: W/dalvikvm(1338): threadid=1: thread exiting with uncaught exception (group=0xb1ab7ba8)
01-02 15:39:38.420: E/AndroidRuntime(1338): FATAL EXCEPTION: main
01-02 15:39:38.420: E/AndroidRuntime(1338): Process: com.example.secondapp, PID: 1338
01-02 15:39:38.420: E/AndroidRuntime(1338): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.secondapp/com.example.secondapp.MainActivity}: java.lang.NullPointerException
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.ActivityThread.access$800(ActivityThread.java:135)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.os.Handler.dispatchMessage(Handler.java:102)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.os.Looper.loop(Looper.java:136)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.ActivityThread.main(ActivityThread.java:5017)
01-02 15:39:38.420: E/AndroidRuntime(1338): at java.lang.reflect.Method.invokeNative(Native Method)
01-02 15:39:38.420: E/AndroidRuntime(1338): at java.lang.reflect.Method.invoke(Method.java:515)
01-02 15:39:38.420: E/AndroidRuntime(1338): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-02 15:39:38.420: E/AndroidRuntime(1338): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-02 15:39:38.420: E/AndroidRuntime(1338): at dalvik.system.NativeStart.main(Native Method)
01-02 15:39:38.420: E/AndroidRuntime(1338): Caused by: java.lang.NullPointerException
01-02 15:39:38.420: E/AndroidRuntime(1338): at com.example.secondapp.MainActivity.onCreate(MainActivity.java:24)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.Activity.performCreate(Activity.java:5231)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
01-02 15:39:38.420: E/AndroidRuntime(1338): ... 11 more
Here is my code for SecondAppApplication, which has similarities to the android docs:
public class SecondAppApplication extends Application {
private static GoogleAnalytics mGa;
private static Tracker mTracker;
private static final String GA_PROPERTY_ID = "UA-XXXXXXXX-1";
private static final int GA_DISPATCH_PERIOD = 30;
private static final boolean GA_IS_DRY_RUN = false;
private static final LogLevel GA_LOG_VERBOSITY = LogLevel.INFO;
private static final String TRACKING_PREF_KEY = "trackingPreferences";
#SuppressWarnings("deprecation")
private void initializeGa() {
mGa = GoogleAnalytics.getInstance(this);
mTracker = mGa.getTracker(GA_PROPERTY_ID);
GAServiceManager.getInstance().setLocalDispatchPeriod(GA_DISPATCH_PERIOD);
mGa.setDryRun(GA_IS_DRY_RUN);
mGa.getLogger().setLogLevel(GA_LOG_VERBOSITY);
SharedPreferences userPrefs = PreferenceManager.getDefaultSharedPreferences(this);
userPrefs.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(TRACKING_PREF_KEY)) {
GoogleAnalytics.getInstance(getApplicationContext()).setAppOptOut(sharedPreferences.getBoolean(key, false));
}
}
});
}
#Override
public void onCreate() {
super.onCreate();
initializeGa();
}
public static Tracker getGaTracker() {
return mTracker;
}
public static GoogleAnalytics getGaInstance() {
return mGa;
}
}
Here is my MainActivity class:
public class MainActivity extends Activity {
public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
private static final String SCREEN_LABEL = "Main Screen";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SecondAppApplication.getGaTracker().set(Fields.SCREEN_NAME,SCREEN_LABEL);
setContentView(R.layout.main);
}
#Override
public void onStart() {
super.onStart();
SecondAppApplication.getGaTracker().send(MapBuilder.createAppView().build());
}
#Override
public void onStop() {
super.onStop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void openSearch() {
}
public void openSettings() {
}
public void sendMessage(View view) {
Intent intent = new Intent(this,DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
Why does java.lang.NullPointerException exists, and/or how would I solve this?
Do I need to declare initializeGa() again inside MainActivity or AndroidManifest.xml?
It looks to me like:
SecondAppApplication.getGaTracker().set(Fields.SCREEN_NAME,SCREEN_LABEL);
Is probably calling the set method on a null object, because your accessing statically without initializing it first. This almost looks like you were trying to do a singleton or something...
I would change your code to:
public static Tracker getGaTracker() {
if(mTracker ==null) {
initialize();
}
return mTracker;
}
The problem of course being that since you're doing this statically you wont have a context to pass.... I think you may need to reorganize the project a bit.
Check out this:
Android: Persist object across activities
I found out that the AndroidManifest.xml application should contain the correct android.name.
In this case, android.name="com.example.secondapplication.SecondAppApplication"