I theoretically have 2 related questions.
1) I tried to make a night mode for my app. That works so far pretty good. Then I wanted to put the setting the User chooses to SharedPreferences. In my first try, It just didn't work. All I did was getting red and causing errors. After a lot of research on the Internet, I found another idea. Now the app is starting but crashing immediately again. The error has to be in the SharedPreferences because as soon as I delete this part it is working again. I just can't find the error and it doesn't show me a red area or so either.
2) Just to check if my research are right. Is it true that it is not possible anymore to make a time-related Night mode? Means dark at night, light at day? I found out that MODE_NIGHT_AUTO_TIME was supposed to do that but is deprecated and they suggest to use MODE_NIGHT_AUTO_BATTERY which is kinda something really different.
btw. here is my code if it helps from the Setting:
public class Settings extends AppCompatActivity {
private static final String TAG = "SettingsActivity";
private RelativeLayout layout;
private SharedPreferences preferences;
private Bundle savedInstanceState;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Spinner spinner = findViewById(DarkMode);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.e(TAG, "onItemSelected: " + position);
handleNightMode(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Log.e(TAG, "onNothingSelected: ");
}
});
}
private void handleNightMode(int position) {
switch (position) {
case 0:
Log.e(TAG, "Nothing Selected");
break;
case 1:
Log.e(TAG, "FOLLLOW_SYSTEM");
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
getDelegate().applyDayNight();
break;
case 2:
Log.e(TAG, "YES");
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
getDelegate().applyDayNight();
break;
case 3:
Log.e(TAG, "NO");
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
getDelegate().applyDayNight();
break;
case 4:
Log.e(TAG, "AUTO");
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
getDelegate().applyDayNight();
break;
default:
Log.e(TAG, "FOLLLOW_SYSTEM");
break;
}
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String NightMode = preferences.getString("prefTheme", "NO");
if (NightMode.equals("YES"))
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
if (NightMode.equals("NO"))
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
else if (NightMode.equals("AUTO"))
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
the MainActivity:
public class MainActivity extends AppCompatActivity {
int currentDayNight;
private Button settings;
private RelativeLayout layout;
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
layout = findViewById(R.id.layout);
settings = findViewById(R.id.btn_settings);
currentDayNight = AppCompatDelegate.getDefaultNightMode();
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openSettings();
}
});
}
private void openSettings() {
Intent intent = new Intent(this, Settings.class);
startActivity(intent);
}
}
logcat:
04-16 21:31:59.861 11136-11136/? I/art: Not late-enabling -Xcheck:jni (already on)
04-16 21:32:00.033 11136-11136/com.goldenegg.darkmode W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
04-16 21:32:00.086 11136-11136/com.goldenegg.darkmode I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
04-16 21:32:00.087 11136-11136/com.goldenegg.darkmode I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
04-16 21:32:00.168 11136-11149/com.goldenegg.darkmode I/art: Background partial concurrent mark sweep GC freed 523(79KB) AllocSpace objects, 0(0B) LOS objects, 50% free, 1007KB/2031KB, paused 6.320ms total 27.683ms
04-16 21:32:00.204 11136-11136/com.goldenegg.darkmode D/AndroidRuntime: Shutting down VM
--------- beginning of crash
04-16 21:32:00.205 11136-11136/com.goldenegg.darkmode E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.goldenegg.darkmode, PID: 11136
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.goldenegg.darkmode/com.goldenegg.darkmode.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.goldenegg.darkmode.MainActivity.onCreate(MainActivity.java:34)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Thanks for your Help.
have a great day
Related
My app crashes after clicking on the button when I call invalidate() to refresh the view. I can't figure out why. If I delete canvasView.invalidate(), the app does not crash. Is it allowed to call invalidate() from another class? I'm new to Android Studio. Surely, somebody can help me?
EDIT: the problem is solved, the answer is below, and I added the LogCat.
Here is the code:
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
CanvasView canvasView;
Button btnChangeColor;
static boolean colorRed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CanvasView canvasView = new CanvasView(this, null);
btnChangeColor = (Button) findViewById(R.id.button);
btnChangeColor.setOnClickListener(this);
colorRed = false;
}
#Override
public void onClick(View v) {
if(colorRed) {
colorRed = false;
canvasView.invalidate();
return;
}
else {
colorRed = true;
canvasView.invalidate();
return;
}
}
}
class CanvasView extends View {
Paint paint;
public CanvasView(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(MainActivity.colorRed == true)
paint.setColor(Color.RED);
else
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL);
canvas.drawCircle(400, 400, 50, paint);
}
}
LogCat:
05-31 21:10:41.341 27902-27902/? I/art: Late-enabling -Xcheck:jni
Reinit property: dalvik.vm.checkjni= false
05-31 21:10:41.351 27902-27909/? I/art: Debugger is no longer active
Starting a blocking GC Instrumentation
05-31 21:10:41.425 27902-27902/? W/System: ClassLoader referenced unknown path: /data/app/com.example.andreas.drawing_exp-2/lib/arm64
05-31 21:10:41.433 27902-27902/? I/InstantRun: starting instant run server: is main process
05-31 21:10:41.450 27902-27902/? I/HwCust: Constructor found for class android.app.HwCustActivityImpl
05-31 21:10:41.465 27902-27902/? I/HwCust: Constructor found for class android.app.HwCustHwWallpaperManagerImpl
05-31 21:10:41.477 27902-27902/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
05-31 21:10:41.533 27902-27913/? I/art: Background sticky concurrent mark sweep GC freed 2801(763KB) AllocSpace objects, 0(0B) LOS objects, 22% free, 3MB/4MB, paused 5.329ms total 13.242ms
05-31 21:10:41.567 27902-27902/? W/VRSystemServiceManager: vr service is not alive
05-31 21:10:41.568 27902-27902/? I/HwSecImmHelper: mSecurityInputMethodService is null
05-31 21:10:41.571 27902-27902/? I/HwPointEventFilter: support AFT
05-31 21:10:41.615 27902-27922/? I/OpenGLRenderer: Initialized EGL, version 1.4
05-31 21:10:41.621 27902-27922/? W/linker: /vendor/lib64/libhwuibp.so: unused DT entry: type 0xf arg 0xe3a
05-31 21:10:41.629 27902-27902/? W/art: Before Android 4.1, method int android.support.v7.widget.DropDownListView.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
05-31 21:10:48.728 27902-27902/com.example.andreas.drawing_exp I/hwaps: JNI_OnLoad
05-31 21:10:48.802 27902-27902/com.example.andreas.drawing_exp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.andreas.drawing_exp, PID: 27902
java.lang.NullPointerException: Attempt to read from field 'boolean com.example.andreas.drawing_exp.CanvasView.colorRed' on a null object reference
at com.example.andreas.drawing_exp.MainActivity.onClick(MainActivity.java:37)
at android.view.View.performClick(View.java:5646)
at android.view.View$PerformClick.run(View.java:22473)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
05-31 21:10:48.837 27902-27902/com.example.andreas.drawing_exp I/Process: Sending signal. PID: 27902 SIG: 9
You are using invalidate() incorrectly.
This must be called from a UI thread. To call from a non-UI thread, call postInvalidate().
You use postInvalidate() to do this.
I found out why my app crashes after watching a few tutorials on how to draw in a custom view in YouTube.
It is because I made the initialisation of my canvas view class the wrong way. I did not add an ID for the view and did not initialize with 'findViewById', instead I used the constructor of the class. But anyway, thanks for your answers!
Here is how the changed code looks like (short excerpt of original code):
public class MainActivity extends AppCompatActivity implements
View.OnClickListener{
CanvasView canvasView;
Button btnChangeColor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
canvasView = (CanvasView) findViewById(R.id.canvasview);
btnChangeColor = (Button) findViewById(R.id.button);
btnChangeColor.setOnClickListener(this);
canvasView.colorRed = false;
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am a beginner at android studio, I have a mission to redesign the app. I use the Fragment. But when I run my app, it has stopped and there is no error in my Gradle. I looked for many website to solve my question, but still have no idea.
I have some questions below.
How can I fix the java.lang.RuntimeException (NULL Pointer Exception) ?
09-30 02:59:56.574 17706-17706/? E/memtrack: Couldn't load memtrack module (No such file or directory)
09-30 02:59:56.574 17706-17706/? E/android.os.Debug: failed to load memtrack module: -2
09-30 02:59:56.996 17722-17722/? E/memtrack: Couldn't load memtrack module (No such file or directory)
09-30 02:59:56.996 17722-17722/? E/android.os.Debug: failed to load memtrack module: -2
09-30 02:59:57.090 17734-17734/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: tw.com.flag.parking22, PID: 17734
java.lang.RuntimeException: Unable to start activity ComponentInfo{tw.com.flag.parking22/tw.com.flag.parking22.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at tw.com.flag.parking22.MainActivity.init(MainActivity.java:102)
at tw.com.flag.parking22.MainActivity.onCreate(MainActivity.java:71)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
09-30 02:59:57.211 1160-1160/? E/EGL_emulation: tid 1160: eglCreateSyncKHR(1865): error 0x3004 (EGL_BAD_ATTRIBUTE)
09-30 03:02:15.409 2159-19872/com.google.android.gms E/Herrevad: [350] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:02:15.445 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:02:15.445 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=NetworkReportService requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=3600000 target_class=com.google.android.gms.common.stats.net.NetworkReportService runtime=1506742923454 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=7200000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:02:15.446 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.common.stats.net.NetworkReportService{u=0 tag="NetworkReportService" trigger=window{period=7200s,flex=3600s,earliest=5988s,latest=9588s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=2388s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:02:15.474 1170-1578/? E/Drm: Failed to find drm plugin
09-30 03:02:15.563 2159-2680/com.google.android.gms E/Volley: [129] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=AggregationTaskTag requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=600000 target_class=com.google.android.gms.checkin.EventLogService runtime=1506741123628 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=1800000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.checkin.EventLogService{u=0 tag="AggregationTaskTag" trigger=window{period=1800s,flex=600s,earliest=1787s,latest=2387s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=587s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:03:37.417 1170-1578/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000
09-30 03:30:15.406 2159-21157/com.google.android.gms E/Herrevad: [355] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:30:15.511 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.518 2159-21168/com.google.android.gms E/ZappLogOperation: Unable to bind to Phonesky
09-30 03:30:15.526 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.526 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.551 2159-2678/com.google.android.gms E/Volley: [127] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:30:15.572 1170-1578/? E/Drm: Failed to find drm plugin
09-30 03:30:22.524 2159-2159/com.google.android.gms E/ActivityThread: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection ctn#2f714ea6 that was originally bound here
android.app.ServiceConnectionLeaked: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection ctn#2f714ea6 that was originally bound here
at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1077)
at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:971)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1774)
at android.app.ContextImpl.bindService(ContextImpl.java:1757)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at com.google.android.gms.chimera.container.zapp.ZappLogOperation.onHandleIntent(:com.google.android.gms#11509280:1)
at com.google.android.chimera.IntentOperation.onHandleIntent(:com.google.android.gms#11509280:2)
at bwy.run(:com.google.android.gms#11509280:10)
at bwv.run(:com.google.android.gms#11509280:14)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=AggregationTaskTag requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=600000 target_class=com.google.android.gms.checkin.EventLogService runtime=1506743055606 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=1800000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.checkin.EventLogService{u=0 tag="AggregationTaskTag" trigger=window{period=1800s,flex=600s,earliest=1199s,latest=1799s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=0s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:44:15.637 2159-21184/com.google.android.gms E/Herrevad: [371] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:44:15.755 2159-2676/com.google.android.gms E/Volley: [126] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:46:13.425 1171-1171/? E/installd: eof
09-30 03:46:13.425 1171-1171/? E/installd: failed to read size
Here is the main activity code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager =(ViewPager) findViewById(R.id.pager);
PagerAdapter padapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(padapter);
//--------------------------------------------------------------------
init();
Action();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
}
else {
}
}
private void init(){
System.out.println("start---------------------");
textView_userIDVal = (TextView) findViewById(R.id.textView_userIDVal);
textView_parkingNoVal = (TextView) findViewById(R.id.textView_parkingNoVal);
textView_pillarNoVal = (TextView) findViewById(R.id.textView_pillarNoVal);
textView_colorVal = (TextView) findViewById(R.id.textView_colorVal);
imageView = (ImageView) findViewById(R.id.imageView);
button_space = (Button) findViewById(R.id.button_space);
button_scan = (Button) findViewById(R.id.button_scan);
button_find = (Button) findViewById(R.id.button_find);
simpleDateFormat = new SimpleDateFormat("MM/dd 'at' HH");
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
userID = Build.SERIAL;
//-------------error start next----------------
textView_userIDVal.setText("User ID : " + userID);
}
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 200);
}
sharedPreferences = getSharedPreferences("Data", 0);
if(sharedPreferences.contains("parkingNum") && sharedPreferences.contains("time")) {
parkingNumtmp = sharedPreferences.getString("parkingNum", "");
textView_parkingNoVal.setText("Parking No. : " + parkingNumtmp + "\t(" + sharedPreferences.getString("time", "") + ")");
}
builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder_timeout = new AlertDialog.Builder(this);
builder_timeout.setTitle("REMIND");
builder_timeout.setMessage("Do you find your car ?");
builder_timeout.setCancelable(false);
builder_timeout.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
json_data = new JSONObject();
json_data.put("MT", "timeout");
json_data.put("PlaceMac", parkingNumtmp);
json_data.put("UserMac", userID);
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", false);
isCloseScreen = false;
} catch (JSONException e) {
e.printStackTrace();
}
thread = new Thread(TCP);
thread.start();
timer_count = 0;
startFlag = false;
}
});
builder_timeout.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
maxTime = 10;
maxTime = maxTime / 2;
timer_count = 0;
startFlag = true;
}
});
}
private void Action(){
button_space.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
json_data = new JSONObject();
json_data.put("MT", "count");
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", true);
//System.out.println(json_write + "\n");
} catch (JSONException e) {
e.printStackTrace();
}
thread = new Thread(TCP);
thread.start();
/*builder.setTitle("INFORMATION");
builder.setMessage("All : " + "\nNow : " );
AlertDialog alertDialog = builder.create();
alertDialog.show();*/
}
});
button_scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ScanActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
});
button_find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(parkingNumtmp != null) {
try {
maxTime = 10;
json_data = new JSONObject();
json_data.put("MT", "search");
json_data.put("PlaceMac", parkingNumtmp);
json_data.put("UserMac", userID);
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", true);
//System.out.println(json_write + "\n");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Don't close the screen before you find your car ! ", Toast.LENGTH_LONG).show();
thread = new Thread(TCP);
thread.start();
}
else {
builder.setTitle("WARNING");
builder.setMessage("Please scan QRcode first!");
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
if(data != null) {
final Barcode barcode = data.getParcelableExtra("barcode");
parkingNumtmp = barcode.displayValue;
Date date = new Date();
final String time = simpleDateFormat.format(date);
sharedPreferences.edit().putString("parkingNum", parkingNumtmp).putString("time", time).commit();
textView_parkingNoVal.post(new Runnable() {
#Override
public void run() {
textView_parkingNoVal.setText("Parking No. : " + parkingNumtmp + "\t(" + time +")");
}
});
}
}
}
About Fragment. Is there any setting I have to do when I receive data form sever?
I want to put the received data to TextView in the another view .
Your init() function is probably try to find views inside fragments in view pager. However, at that moment, the fragments are not inflated yet, so your views in the activity are null and trying to do operation on them gives NPE. You should use onCreateView() of Fragment classes to find those views. Then you may notify main activity via callback mechanism.
For example, create FirstFragment as follows:
public class FirstFragment extends Fragment {
private OnFirstFragmentReadyListener callback;
#Override
public void onAttach(Context context) {
super.onAttach(context);
// This makes sure that the container activity has implemented the callback.
try {
callback = (OnFirstFragmentReadyListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnFirstFragmentReadyListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_first, container, false);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Notify the parent activity that the fragment is inflated.
callback.onFirstFragmentReady();
}
public interface OnFirstFragmentReadyListener {
void onFirstFragmentReady();
}
}
Let the layout of FirstFragment as follows (referenced above as fragment_first):
<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">
<TextView
android:id="#+id/first_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Assume we created two more similar fragment classes named as SecondFragment and ThirdFragment. Then the activity should be like this:
public class MainActivity extends AppCompatActivity implements FirstFragment.OnFirstFragmentReadyListener,
SecondFragment.OnSecondFragmentReadyListener, ThirdFragment.OnThirdFragmentReadyListener {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager =(ViewPager) findViewById(R.id.pager);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
// Don't call these functions here, spread them into callbacks.
// init();
// Action();
}
#Override
public void onFirstFragmentReady() {
TextView firstTextView = (TextView) findViewById(R.id.first_label);
...
// Now you have the views from FirstFragment instance.
// You can now call setText() or setOnClickListener() here.
}
#Override
public void onSecondFragmentReady() {
TextView secondTextView = (TextView) findViewById(R.id.second_label);
...
// Now you have the views from SecondFragment instance.
// You can now call setText() or setOnClickListener() here.
}
#Override
public void onThirdFragmentReady() {
TextView thirdTextView = (TextView) findViewById(R.id.third_label);
...
// Now you have the views from ThirdFragment instance.
// You can now call setText() or setOnClickListener() here.
}
}
Although this code works, this may not be the best way. I think it is better to do operations on views like setting texts or assigning OnClickListeners in fragments itself. If you need to notify a fragment after an action happened in the parent activity, you can implement public methods inside fragments and you can call them from the parent activity when needed.
In fragment you should call the function in onCreateView function(reason as mention by #Mehmed) which is something like below:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.your_fragment, container, false);
//all findViewById;
TextView yourTextView = (Text)view.findViewById(R.id.yourTextView);
//here call for your function
init();
// any other function goes here
return view;
}
I'm new in android development and I'm trying to build a kind of book listing kind of app for a project in my class. The prof's favorite motto is "whatever you don't know google it". That's not bad when you semi-know what to do but since we are learning java along with android development that's not helpful since java can seem a bit alien.
Anyways basing my app in a contact app this is how my MainActivity looks
//MainActivity.java
package com.iekproject.siegfried.libraryapp;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class MainActivity extends AppCompatActivity
implements LibraryFragment.LibraryFragmentListener, DetailFragment.DetailFragmentListener,
AddEditFragment.AddEditFragmentListener {
//key for storing a book's Uri in a Bundle passed to a fragment
public static final String BOOK_URI = "book_uri";
private LibraryFragment libraryFragment; //displays library aka book list
//displays LibraryFragment when MainActivity first loads
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//if layout contains fragmentContainer, the phone layout is in use. Create and display
//a LibraryFragment
if (savedInstanceState == null && findViewById(R.id.fragmentContainer) != null) {
//create LibraryFragment
libraryFragment = new LibraryFragment();
//add the fragment to the FrameLayout
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragmentContainer, libraryFragment);
transaction.commit(); //displays LibraryFragment
}
else {
libraryFragment =
(LibraryFragment) getSupportFragmentManager().
findFragmentById(R.id.DetailFragment);
}
}
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
//displays DetailFragment for selected book
#Override
public void onBookSelected(Uri bookUri) {
getSupportFragmentManager().popBackStack();
displayBook(bookUri, R.id.rightPaneContainer);
}
//displays AddEditFragment to add a new book. Possibly what I'll also have to change to make it
//scan/update the book list
#Override
public void onAddBook() {
displayAddEditFragment(R.id.rightPaneContainer, null);
}
//displays a book
private void displayBook(Uri bookUri, int viewID) {
DetailFragment detailFragment = new DetailFragment();
//specify book's Uri as an argument to the DetailFragment
Bundle arguments = new Bundle();
arguments.putParcelable(BOOK_URI, bookUri);
detailFragment.setArguments(arguments);
//use a FragmentTransaction to display the DetailFragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(viewID, detailFragment);
transaction.addToBackStack(null);
transaction.commit(); //causes DetailFragment to display
}
//displays fragment for adding new or editing existing book
private void displayAddEditFragment(int viewID, Uri bookUri) {
AddEditFragment addEditFragment = new AddEditFragment();
//if editing existing book, provide bookUri as an argument
if (bookUri != null) {
Bundle arguments = new Bundle();
arguments.putParcelable(BOOK_URI, bookUri);
addEditFragment.setArguments(arguments);
}
//use a FragmentTransaction to display the AddEditFragment
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.replace(viewID, addEditFragment);
transaction.addToBackStack(null);
transaction.commit(); //causes AddEditFragment to display
}
//return to book list when displayed book deleted
#Override
public void onBookDeleted() {
//removes top of back stack
getSupportFragmentManager().popBackStack();
libraryFragment.updateLibrary(); //refresh book list
}
//displays the AddEditFragment to edit an existing book. Maybe it can be used as Move or sth
/*#Override
public void onEditBook(Uri bookUri) {
displayAddEditFragment(R.id.rightPaneContainer, bookUri);
}*/
//update GUI after the new book or updated book saved
#Override
public void onAddEditCompleted(Uri bookUri) {
//removes top of back stack
getSupportFragmentManager().popBackStack();
libraryFragment.updateLibrary(); //refresh book list
if (findViewById(R.id.fragmentContainer) == null){ //tablet
//removes top of back stack
getSupportFragmentManager().popBackStack();
//on tablet, displays the book that was just added or edited
displayBook(bookUri, R.id.rightPaneContainer);
}
}
}
and this is the logcat
04-12 16:14:38.807 5796-5796/? I/art: Not late-enabling -Xcheck:jni (already on)
04-12 16:14:38.808 5796-5796/? W/art: Unexpected CPU variant for X86 using defaults: x86
04-12 16:14:38.926 5796-5796/com.iekproject.siegfried.libraryapp W/System: ClassLoader referenced unknown path: /data/app/com.iekproject.siegfried.libraryapp-1/lib/x86
04-12 16:14:38.945 5796-5796/com.iekproject.siegfried.libraryapp I/InstantRun: starting instant run server: is main process
04-12 16:14:38.991 5796-5796/com.iekproject.siegfried.libraryapp W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
04-12 16:14:39.119 5796-5796/com.iekproject.siegfried.libraryapp D/AndroidRuntime: Shutting down VM
04-12 16:14:39.119 5796-5796/com.iekproject.siegfried.libraryapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.iekproject.siegfried.libraryapp, PID: 5796
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.iekproject.siegfried.libraryapp/com.iekproject.siegfried.libraryapp.MainActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
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.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.support.v7.app.AppCompatDelegateImplV9.setSupportActionBar(AppCompatDelegateImplV9.java:207)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:130)
at com.iekproject.siegfried.libraryapp.MainActivity.onCreate(MainActivity.java:30)
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.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
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)
any help is appreciated
You just need to set the content view after setting the toolbar. You can write like this :
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setContentView(R.layout.activity_main);
The app is crashing because you are first setting the view and then setting the toolbar.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am a beginner, and I am trying to use ArrayList from an Interface. I got the structure from an article here. The problem is it's giving me null when I try to use it in a Fragment.
The class is:
public class NewsFRagment extends Fragment implements BackgroundTask.CallBack {
private ArrayList<NewsPOJO> arrayList1;
public NewsFRagment() {
// Required empty public constructor
}
#Override
public void onSuccess(ArrayList<NewsPOJO> arrayList) {
this.arrayList1 = arrayList;
Log.d("arraylist in onSuccess", String.valueOf(arrayList.size()));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.news_fragment, container, false);
BackgroundTask backgroundTask = new BackgroundTask(this.getActivity(), this);
backgroundTask.execute();
RecyclerView recyclerView = (RecyclerView) v.findViewById(R.id.rv_news);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
Log.d("Arraylist1 size", String.valueOf(+arrayList1.size()));
recyclerView.setAdapter(new MyRecyclerAdapter(this.getActivity(), arrayList1));
return v;
}
#Override
public String toString() {
return "News Fragment";
}
}
I need to use arraylist from the onSuccess and pass it in my setAdapter method, Problem is its null when I pass it in setAdaper, but it's not null in the onSuccess, How can I solve it?
This is logcat:
06-03 04:52:50.367 21851-21851/hilz.reycfrag W/art: Failed to find OatDexFile for DexFile /data/data/hilz.reycfrag/files/instant-run/dex/slice-slice_8-classes.dex ( canonical path /data/data/hilz.reycfrag/files/instant-run/dex/slice-slice_8-classes.dex) with checksum 0xd8bc1e5a in OatFile /data/data/hilz.reycfrag/cache/slice-slice_8-classes.dex
06-03 04:52:51.150 21851-21851/hilz.reycfrag D/AndroidRuntime: Shutting down VM
06-03 04:52:51.150 21851-21851/hilz.reycfrag E/AndroidRuntime: FATAL EXCEPTION: main
Process: hilz.reycfrag, PID: 21851
java.lang.RuntimeException: Unable to start activity ComponentInfo{hilz.reycfrag/hilz.reycfrag.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
at hilz.reycfrag.NewsFRagment.onCreateView(NewsFRagment.java:45)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:330)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:547)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1236)
at android.app.Activity.performStart(Activity.java:6006)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2288)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
06-03 04:52:51.178 21851-21897/hilz.reycfrag D/arraylist in onSuccess: 4
#Override
public void onSuccess(ArrayList<NewsPOJO> arrayList) {
this.arrayList1 = arrayList;
Log.d("arraylist in onSuccess", String.valueOf(arrayList.size()));
// Make sure your fragment is done view loading before on success.
RecyclerView recyclerView = (RecyclerView) v.findViewById(R.id.rv_news);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
Log.d("Arraylist1 size", String.valueOf(+arrayList1.size()));
recyclerView.setAdapter(new MyRecyclerAdapter(this.getActivity(), arrayList1));
}
Call the below code on start, show a progress dialog, and cancel on success:
BackgroundTask backgroundTask = new BackgroundTask(this.getActivity(), this);
backgroundTask.execute();
Check in what order the callbacks happen...
Your arraylist may not be initialized, when the callback happens at setAdapter as you only declare it. You never initialize it in constructor. As opposed to in the OnSuccess call back, where you receive an arraylist reference as input and set your local instance variable to it.
The creation of the view would be the initial callback run, so if you need to pass the list you need to initialise it first, you could for instance add an initialization to the constructor:
public NewsFRagment() {
// Required empty public constructor
arrayList1 = new ArrayList<NewsPOJO>();
}
Or you could have a specific initialise method, that you call after doing needed stuff in the view creation event first (if you need to pre-set the list).
I'm getting the error 'Attempt to invoke method '...' on a null object reference' on Android when trying to access a field which was set previously.
I check upon setting it that it's not null, but when it's accessed in a different activity, it 'null'.
This field is created along with multiple others' and for some reason, it's the only one which appear to old a null reference.
Object in question
public enum Locations {
Meeting_Room,Office_245,Lobby,NOC,VPsoffice
}
Class declaration:
public class Task implements Serializable {
private long taskId;
private String description;
private Boolean completed = false;
private Category task_catg;
private Task_Status task_sts;
private Locations tsk_location;
}
public Locations getTsk_location() {
return tsk_location;
}
public void setTsk_location(Locations tsk_location) {
this.tsk_location = tsk_location;
}
Please note that Task_Status & Category are also enums, and I do not encounter any issues with them.
This is where the object is initialized, I've added prints here and saw that the value returned from the activity is not null.
New Task activity
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(resultCode == RESULT_OK) {
switch (requestCode) {
case ACTIVITY_SELECT_LOCATION:
{
/*returned_selc_loc = (Locations) data.getSerializableExtra("location");
loc.setText(returned_selc_loc.toString());
loc.setClickable(false);*/
switch(Globals.temp)
{
case 0:
returned_selc_loc=Locations.Meeting_Room;
loc.setText(returned_selc_loc.toString());
loc.setClickable(false);
break;
case 1:
returned_selc_loc=Locations.Office_245;
loc.setText(returned_selc_loc.toString());
loc.setClickable(false);
break;
case 2:
returned_selc_loc=Locations.Lobby;
loc.setText(returned_selc_loc.toString());
loc.setClickable(false);
break;
case 3:
returned_selc_loc=Locations.NOC;
loc.setText(returned_selc_loc.toString());
loc.setClickable(false);
break;
case 4:
returned_selc_loc=Locations.VPsoffice;
loc.setText(returned_selc_loc.toString());
loc.setClickable(false);
break;
}
break;
}
default:
break;
}
}
}
This is where the Task object is created and the Location is set:
New Task activity
public void addTaskBtn (View view)
{
boolean state=true;
EditText desc = (EditText)findViewById(R.id.newTaskDesc);
EditText date = (EditText)findViewById(R.id.taskDateEdit);
EditText time = (EditText)findViewById(R.id.taskTimeEdit);
loc = (EditText)findViewById(R.id.taskLocation);
Date myDate = null;
RadioButton rb;
String emp_name;
t = new Task(desc.getText().toString());
t.setTask_sts(Task_Status.WAITING);
int position = spin.getSelectedItemPosition();
switch(position)
{
case 0:
t.setTask_catg(Category.GENERAL);
break;
case 1:
t.setTask_catg(Category.CLEANING);
break;
case 2:
t.setTask_catg(Category.ELECTRICITY);
break;
case 3:
t.setTask_catg(Category.COMPUTERS);
break;
case 4:
t.setTask_catg(Category.OTHER);
break;
}
//Added prints here and value is set correctly, definitely not NULL.
t.setTsk_location(returned_selc_loc);
t.setTaskId(task_id);
task_id++;
Intent returnIntent = new Intent();
dbm = DBManager.getInstance(this);
long seq_tsk_id = dbm.addTask(t);
t.setTaskId(seq_tsk_id);
returnIntent.putExtra("task", t);
setResult(RESULT_OK, returnIntent);
finish();
}
This is the call to the Edit Task activity, the call is from the MainActivity.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
dbM = DBManager.getInstance(context);
itemList = dbM.getAllTasks();
list.setAdapter(new TaskItemAdapter(context, itemList));
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long arg3) {
//get item instance from list
Task tt = (Task) ((TaskItemAdapter) parent.getAdapter()).getItem(position);
if(true)
{
//start the create activity again, now for editing
Intent i = new Intent(getApplicationContext(), EditTaskActivity.class);
i.putExtra("task", tt);
startActivityForResult(i, REQUEST_CODE_UPDATE_TASK);
}
return false;
}
});
}
Edit Task activity
This is I get the error (left only relevant part, as other variables in the object are successfully,
public void deleteTaskBtn(View view)
{
Intent returnIntent = new Intent(this,MainActivity.class);
Intent i = getIntent();
tastToEdit = (Task)i.getSerializableExtra("task");
tastToEdit.setToDelete(true);
ParseObject parse_task = new ParseObject("Task");
parse_task.put("Description",tastToEdit.getDescription());
parse_task.put("DueDate",tastToEdit.getDueDate());
parse_task.put("Priority",tastToEdit.getPriority().ordinal());
int com_state = (tastToEdit.getCompleted()) ? 1 : 0;
parse_task.put("IsCompleted",com_state);
parse_task.put("Location", tastToEdit.getTsk_location().ordinal());
parse_task.put("Category",tastToEdit.getTask_catg().ordinal());
parse_task.put("Status", tastToEdit.getTask_sts().ordinal());
parse_task.put("TeamName",Globals.team_name);
parse_task.put("Employee",tastToEdit.getEmp_name());
parse_task.deleteInBackground(new DeleteCallback() {
public void done(ParseException e) {
if (e == null) {
Log.d("msg","deleted");
} else {
Log.d("msg", "not deleted");
e.printStackTrace();
}
}
});
returnIntent.putExtra("task",tastToEdit);
setResult(RESULT_OK, returnIntent);
finish();
}
This line returns that NULL reference:
Location selected_loc = tastToEdit.getTsk_location();
Full error stack
03-09 21:28:20.192 10425-10425/? I/art: Late-enabling -Xcheck:jni
03-09 21:28:20.229 10425-10433/? I/art: Debugger is no longer active
03-09 21:28:20.240 10425-10425/? W/System: ClassLoader referenced unknown path: /data/app/il.ac.shenkar.david.todolistex2-1/lib/arm
03-09 21:28:20.446 10425-10456/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
03-09 21:28:20.508 10425-10456/? I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: QUALCOMM Build: 10/21/15, 369a2ea, I96aee987eb
03-09 21:28:20.511 10425-10456/? I/OpenGLRenderer: Initialized EGL, version 1.4
03-09 21:28:27.832 10425-10425/il.ac.shenkar.david.todolistex2 I/Choreographer: Skipped 52 frames! The application may be doing too much work on its main thread.
03-09 21:28:28.397 10425-10456/il.ac.shenkar.david.todolistex2 D/OpenGLRenderer: endAllStagingAnimators on 0xb38ccf80 (RippleDrawable) with handle 0xaef7fe30
03-09 21:28:29.620 10425-10456/il.ac.shenkar.david.todolistex2 D/OpenGLRenderer: endAllStagingAnimators on 0xb39ba400 (RippleDrawable) with handle 0xaef7f9e0
03-09 21:28:30.360 10425-10456/il.ac.shenkar.david.todolistex2 D/OpenGLRenderer: endAllStagingAnimators on 0xb397f900 (RippleDrawable) with handle 0xb3b29370
03-09 21:28:32.921 10425-10456/il.ac.shenkar.david.todolistex2 D/OpenGLRenderer: endAllStagingAnimators on 0x9f2cbb80 (ListPopupWindow$DropDownListView) with handle 0xb3b29530
03-09 21:28:33.437 10425-10456/il.ac.shenkar.david.todolistex2 D/OpenGLRenderer: endAllStagingAnimators on 0x9f2cad80 (RippleDrawable) with handle 0xb3b295d0
03-09 21:28:40.866 10425-10456/il.ac.shenkar.david.todolistex2 V/RenderScript: 0x9dca9000 Launching thread(s), CPUs 4
03-09 21:28:40.907 10425-10456/il.ac.shenkar.david.todolistex2 D/OpenGLRenderer: endAllStagingAnimators on 0xb3947700 (RippleDrawable) with handle 0xb3b29910
03-09 21:28:44.971 10425-10425/il.ac.shenkar.david.todolistex2 W/sdas: null
03-09 21:28:45.143 10425-10456/il.ac.shenkar.david.todolistex2 D/OpenGLRenderer: endAllStagingAnimators on 0xb39b5380 (ListView) with handle 0xaef7f510
03-09 21:28:48.110 10425-10425/il.ac.shenkar.david.todolistex2 D/AndroidRuntime: Shutting down VM
03-09 21:28:48.111 10425-10425/il.ac.shenkar.david.todolistex2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: il.ac.shenkar.david.todolistex2, PID: 10425
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.internal.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:278)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.internal.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:273)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int il.ac.shenkar.david.todolistex2.Location.ordinal()' on a null object reference
at il.ac.shenkar.david.todolistex2.EditTaskActivity.deleteTaskBtn(EditTaskActivity.java:372)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.internal.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:273)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
But as you can see, this field is set successfully previously, in another activity.
What can be the cause?
It looks to me that it's not about whether or not the field has been set, but rather the object you are trying to pull off the intent isn't there on this line in the onCreate:
tastToEdit = (Task)i.getSerializableExtra("task");
Add a check after this to see whether tastToEdit is null, and if so investigate why it hasn't been properly added to the intent if this is the case.
It looks like you're mistaken about what happens to the intent that you populated in one Activity's onActivityResult(). That method is responsible for handling the result of the next activity which was invoked with startActivityForResult(). That next activity can set a result for the prior activity using setResult(), which becomes available in onActivityResult() when the invoked activity finish.
However it looks like you're expecting getIntent() in "a different activity" to be able to see that Intent you created in onActivityResult(). That's simply not the case. getIntent() returns the activity that was used to start the current activity that you're working with. It's completely unrelated the intent from an activity result. So you'll need to change your strategy for passing data around between these activities.