How to fix this error regarding getSupportFragmentManager()? - java

recently i started a new project in android studios and came across an error I can't really find or see the problem with, my application crashes when it hits the line getSupportFragmentManager(). I am using it alongside of TimePickerFragment
I tried googling different things and trying different ways to implement this
ButtonListeners class
import android.app.TimePickerDialog;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.TimePicker;
public class ButtonListeners extends FragmentActivity implements
View.OnClickListener, TimePickerDialog.OnTimeSetListener {
#Override
public void onClick(View buttons) {
switch (buttons.getId()){
case R.id.button1:
break;
case R.id.button2:
DialogFragment timePicker = new TimePickerFragment();
**FragmentManager manager = getSupportFragmentManager();** //<< error here
timePicker.show(manager,"timepicker");
}
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//do something
}
}
TimePickerFragment class
public class TimePickerFragment extends DialogFragment {
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
return new TimePickerDialog(getActivity(), (TimePickerDialog.OnTimeSetListener) getActivity(), hour, minute, DateFormat.is24HourFormat(getActivity()));
}
}
LogCat
2019-06-18 16:29:24.449 25857-25857/com.example.calendar E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.calendar, PID: 25857
java.lang.IllegalStateException: Activity has been destroyed
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:2114)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:683)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:637)
at android.support.v4.app.DialogFragment.show(DialogFragment.java:144)
at com.example.calendar.ButtonListeners.onClick(ButtonListeners.java:28)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

Try to use getFragmentManager() in place of getSupportFragmentManager().
There is second option, using getActivity().getSupportFragmentManager();

Related

Problem with Android Networking (Using Google Book API and LoadManager/ AsyncTaskLoader)

Having problems debugging an android networking application. I think I might have some problems with the import but I don't know which. If you can see the problem, please do let me know. Thank you.
MainActivity.java
package com.example.networkingfinals;
import androidx.appcompat.app.AppCompatActivity;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Loader;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<BookInfo>> {
private String url;
private String input;
private BookAdapter bookAdapter;
private int LOADER_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.submit);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editText = (EditText) findViewById(R.id.input);
input = String.valueOf(editText.getText());
url = "https://www.googleapis.com/books/v1/volumes?q="+input+"&maxResults=3";
}
});
LoaderManager loaderManager = getLoaderManager();
getLoaderManager().initLoader(LOADER_ID, null, this);//Set loader manager to call asyncloader in onCreateLoader
//TODO: Implement AsyncTaskLoader and LoadManager fetching network data on parallel thread
}
#Override
public Loader<List<BookInfo>> onCreateLoader(int id, Bundle args) {
Loader<List<BookInfo>> books = new BookAsync(this, url);
return books;
//Call oncreate Loader , fetching List of Book Info
}
#Override
public void onLoadFinished(Loader<List<BookInfo>> loader, List<BookInfo> data) {
Log.v("onLoadFinished", "Return " + data);
bookAdapter.addAll(data);
}
#Override
public void onLoaderReset(Loader loader) {
bookAdapter.clear();
}
Logcat
2021-01-10 18:44:55.950 13590-13590/com.example.networkingfinals V/onCreateLoader: Return BookAsync{814c192 id=0}
2021-01-10 18:44:56.045 13590-13590/com.example.networkingfinals V/onLoadFinished: Return null
2021-01-10 18:44:56.045 13590-13590/com.example.networkingfinals D/AndroidRuntime: Shutting down VM
2021-01-10 18:44:56.055 13590-13590/com.example.networkingfinals E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.networkingfinals, PID: 13590
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.networkingfinals.BookAdapter.addAll(java.util.Collection)' on a null object reference
at com.example.networkingfinals.MainActivity.onLoadFinished(MainActivity.java:61)
at com.example.networkingfinals.MainActivity.onLoadFinished(MainActivity.java:17)
at android.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:497)
at android.app.LoaderManagerImpl$LoaderInfo.onLoadComplete(LoaderManager.java:465)
at android.content.Loader.deliverResult(Loader.java:157)
at android.content.AsyncTaskLoader.dispatchOnLoadComplete(AsyncTaskLoader.java:274)
at android.content.AsyncTaskLoader$LoadTask.onPostExecute(AsyncTaskLoader.java:97)
at android.os.AsyncTask.finish(AsyncTask.java:755)
at android.os.AsyncTask.access$900(AsyncTask.java:192)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:772)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7458)
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:935)
2021-01-10 18:44:56.138 13590-13590/com.example.networkingfinals I/Process: Sending signal. PID: 13590 SIG:
I think I don't understand how onCreateLoader() and onLoadFinished() works. I tried and find that onCreateLoader return non-null data but in onLoadFinished() the data passed into it was null.
This error is because your adapter is not initialized yet you need to initialize it in onCreate
this.bookAdapter = new BookAdapter();
the error message says
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.networkingfinals.BookAdapter.addAll(java.util.Collection)' on a null object reference
that means is your adapter is null and you call addAll from the null object reference

