how to find null pointer exception with logcat - java

I'm trying to build a small app that takes a data file in external storage and emails it. I keep getting 'null pointer exceptions' right away in logcat and then my app dies. I can't seem to locate my exception and I am wondering if there is a way to determine the line of code that is causing this. I have the MainActivity class and then a class called SendData- the code is below. I'm new at this so any help would be greatly appreciated- thank you.
private static final String TAG = "MainActivity_ErrorLog";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// Create the getData intent
Intent intentgetData = new Intent(MainActivity.this, SendData.class);
public void onStart()
{
{
try
{
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite())
{
// verify the paths
String currentDBPath = "TLC_COMMON/database.db";
String backupDBPath = "database.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists())
{
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
}
catch (Exception e)
{
// change the V below to E when complete
Log.v(TAG,"ERROR: Database file not created");
}
startActivity(intentgetData);
}
}
}
--new class
public class SendData extends Activity
{
private static final String TAG = "MainActivity";
/* Checks if external storage is available to read */
public boolean isExternalStorageReadable()
{
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))
{
return true;
}
return false;
}
/** Called when the user clicks the Send My Data button */
public SendData(View view)
{
// Send data by email
{
File root = Environment.getExternalStorageDirectory();
// verify it is saving as this file name; also path in previous class
String fileName = "database.db";
if (root.canWrite())
{
File attachment = new File(root, fileName);
Intent email = new Intent(Intent.ACTION_SENDTO);
email.putExtra(android.content.Intent.EXTRA_SUBJECT, "Exercise data");
email.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"test#gmail.com"});
// is the Uri necessary?
email.putExtra(android.content.Intent.EXTRA_TEXT, Uri.fromFile(attachment));
// look at this VVV
startActivity(Intent.createChooser(email, "Send the data via Email"));}
else
{
// Change the V below to E when complete
Log.v(TAG, "Email send failed");
}
}
}
public void finish()
{
}
}
11-13 13:29:37.343: W/dalvikvm(3319): threadid=1: thread exiting with uncaught exception (group=0x418e3300)
11-13 13:29:37.343: E/AndroidRuntime(3319): FATAL EXCEPTION: main
11-13 13:29:37.343: E/AndroidRuntime(3319): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.va.datasender/com.example.va.datasender.MainActivity}: java.lang.NullPointerException
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.access$600(ActivityThread.java:130)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.os.Handler.dispatchMessage(Handler.java:99)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.os.Looper.loop(Looper.java:137)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-13 13:29:37.343: E/AndroidRuntime(3319): at java.lang.reflect.Method.invokeNative(Native Method)
11-13 13:29:37.343: E/AndroidRuntime(3319): at java.lang.reflect.Method.invoke(Method.java:511)
11-13 13:29:37.343: E/AndroidRuntime(3319): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-13 13:29:37.343: E/AndroidRuntime(3319): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-13 13:29:37.343: E/AndroidRuntime(3319): at dalvik.system.NativeStart.main(Native Method)
11-13 13:29:37.343: E/AndroidRuntime(3319): Caused by: java.lang.NullPointerException
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.content.ComponentName.<init>(ComponentName.java:75)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.content.Intent.<init>(Intent.java:3301)
11-13 13:29:37.343: E/AndroidRuntime(3319): at com.example.va.datasender.MainActivity.<init>(MainActivity.java:36)
11-13 13:29:37.343: E/AndroidRuntime(3319): at java.lang.Class.newInstanceImpl(Native Method)
11-13 13:29:37.343: E/AndroidRuntime(3319): at java.lang.Class.newInstance(Class.java:1319)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
11-13 13:29:37.343: E/AndroidRuntime(3319): ... 11 more

Find the lowest "Caused by" and continue down until you reach a line from your code:
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
at android.content.ComponentName.<init>(ComponentName.java:75)
at android.content.Intent.<init>(Intent.java:3301)
at com.example.va.datasender.MainActivity.<init>(MainActivity.java:36)
The <init> means you are doing something as a class variable or inside a constructor before the Activity has a valid Context... But the specific problem is on line 36.
I would guess that you are trying to create an Intent with this. Initialize your Intent inside onCreate() instead.
Found it. Change this:
// Create the getData intent
Intent intentgetData = new Intent(MainActivity.this, SendData.class);
to:
Intent intentgetData;
and inside onCreate() (or onStart() just before calling startActivity()) add:
intentgetData = new Intent(MainActivity.this, SendData.class);

