I am trying to run an app using Android Studio 3.4.1, but the application crashes when I try to debug or run it.
I've encountered the Unable to start activity ComponentInfo error once already, but on a project that used Kotlin (this project is using Java), and with a different exception. I've tried editing the manifest, modifying activities and changing all of the images in the mipmap folders to the drawable folders, but none of that worked.
Here is my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.testapp">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:ignore="AllowBackup,GoogleAppIndexingWarning">
<activity
android:name=".Main2Activity"
android:label="#string/title_activity_main2" />
<activity
android:name=".NotificationsActivity"
android:label="#string/title_notifications" />
<activity
android:name=".DashboardActivity"
android:label="#string/title_dashboard" />
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.testapp.DashboardActivity" />
<activity
android:name=".BaseActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
My BaseActivity.java:
package com.example.testapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
public class BaseActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
protected BottomNavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getContentViewId()); //References this line in the logs
navigationView = findViewById(R.id.nav_view);
navigationView.setOnNavigationItemSelectedListener(this);
}
#Override
protected void onStart() {
super.onStart();
updateNavigationBarState();
}
// Remove inter-activity transition to avoid screen tossing on tapping bottom navigation items
#Override
public void onPause() {
super.onPause();
overridePendingTransition(0, 0);
}
#Override
public boolean onNavigationItemSelected(#NonNull final MenuItem item) {
navigationView.postDelayed(new Runnable() {
#Override
public void run() {
int itemId = item.getItemId();
if (itemId == R.id.navigation_home) {
BaseActivity.this.startActivity(new Intent(BaseActivity.this, BaseActivity.class));
} else if (itemId == R.id.navigation_dashboard) {
BaseActivity.this.startActivity(new Intent(BaseActivity.this, DashboardActivity.class));
} else if (itemId == R.id.navigation_notifications) {
BaseActivity.this.startActivity(new Intent(BaseActivity.this, NotificationsActivity.class));
}
BaseActivity.this.finish();
}
}, 300);
return true;
}
private void updateNavigationBarState(){
int actionId = getNavigationMenuItemId();
selectBottomNavigationBarItem(actionId);
}
void selectBottomNavigationBarItem(int itemId) {
Menu menu = navigationView.getMenu();
for (int i = 0, size = menu.size(); i < size; i++) {
MenuItem item = menu.getItem(i);
boolean shouldBeChecked = item.getItemId() == itemId;
if (shouldBeChecked) {
item.setChecked(true);
break;
}
}
}
int getContentViewId() {
return 0;
}
int getNavigationMenuItemId() {
return 0;
}
}
And my debugging log:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.testapp, PID: 10261
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testapp/com.example.testapp.BaseActivity}: android.content.res.Resources$NotFoundException: Resource ID #0x0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2827)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2902)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1603)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:169)
at android.app.ActivityThread.main(ActivityThread.java:6578)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x0
at android.content.res.ResourcesImpl.getValue(ResourcesImpl.java:204)
at android.content.res.Resources.loadXmlResourceParser(Resources.java:2133)
at android.content.res.Resources.getLayout(Resources.java:1142)
at android.view.LayoutInflater.inflate(LayoutInflater.java:421)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.testapp.BaseActivity.onCreate(BaseActivity.java:18)
at android.app.Activity.performCreate(Activity.java:7016)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2780)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2902)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1603)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:169)
at android.app.ActivityThread.main(ActivityThread.java:6578)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
The app was supposed to work, but after modifying the .javas, it started giving this error no matter what I did. I've seen some questions that had similar results, but none of them actually helped me.
Try changing
setContentView(getContentViewId());
to
setContentView(R.layout.activity_base);
The error :
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x0
means that the resource can't be found and since it is pointing to setContentView, it means that getContentViewId() could not be found.
Related
I tried to use a media recorder, but it keeps giving me errors, I have added permission request and this is my manifest. When I goes to Logcat it says:
2020-04-23 18:23:46.754 12665-12665/com.example.soundmedi E/MediaRecorder: stop called in an invalid state: 4
2020-04-23 18:23:46.754 12665-12665/com.example.soundmedi D/AndroidRuntime: Shutting down VM
2020-04-23 18:23:46.767 12665-12665/com.example.soundmedi E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.soundmedi, PID: 12665
java.lang.IllegalStateException
at android.media.MediaRecorder.stop(Native Method)
at com.example.soundmedi.Activity4$1.onClick(Activity4.java:69)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.soundmedi">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<application
android:allowBackup="true"
android:requestLegacyExternalStorage="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Activity5"></activity>
<activity android:name=".Activity4" />
<activity android:name=".Activity3" />
<activity android:name=".Activity2" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
package com.example.soundmedi;
import android.Manifest;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import java.io.File;
import java.io.IOException;
public class Activity4 extends AppCompatActivity {
private Button record, stop;
private MediaRecorder mediaRecorder;
private String outputFile;
private boolean permissionToRecordAccepted = false;
private String [] permissions = {Manifest.permission.RECORD_AUDIO};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_4);
record = (Button) findViewById(R.id.record);
stop = (Button) findViewById(R.id.stop);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, getPackageManager().PERMISSION_GRANTED);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, getPackageManager().PERMISSION_GRANTED);
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File dir = new File(path + "/soundmedi/");
outputFile = String.valueOf(dir);/**Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";*/
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setOutputFile("first.3gp");
mediaRecorder.setOutputFile("/0/Download/soundmedi/");
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null != mediaRecorder) {
try{
mediaRecorder.stop();
mediaRecorder.reset();
mediaRecorder.release();
mediaRecorder = null;
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_LONG).show();
} catch(RuntimeException stopException) {
}
}
}
});
record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();// make something
}
Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
record.setEnabled(false);
//recording for 10s
/**final Handler handler = new Handler();
final boolean b = handler.postDelayed(new Runnable() {
#Override
public void run() {
}
}, 10000);*/
}
});
}
}
enter image description here
I am using a simple code to open up a camera on opencv the app works fine on LG G Pro but crashes on samsung galaxy S4
Please Note that this activity is called via another activity through intent.
GameActivity.java
public class GameActivity extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2 {
public static final String MY_TAG = "MY_CUSTOM_MESSAGE";
private JavaCameraView javaCameraView;
private BaseLoaderCallback baseLoaderCallback= new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status){
case LoaderCallbackInterface.SUCCESS:
{
Log.i(MY_TAG, "OPENCV Loaded");
javaCameraView.enableView();
break;
}
default:
super.onManagerConnected(status);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Log.i(MY_TAG, "onCreate Act 2");
javaCameraView=(JavaCameraView)findViewById(R.id.MyJavaCam);
javaCameraView.setVisibility(SurfaceView.VISIBLE);
javaCameraView.setCvCameraViewListener(this);
}
#Override
protected void onResume() {
super.onResume();
Log.i(MY_TAG, "onResume Act 2");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_11, this, baseLoaderCallback);
Log.i(MY_TAG, "onResume Act 2 done resuming");
}
#Override
protected void onPause() {
super.onPause();
Log.i(MY_TAG, "onPause Act 2");
}
#Override
public void onCameraViewStarted(int width, int height) {
}
#Override
public void onCameraViewStopped() {
}
#Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
return inputFrame.rgba();
}
#Override
protected void onDestroy() {
super.onDestroy();
if(javaCameraView != null)
{
javaCameraView.disableView();
}
}
}
content_game.xml
<org.opencv.android.JavaCameraView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="gone"
android:id="#+id/MyJavaCam"
opencv:show_fps="true"
opencv:camera_id="any"
/>
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar"
android:screenOrientation="landscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".GameActivity"
android:label="#string/title_activity_game"
android:theme="#style/AppTheme.NoActionBar"
android:screenOrientation="landscape">
<intent-filter>
<action android:name="com.roundcube.gamewithserver.GameActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
Logcat
07-10 04:13:48.107 11233-11233/com.roundcube.gamewithserver E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.roundcube.gamewithserver, PID: 11233
java.lang.RuntimeException: Unable to resume activity {com.roundcube.gamewithserver/com.roundcube.gamewithserver.GameActivity}: java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=org.opencv.engine.BIND }
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3403)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3434)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2772)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
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:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
Caused by: java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=org.opencv.engine.BIND }
at android.app.ContextImpl.validateServiceIntent(ContextImpl.java:2052)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:2160)
at android.app.ContextImpl.bindService(ContextImpl.java:2138)
at android.content.ContextWrapper.bindService(ContextWrapper.java:559)
at org.opencv.android.AsyncServiceHelper.initOpenCV(AsyncServiceHelper.java:24)
at org.opencv.android.OpenCVLoader.initAsync(OpenCVLoader.java:89)
at com.roundcube.gamewithserver.GameActivity.onResume(GameActivity.java:85)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1255)
at android.app.Activity.performResume(Activity.java:6412)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3392)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3434)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2772)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
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:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
On using Logs i figured out that problem in this function call
`OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_11, this, baseLoaderCallback);
Please help me find a solution to this thank you.
This question already has answers here:
android.content.ActivityNotFoundException: Unable to find explicit activity class
(9 answers)
Closed 6 years ago.
I am creating an app and added a new Resource Layout File. In Android Studio Preview, I am able to preview the file. The problem is that, While Calling that Layout, the app is getting crashed.
details_main_xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
DetailsMain.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class DetailsMain extends AppCompatActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details_main);
}
}
I am calling this Activity fron Navigation bar Menu Item. The code is as follows.
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_details) {
Intent in = new Intent(getApplicationContext(),DetailsMain.class);
startActivity(in);
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
What Mistake had I made?
LogCat
E/AndroidRuntime: FATAL EXCEPTION: main
Process: switchmode.new.switch, PID: 3156
android.content.ActivityNotFoundException: Unable to find explicit
activity class
{switchmode.new.switch/switchmode.new.switch.DetailsMain}; have you
declared this activity in your AndroidManifest.xml?
at
android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1777)
at
android.app.Instrumentation.execStartActivity(Instrumentation.java:1501)
at android.app.Activity.startActivityForResult(Activity.java:3745)
at android.app.Activity.startActivityForResult(Activity.java:3706)
at
android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:843)
at android.app.Activity.startActivity(Activity.java:4016)
at android.app.Activity.startActivity(Activity.java:3984)
at
switchmode.new.switch.MainActivity.onNavigationItemSelected(MainActivity.java:97)
at
android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:151)
at
android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:811)
at
android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
at
android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:958)
at
android.support.design.internal.NavigationMenuPresenter$1.onClick(NavigationMenuPresenter.java:318)
at android.view.View.performClick(View.java:4789)
at android.view.View$PerformClick.run(View.java:19881)
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:5289)
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:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
You forget to Declare your Activity in manifest file.
<activity android:name="your.pakage.name.DetailsMain" />
you need to declare DetailsMain in your Manifest file
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.DetailsMain"/>
</application>
You haven't declared activity in menifest file
<activity android:name="you_package_name.DetailsMain" />
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I make my application in Android Studio. I run this application but the Android app stopped. I make a app with an animation.
Here is my source code:
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.geven.animation" >
<application
android:allowBackup="true"
android:icon="#mipmap/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=".Animation"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.geven.animation.DRAWINGTHEBALL" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity:
package com.geven.animation;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button button = (Button) findViewById(R.id.button);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, Animation.class));
}
});
setContentView(R.layout.activity_main);
}
#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);
}
}
ActivityMain.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:layout_width="400dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:gravity="center"
android:textSize="20dp"
android:id="#+id/button"
android:text="Goto animation"/>
</RelativeLayout>
Animation.java:
package com.geven.animation;
import android.app.Activity;
import android.os.Bundle;
public class Animation extends Activity {
DrawingTheBall v;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
v = new DrawingTheBall(this);
setContentView(v);
}
}
DrawingTheBall.java:
package com.geven.animation;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.View;
public class DrawingTheBall extends View {
Bitmap bbal;
int x,y;
public DrawingTheBall(Context context) {
super(context);
bbal = BitmapFactory.decodeResource(getResources(), R.drawable.blueball);
x=0;
y=0;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Rect ourRect = new Rect();
ourRect.set(0,0,canvas.getWidth(), canvas.getHeight()/2);
Paint blue = new Paint();
blue.setColor(Color.BLUE);
blue.setStyle(Paint.Style.FILL);
canvas.drawRect(ourRect,blue);
if (x< canvas.getWidth()) {
x += 10;
}else {x=0;}
if (y<canvas.getHeight()) {
y += 10;
}else {y=0;}
Paint p = new Paint();
canvas.drawBitmap(bbal, x, y, p);
invalidate();
}
}
Logcat:
02-26 21:55:59.874 17975-17975/com.geven.animation D/AndroidRuntime﹕ Shutting down VM
02-26 21:55:59.874 17975-17975/com.geven.animation W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4174b700)
02-26 21:55:59.879 17975-17975/com.geven.animation E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.geven.animation/com.geven.animation.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2232)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2362)
at android.app.ActivityThread.access$700(ActivityThread.java:168)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1329)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:177)
at android.app.ActivityThread.main(ActivityThread.java:5493)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1225)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1041)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1914)
at com.geven.animation.MainActivity.<init>(MainActivity.java:14)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1130)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2223)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2362)
at android.app.ActivityThread.access$700(ActivityThread.java:168)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1329)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:177)
at android.app.ActivityThread.main(ActivityThread.java:5493)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1225)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1041)
at dalvik.system.NativeStart.main(Native Method)
02-26 22:01:00.199 17975-17975/com.geven.animation I/Process﹕ Sending signal. PID: 17975 SIG: 9
Button button = (Button) findViewById(R.id.button);
You need to put that line in your onCreate method.
Basically, at the field level, you can have Button button; and then in onCreate you would initialize the variable thusly: button = (Button) findViewById(R.id.button);. You can't call findViewById() before the view has been inflated.
As a side note, a stacktrace may look intimidating at first, but the easiest way to deal with it, is to search for your package name, in this case "com.geven.animation". The first entry in the stack trace that includes that package name is usually the offending line. at com.geven.animation.MainActivity.<init>(MainActivity.java:14) so line 14 of your MainActivity class.
I'm making an android app with 2 activities and a Java class that reads/writes RFID data using NFC.
I'm using the enableReaderMode() method to enable reader/writer mode in the mainActivity, which then calls onTagDiscovered in a separate java class. Once in the onTagDiscovered method, I'm calling mainActivity.startNewActivity() to open a the second activity. I know that I'm reaching startNewActivity() because of a log message, but the activity is not actually starting. The app doesn't crash, and I'm not getting any errors, it just isn't starting. I've tried placing a button in the mainActivity and opening that way, and it works fine. It just doesn't work when I call the method from encode.java.
**I know that it is not necessary to open the activity from Encode.java, and that I could directly code this into MainActivity, but I'm preparing to do something more complex where I will need to open from Encode.java, and I want to test that the activity will open at all.
Here's the code
Encode.java
public class Encode implements NfcAdapter.ReaderCallback {
MainActivity mainActivity = new MainActivity();
public void onTagDiscovered(Tag tag) {
Log.i(TAG, "New tag discovered");
mainActivity.startNewActivity();
}
MainActivity
public void startNewActivity() {
Log.v(TAG, "in startNewActivity");
Intent intent = new Intent(this, Success.class);
startActivity(intent);
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.project" >
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.NFC"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/xband"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<action android:name="android.nfc.action.TECH_DISCOVERED" />
<action android:name="android.nfc.action.TAG_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="#xml/nfc_tech" />
</activity>
<activity android:name=".Success" >
</activity>
</application>
</manifest>
Success.java
package com.project;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class Success extends Activity {
private static final String TAG = "encode";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.success_activity);
Log.v(TAG, "in success activity");
}
}
I tried adding the following code and then got this error message:
Encode.java
public void onTagDiscovered(Tag tag) {
Log.i(TAG, "New Tag Discovered");
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
mainActivity.startNewActivity();
}
});
}
02-20 11:52:27.739 22088-22088/com.project E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.project, PID: 22088
java.lang.NullPointerException
at android.app.Activity.startActivityForResult(Activity.java:3474)
at android.app.Activity.startActivityForResult(Activity.java:3435)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:817)
at android.app.Activity.startActivity(Activity.java:3677)
at android.app.Activity.startActivity(Activity.java:3645)
at com.project.MainActivity.startNewActivity(MainActivity.java:110)
at com.project.encoding.Encode$1.run(Encode.java:331)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5293)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
Someone at work was able to help me figure this out.
This wasn't working because I was creating a new instance of the MainActivity in Encode, instead of referencing the existing MainActivity.
In MainActivity we added:
private static MainActivity _instance = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
encode = new Encode();
enableReaderMode();
MainActivity._instance = this;
}
public static MainActivity getInstance() {
return _instance;
}
and in Encode we called the startNewActivity method by calling:
public void onTagDiscovered(Tag tag) {
Log.i(TAG, "New Tag Discovered");
MainActivity.getInstance().startNewActivity();
});
so that now Encode is using the existing instance of MainActivity
Instead of:
Intent intent = new Intent(this, Success.class);
Try: Intent intent = new Intent(getApplicationContext(), Success.class);
That worked for me one time cause it "Return the context of the single, global Application object of the current process. "