ClassCastException : Fragment cannot be cast to Fragment

I have that app when, in MainActivity(which here is LoginActivity) first is replaced with a fragment(LoginFragment), for the sake of good code.
If a user want to signup, is redirected to a new SignUpFragment directly from mainActivity supportFragment manager:
//setting the first fragment in onCreate
fragmentManager = getSupportFragmentManager();
LoginFragment fragment = (LoginFragment) fragmentManager.findFragmentById(R.id.activity_main_content);
if(fragment == null){
fragment = LoginFragment.newInstance();
fragmentManager.beginTransaction().add(R.id.activity_main_content, fragment).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();
}
//Opening new registration fragment in LoginFragment.java
signUpTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((LoginActivity)getActivity()).loadSignUpFragment();
}
});
//In LoginActvity.java
public void loadSignUpFragment(){
SignUpFragment fragmentSignUp = SignUpFragment.newInstance();
fragmentManager.beginTransaction().replace(R.id.activity_main_content, fragmentSignUp).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).addToBackStack(null).commit();
}
all good, is working at first opening. Trying to register a new user, is working
But, after applying some minor code changes(like showing a snackbar if login fails), i got that error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.minimalart.studentlife/com.minimalart.studentlife.activities.LoginActivity}: java.lang.ClassCastException: com.minimalart.studentlife.fragments.SignUpFragment cannot be cast to com.minimalart.studentlife.fragments.LoginFragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4519)
at android.app.ActivityThread.-wrap19(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.ClassCastException: com.minimalart.studentlife.fragments.SignUpFragment cannot be cast to com.minimalart.studentlife.fragments.LoginFragment
at com.minimalart.studentlife.activities.LoginActivity$override.onCreate(LoginActivity.java:38)
at com.minimalart.studentlife.activities.LoginActivity$override.access$dispatch(LoginActivity.java)
at com.minimalart.studentlife.activities.LoginActivity.onCreate(LoginActivity.java:0)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4519) 
at android.app.ActivityThread.-wrap19(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
why i got that?
i'm switching and opening fragments only from my main activity
Thanks.
all LoginActivity.java:
package com.minimalart.studentlife.activities;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.minimalart.studentlife.R;
import com.minimalart.studentlife.fragments.LoginFragment;
import com.minimalart.studentlife.fragments.SignUpFragment;
public class LoginActivity extends AppCompatActivity {
private FragmentManager fragmentManager;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth = FirebaseAuth.getInstance();
fragmentManager = getSupportFragmentManager();
LoginFragment fragment = (LoginFragment) fragmentManager.findFragmentById(R.id.activity_main_content);
if(fragment == null){
fragment = LoginFragment.newInstance();
fragmentManager.beginTransaction().add(R.id.activity_main_content, fragment).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();
}
}
public void loadSignUpFragment(){
SignUpFragment fragmentSignUp = SignUpFragment.newInstance();
fragmentManager.beginTransaction().replace(R.id.activity_main_content, fragmentSignUp).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).addToBackStack(null).commit();
}
public void signUpNewUser(String email, String pass, String firstName, String secName, String age){
firebaseAuth.createUserWithEmailAndPassword(email, pass).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
}
else{
Snackbar.make(findViewById(R.id.signUpLinearLayout), task.getException().getLocalizedMessage(), Snackbar.LENGTH_LONG).show();
}
// ...
}
});
}
public void logInUser(String email, String pass){
}
}
I solved this, i found that the problem is at declaring main fragment
replaced
LoginFragment fragment = (LoginFragment)fragmentManager.findFragmentById(R.id.activity_main_content);
with
Fragment fragment = fragmentManager.findFragmentById(R.id.activity_main_content);
thanks #Selvin for your hint :)

Null Pointer Exception - What did I not initialize?