Your problem comes from line 36 on your MainActivity. Check there for the problem.
11-13 13:29:37.343: E/AndroidRuntime(3319): at com.example.va.datasender.MainActivity.<init>(MainActivity.java:36)

The exeption from line number 36: at com.example.va.datasender.MainActivity.<init>(MainActivity.java:36).

Since the error log also shows android.content.Intent.<init> after the MainActivity.java:36, I would check the value for the first parameter in the following line, when instantiating intentgetData:
Intent intentgetData = new Intent(MainActivity.this, SendData.class);
Instead of having the instatiation done there, try doing it in the onStart() method just before calling startActivity(intentgetData);:
Intent intentgetData = new Intent(MainActivity.this, SendData.class);
startActivity(intentgetData);

Related

How to rectify this error iin Recyclerview with database

When i am trying to display the contacts in card view when i click on Button it shows fatal exception error it doesnot display cardview anyone can solve this programming with brillliance and another error is it show only one cardview when i click on again the app will be strucked?
Showcontacts.java
public class ShowContacts extends Activity
{
private SQLiteDatabase db;
DbOperations doo;
private List<Contacts> contactsList;
private RecyclerView rv;
private Cursor c;
String names,email,address;
int phone;
String read_query = "select * from"+ ContactsTask.ContactsEntry.TABLE_NAME;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycle_layout);
doo = new DbOperations(this);
openDatabase();
rv = (RecyclerView)findViewById(R.id.recyclerview);
initializeData();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
rv.setLayoutManager(linearLayoutManager);
rv.setHasFixedSize(true);
ContactAdapter cc = new ContactAdapter(contactsList);
rv.setAdapter(cc);
}
public void initializeData() {
contactsList = new ArrayList<>();
c = db.rawQuery(read_query,null);
c.moveToFirst();
while (!c.isLast())
{
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
c.isLast();
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
private void openDatabase() {
db = openOrCreateDatabase("contactDB", Context.MODE_PRIVATE,null);
}
}
Logacat error
06-28 08:57:43.107 568-568/com.example.anilkumar.contactstask E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anilkumar.contactstask/com.example.anilkumar.contactstask.ShowContacts}: android.database.sqlite.SQLiteException: near "fromcontacts": syntax error: , while compiling: select * fromcontacts
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: android.database.sqlite.SQLiteException: near "fromcontacts": syntax error: , while compiling: select * fromcontacts
at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:68)
at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:143)
at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:361)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:127)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:94)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:53)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1564)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1538)
at com.example.anilkumar.contactstask.ShowContacts.initializeData(ShowContacts.java:44)
at com.example.anilkumar.contactstask.ShowContacts.onCreate(ShowContacts.java:34)
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) 
Another logact error
06-28 13:14:40.552 11252-11261/com.example.anilkumar.contactstask E/SQLiteDatabase: close() was never explicitly called on database '/data/data/com.example.anilkumar.contactstask/databases/contactDB'
android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1943)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1007)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:986)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:962)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1043)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1036)
at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:761)
at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:215)
at com.example.anilkumar.contactstask.ShowContacts.openDatabase(ShowContacts.java:66)
at com.example.anilkumar.contactstask.ShowContacts.onCreate(ShowContacts.java:33)
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)
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)
Just update
String read_query = "select * from"+ ContactsTask.ContactsEntry.TABLE_NAME;
to
String read_query = "select * from "+ ContactsTask.ContactsEntry.TABLE_NAME;
Always close cursor. update your initializeData method
public void initializeData() {
try {
contactsList = new ArrayList<>();
try{
c = db.rawQuery(read_query,null);
c.moveToFirst();
while (!c.isLast())
{
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
c.isLast();
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
} catch (Exception e) {
// exception handling
} finally {
if(c != null){
c.close();
}
}
}

lockNow() in broadcast receiver

it seems that i get an error when i try to use LockNow() in the broadcast receiver. can anyone help me.
public class Onlockreceive extends BroadcastReceiver {
LockSettings lockactivity;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
lockactivity.mdevicepolicymanager.lockNow();
}
}
The error message :
12-31 03:14:16.322: D/AndroidRuntime(27478): Shutting down VM 12-31 03:14:16.322: W/dalvikvm(27478): threadid=1: thread exiting with uncaught exception (group=0x41b0d378) 12-31 03:14:16.332: E/AndroidRuntime(27478): FATAL EXCEPTION: main 12-31 03:14:16.332: E/AndroidRuntime(27478): java.lang.RuntimeException: Unable to start receiver com.example.settings2.Onlockreceive: java.lang.NullPointerException 12-31 03:14:16.332: E/AndroidRuntime(27478): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2257) 12-31 03:14:16.332: E/AndroidRuntime(27478): at android.app.ActivityThread.access$1500(ActivityThread.java:138) 12-31 03:14:16.332: E/AndroidRuntime(27478): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283) 12-31 03:14:16.332: E/AndroidRuntime(27478): at android.os.Handler.dispatchMessage(Handler.java:99) 12-31 03:14:16.332: E/AndroidRuntime(27478): at android.os.Looper.loop(Looper.java:213) 12-31 03:14:16.332: E/AndroidRuntime(27478): at android.app.ActivityThread.main(ActivityThread.java:4787) 12-31 03:14:16.332: E/AndroidRuntime(27478): at java.lang.reflect.Method.invokeNative(Native Method) 12-31 03:14:16.332: E/AndroidRuntime(27478): at java.lang.reflect.Method.invoke(Method.java:511) 12-31 03:14:16.332: E/AndroidRuntime(27478): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 12-31 03:14:16.332: E/AndroidRuntime(27478): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556) 12-31 03:14:16.332: E/AndroidRuntime(27478): at dalvik.system.NativeStart.main(Native Method) 12-31 03:14:16.332: E/AndroidRuntime(27478): Caused by: java.lang.NullPointerException 12-31 03:14:16.332: E/AndroidRuntime(27478): at com.example.settings2.Onlockreceive.onReceive(Onlockreceive.java:15) 12-31 03:14:16.332: E/AndroidRuntime(27478): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2250) 12-31 03:14:16.332: E/AndroidRuntime(27478): ... 10 more
My problem is similar to this one same problem.. but i don't understand how to fix it
this is the code i use to call the broadcast receiver
private void setupAlarm(int seconds,boolean s) {
// Finish the currently running activity
// MainActivity.this.finish();
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(getBaseContext(), Onlockreceive.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
LockSettings.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Log.d(TAG, "Setup the alarm");
// Getting current time and add the seconds in it
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, seconds);
if (s == true){
//alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
//alarmManager.setInexactRepeating(type, triggerAtMillis, intervalMillis, operation)
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 5000, pendingIntent );
}else if (s == false)
{
alarmManager.cancel(pendingIntent);
}
}
Either lockactivity or mdevicepolicymanager is null. This is not surprising, as your process may well have been terminated before the BroadcastReceiver got control.
Static data members are only a cache. Do not rely upon them. And most certainly do not put an Activity in a static data member, as you are leaking a lot of memory by doing so.
You can use the Context passed into onReceive() to retrieve a DevicePolicyManager and call lockNow().
UPDATE
Here is the revised class, complete with better formatting and case:
public class OnLockReceive extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
((DevicePolicyManager)context.getSystemService(Context.DEVICE_POLICY_SERVICE)).lockNow();
}
}