I am making a simple reminder app. I am getting a null pointer exception when the reminder goes off.
Here the key info from Logcat: Caused by: java.lang.NullPointerException
at com.joshbgold.move.AlarmReceiver.onReceive(AlarmReceiver.java:34)
Evidently I am not initializing AlarmActivity inst properly. I know this is probably a simple fix, thanks for your patience with a newer Java programmer.
AlarmReceiver.java:
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v4.content.WakefulBroadcastReceiver;
/**
* Created by JoshG on 7/6/2015.
*/
public class AlarmReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
//MediaPlayer is used to play an mp3 file
final MediaPlayer mediaPlayer = MediaPlayer.create(context, R.drawable.om_mani_short);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaplayer) {
mediaplayer.stop();
mediaplayer.release();
}
});
mediaPlayer.start();
//this will update the UI with message
AlarmActivity inst = AlarmActivity.instance();
inst.setAlarmText("stretch");
//this will send a notification message
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
AlarmActivity.java:
package com.joshbgold.move;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.ToggleButton;
import java.util.Calendar;
/**
* Created by JoshG on 7/6/2015.
*/
public class AlarmActivity extends Activity {
AlarmManager alarmManager;
private PendingIntent pendingIntent;
private TimePicker alarmTimePicker;
private static AlarmActivity inst;
private TextView alarmTextView;
public static AlarmActivity instance() {
return inst;
}
#Override
public void onStart() {
super.onStart();
inst = this;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmTimePicker = (TimePicker) findViewById(R.id.alarmTimePicker);
alarmTextView = (TextView) findViewById(R.id.alarmText);
ToggleButton alarmToggle = (ToggleButton) findViewById(R.id.alarmToggle);
final Button exitButton = (Button) findViewById(R.id.exitButton);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
final MediaPlayer mediaPlayer = MediaPlayer.create(this, R.drawable.om_mani_short);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaplayer) {
mediaplayer.stop();
mediaplayer.release();
}
});
mediaPlayer.start();
View.OnClickListener quitApp = new View.OnClickListener() { //this block stops music when exiting
#Override
public void onClick(View view) {
if (mediaPlayer != null) try {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
} catch (Exception e) {
Log.d("Alarm Activity", e.toString());
}
finish();
}
};
exitButton.setOnClickListener(quitApp);
}
public void onToggleClicked(View view) {
if (((ToggleButton) view).isChecked()) {
Log.d("MyActivity", "Alarm On");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());
Intent myIntent = new Intent(AlarmActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(AlarmActivity.this, 0, myIntent, 0);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
} else {
alarmManager.cancel(pendingIntent);
setAlarmText("Alarm Off");
Log.d("MyActivity", "Alarm Off");
}
}
public void setAlarmText(String alarmText) {
alarmTextView.setText(alarmText);
}
}
Alarm Service.java
package com.joshbgold.move;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
/**
* Created by JoshG on 7/6/2015.
*/
public class AlarmService extends IntentService {
private NotificationManager alarmNotificationManager;
public AlarmService() {
super("AlarmService");
}
#Override
public void onHandleIntent(Intent intent) {
sendNotification("stretch");
}
private void sendNotification(String msg) {
Log.d("AlarmService", "Preparing to send notification...: " + msg);
alarmNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, AlarmActivity.class), 0);
NotificationCompat.Builder alarmNotificationBuilder = new NotificationCompat.Builder(
this).setContentTitle("Reminder").setSmallIcon(R.mipmap.ic_launcher)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
alarmNotificationBuilder.setContentIntent(contentIntent);
alarmNotificationManager.notify(1, alarmNotificationBuilder.build());
Log.d("AlarmService", "Notification sent.");
}
}
Here is the contents of Logcat. I have it set to Log Level of Error:
07-07 18:53:13.119 13065-13065/com.joshbgold.move E/﹕ mali: REVISION=Linux-r3p2-01rel2 BUILD_DATE=Mon Nov 18 21:41:36 KST 2013
07-07 19:00:11.569 16746-16746/com.joshbgold.move E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start receiver com.joshbgold.move.AlarmReceiver: java.lang.NullPointerException
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2469)
at android.app.ActivityThread.access$1600(ActivityThread.java:158)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1372)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5365)
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:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.joshbgold.move.AlarmReceiver.onReceive(AlarmReceiver.java:34)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2462)
            at android.app.ActivityThread.access$1600(ActivityThread.java:158)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1372)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:176)
            at android.app.ActivityThread.main(ActivityThread.java:5365)
            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:1102)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
            at dalvik.system.NativeStart.main(Native Method)