How to mail TextView data on button click with Android-Intent?

I am pretty new to both android and NFC. I am working on an NFC related application as a college project that reads the data from tags and lists them. Although I am able to do so, I am facing problems with intent where I am supposed to mail this list to user on button click.
Can someone please tell me where I am going wrong and help with a detailed step-by-step approach. Huge thanks..!!
Here's the WebServiceActivity:
public class WebServiceActivity extends Activity {
Intent intent = getIntent();
String studlist = intent.getStringExtra("studlist");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webservice);
TextView mailtext = (TextView) findViewById(R.id.students);
TextView mailbody = (TextView) findViewById(R.id.emailtext);
mailbody.setText("Here is the list for Tranport Tracking For Today: \n" + studlist);
Button send=(Button) findViewById(R.id.emailsendbutton);
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Log.i("Send email", "");
String[] TO = {"h.trivedi04#gmail.com"};
String[] CC = {"h.trivedi04#gmail.com", "harshit.trivedi22#gmail.com"};
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
emailIntent.putExtra(Intent.EXTRA_CC, CC);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Student Transport Track For Today");
emailIntent.putExtra(Intent.EXTRA_TEXT, studlist);
try {
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
finish();
Log.i("Finished sending email...", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(WebServiceActivity.this,
"There is no email client installed.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
And the main activity TransportActivity has:
Button webServiceButton = (Button)this.findViewById(R.id.webServiceButton);
webServiceButton.setOnClickListener(new android.view.View.OnClickListener()
{
public void onClick(View view) {
Intent intent = new Intent( view.getContext(), WebServiceActivity.class);
intent.putExtra("studlist", students.getText().toString());
startActivity(intent);
}
});
Here's the LogCat for the problem:
05-01 21:37:31.267: E/AndroidRuntime(27758): FATAL EXCEPTION: main
05-01 21:37:31.267: E/AndroidRuntime(27758): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.harshit.studenttranstrack/com.harshit.studenttranstrack.WebServiceActivity}: java.lang.NullPointerException
05-01 21:37:31.267: E/AndroidRuntime(27758): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2229)
05-01 21:37:31.267: E/AndroidRuntime(27758): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2359)
05-01 21:37:31.267: E/AndroidRuntime(27758): at android.app.ActivityThread.access$700(ActivityThread.java:165)
05-01 21:37:31.267: E/AndroidRuntime(27758): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1326)
05-01 21:37:31.267: E/AndroidRuntime(27758): at android.os.Handler.dispatchMessage(Handler.java:99)
05-01 21:37:31.267: E/AndroidRuntime(27758): at android.os.Looper.loop(Looper.java:137)
05-01 21:37:31.267: E/AndroidRuntime(27758): at android.app.ActivityThread.main(ActivityThread.java:5455)
05-01 21:37:31.267: E/AndroidRuntime(27758): at java.lang.reflect.Method.invokeNative(Native Method)
05-01 21:37:31.267: E/AndroidRuntime(27758): at java.lang.reflect.Method.invoke(Method.java:525)
05-01 21:37:31.267: E/AndroidRuntime(27758): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
05-01 21:37:31.267: E/AndroidRuntime(27758): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
05-01 21:37:31.267: E/AndroidRuntime(27758): at dalvik.system.NativeStart.main(Native Method)
05-01 21:37:31.267: E/AndroidRuntime(27758): Caused by: java.lang.NullPointerException
05-01 21:37:31.267: E/AndroidRuntime(27758): at com.harshit.studenttranstrack.WebServiceActivity.<init>(WebServiceActivity.java:22)
05-01 21:37:31.267: E/AndroidRuntime(27758): at java.lang.Class.newInstanceImpl(Native Method)
Try it like this inside onCreate() method.
Intent intent = this.getIntent(); //in the WebServiceActivity activity
String studlist = (String) intent .getStringExtra("studlist");
You can't getIntent() before onCreate() .There's simply no Intent available at that point. I believe the same is true for anything that requires a Context.
Set these in onCreate() method
String studlist = this.getIntent().getStringExtra("studlist");