If this is the class, line 34 is
inst.setAlarmText("stretch");
which points to the line above it not getting an actual activity
AlarmActivity inst = AlarmActivity.instance();
Check your AlarmActivity class to make sure inst is not null when it is created with the instance() method.
Can you post your AlarmActivity class to see how you are creating/fetching your instance?
//this will update the UI with message
AlarmActivity inst = AlarmActivity.instance();
inst.setAlarmText("stretch");
inst is null. You should check AlarmActivity.instance()
public static AlarmActivity instance() {
if (inst == null) {
// Do something such as inst = ...
}
return inst;
}
I took a sharp right turn, and did a different implementation when the reminder/alarm goes off. While I am doing something a little different then originally intended, the above answers provided led me in the correct direction.
Here is what I am using for AlarmReceiver.java:
package com.joshbgold.move;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
public class AlarmReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
//this will change to new activity for Reminder(s) at the appropriate time
Intent myIntent = new Intent();
myIntent.setClassName("com.joshbgold.move", "com.joshbgold.move.ReminderActivity");
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
}
}

How to call view from DatePickerFragment

package org.jaberrio.personai2;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.TextView;
import java.util.Calendar;
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
DataBaseManager dataBaseManager = new DataBaseManager();
String date = String.valueOf(month) + "/" + String.valueOf(day) + "/" + String.valueOf(year);
dataBaseManager.tempSaveCurrentEvent(DataBaseManager.FieldTypes.DUE_DATE,date, getActivity().getApplicationContext());
TextView dueDate = (TextView)view.getRootView().findViewById(R.id.dueDate);
dueDate.setText(dataBaseManager.tempGetCurrentEvent(DataBaseManager.FieldTypes.DUE_DATE,getActivity().getApplicationContext()));
}
}
LOGCAT:
06-23 19:04:05.451 13931-13931/org.jaberrio.personai2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: org.jaberrio.personai2, PID: 13931
java.lang.NullPointerException
at org.jaberrio.personai2.DatePickerFragment.onDateSet(DatePickerFragment.java:36)
at android.app.DatePickerDialog.tryNotifyDateSet(DatePickerDialog.java:148)
at android.app.DatePickerDialog.onClick(DatePickerDialog.java:116)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
I am calling dueDate.setText() however it is returning null. I called view.getRootView() because I am inside the view of DatePicker therefore it should return the view containing my dueDate TextView. I could also pass the View from the method calling DatePickerFragment but I do not know how.I am guessing that DatePicker view when called getRootView() does not return the view that contains R.id.dueDate. Thanks in advance.

Error while opening Android app

i am new to android development and i am writing an app for my college project .The app transmits a string of data stored in shared preferences .The data is stored by one time setup screen which is never shown again.The issue is after first time,when app is started again it shows that "app has unfortunately stopped working "and when i click ok the app starts.Can anybody tell me why this is happening?
Code:
package com.example.homeautomation.zigbeehomeauto;
import android.annotation.TargetApi;
import android.content.SharedPreferences;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Toast;
public class MainScreen extends ActionBarActivity {
NdefMessage msg;
NfcAdapter nfcadapter;
public static final String PREFS_NAME = "MyPrefsFile";
public String pass2 ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
SharedPreferences check = getSharedPreferences(PREFS_NAME, 0);
String Pass = check.getString("Str", "Nothing");
pass2 = Pass;
nfcadapter = NfcAdapter.getDefaultAdapter(this);
if (nfcadapter == null) {
Toast.makeText(this, "NFC is not available User", Toast.LENGTH_LONG)
.show();
finish();
}
}
public void ExApp(View v) {
finish();
System.exit(0);
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void Nsend(View v)
{
byte[] stringBytes = pass2.getBytes();
nfcadapter.setNdefPushMessage(msg = new NdefMessage(new NdefRecord[]{NdefRecord.createMime("text/plain", stringBytes)
}),this);
}
}
Logcat Ouput:
04-07 12:04:38.478 10836-10836/com.example.homeautomation.zigbeehomeauto E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.homeautomation.zigbeehomeauto, PID: 10836
android.util.SuperNotCalledException: Activity {com.example.homeautomation.zigbeehomeauto/com.example.homeautomation.zigbeehomeauto.SetupScreen} did not call through to super.onCreate()
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2510)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2603)
at android.app.ActivityThread.access$900(ActivityThread.java:174)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5752)
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:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Check in your SetupScreen.java do you have super.onCreate(savedInstanceState);
after onCreate() Method is starts .
post your SetupScreen.java code also ..
Your onCreate() method of class SetupScreen do not call the super.onCreate(). Add the statement and the error should go away.

Categories

Resources