Application stopped unexpectedly. Force close. what to do?

public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
System.loadLibrary("detection_based_tracker");
try {
InputStream is = getResources().openRawResource(R.raw.lbpcascade_frontalface);
File cascadeDir = getDir("cascade", Context.MODE_PRIVATE);
mCascadeFile = new File(cascadeDir, "lbpcascade_frontalface.xml");
FileOutputStream os = new FileOutputStream(mCascadeFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
is.close();
os.close();
mJavaDetector = new CascadeClassifier(mCascadeFile.getAbsolutePath());
if (mJavaDetector.empty()) {
Log.e(TAG, "Failed to load cascade classifier");
mJavaDetector = null;
} else
Log.i(TAG, "Loaded cascade classifier from " + mCascadeFile.getAbsolutePath());
cascadeDir.delete();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "Failed to load cascade. Exception thrown: " + e);
}
mOpenCvCameraView.enableView();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
public Mat onCameraFrame(CvCameraViewFrame inputFrame)
{
mRgba = inputFrame.rgba();
mGray = inputFrame.gray();
if (mAbsoluteFaceSize == 0) {
int height = mGray.rows();
if (Math.round(height * mRelativeFaceSize) > 0) {
mAbsoluteFaceSize = Math.round(height * mRelativeFaceSize);
}
}
MatOfRect faces = new MatOfRect();
if (mDetectorType == JAVA_DETECTOR){
if (mJavaDetector != null)
mJavaDetector.detectMultiScale(mGray, faces, 1.1, 2, 2,
new Size(mAbsoluteFaceSize, mAbsoluteFaceSize), new Size());
}
else {
Log.e(TAG, "Detection method is not selected!");
}
Rect[] facesArray = faces.toArray();
for (int i = 0; i < facesArray.length; i++)
{
Core.rectangle(mRgba, facesArray[i].tl(), facesArray[i].br(), FACE_RECT_COLOR, 5);
}
return mRgba;
}
While executing this code for face detection. I got this, application stopped unexpectedly.I decided to do face detection without any options and all. So can anybody suggest me what's wrong with my code.
Thanks in advance.
logcat
01-24 09:50:04.605: D/dalvikvm(335): newInstance failed: p0 i0 [0 a1
01-24 09:50:04.605: D/AndroidRuntime(335): Shutting down VM
01-24 09:50:04.605: W/dalvikvm(335): threadid=1: thread exiting with uncaught exception (group=0x40015560)
01-24 09:50:04.625: E/AndroidRuntime(335): FATAL EXCEPTION: main
01-24 09:50:04.625: E/AndroidRuntime(335): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.faces/com.example.faces.MainActivity}: java.lang.InstantiationException: com.example.faces.MainActivity
01-24 09:50:04.625: E/AndroidRuntime(335): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
01-24 09:50:04.625: E/AndroidRuntime(335): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
01-24 09:50:04.625: E/AndroidRuntime(335): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
01-24 09:50:04.625: E/AndroidRuntime(335): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
01-24 09:50:04.625: E/AndroidRuntime(335): at android.os.Handler.dispatchMessage(Handler.java:99)
01-24 09:50:04.625: E/AndroidRuntime(335): at android.os.Looper.loop(Looper.java:123)
01-24 09:50:04.625: E/AndroidRuntime(335): at android.app.ActivityThread.main(ActivityThread.java:3683)
01-24 09:50:04.625: E/AndroidRuntime(335): at java.lang.reflect.Method.invokeNative(Native Method)
01-24 09:50:04.625: E/AndroidRuntime(335): at java.lang.reflect.Method.invoke(Method.java:507)
01-24 09:50:04.625: E/AndroidRuntime(335): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-24 09:50:04.625: E/AndroidRuntime(335): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-24 09:50:04.625: E/AndroidRuntime(335): at dalvik.system.NativeStart.main(Native Method)
01-24 09:50:04.625: E/AndroidRuntime(335): Caused by: java.lang.InstantiationException: com.example.faces.MainActivity
01-24 09:50:04.625: E/AndroidRuntime(335): at java.lang.Class.newInstanceImpl(Native Method)
01-24 09:50:04.625: E/AndroidRuntime(335): at java.lang.Class.newInstance(Class.java:1409)
01-24 09:50:04.625: E/AndroidRuntime(335): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
01-24 09:50:04.625: E/AndroidRuntime(335): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1561)
01-24 09:50:04.625: E/AndroidRuntime(335): ... 11 more
Caused by: java.lang.InstantiationException: com.example.faces.MainActivity
Make sure your MainActivity class can be instantiated. Some common causes for this:
The class is abstract.
There is an explicit constructor an it takes arguments. Activities shouldn't really need an explicit constructor. If one is provided, it should take no arguments.
There's nothing wrong with the code you have attached here as I have a working version of the same sample code. Have you added the activity to the AndroidManifest.xml file?
I have been having the same issue with this all types of applications said as unexpectedly stopped/please force close. what I did is I totally restored my phone and it helped me avoid this issue again.
Before restoring be sure that all your needed docs and files are safe, transferred to other device or you can download one program from google market which helps in shifting files from file to the other new file in it.
And finally to restore have to go to settings-applications-restore SD card and phone, phone will be switched off and need to start again uploading your gmail account and connected to internet or WiFi.

Code keeps thowing a NPE, cannot find the cause

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

Categories

Resources