I'm currently trying to display the current time to my custom ListView but I keep getting a NullPointerException and was wondering what I was doing wrong since I was already adding to the array and grabbing its value.
The custom Adapter and setter/getters are here: 1 2
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list_view);
boss_title = getResources().getStringArray(R.array.boss_array);
bossTime = (TextView) findViewById(R.id.boss_time);
adapter = new BossAdapter(getApplicationContext(), R.layout.boss_layout);
listView.setAdapter(adapter);
int i = 0;
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("HH-mm-ss");
String formattedTime = df.format(c.getTime());
String [] boss_time_array = new String[6];
for(int i =0; i < 6; i++){
boss_time_array[i] = formattedTime;
}
boss_time = boss_time_array;
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
for (String boss : boss_title) {
Boss bossObject = new Boss(boss_icon[i], boss, boss_time[i]);
adapter.add(bossObject);
i++;
}
}
Logcat
8541-8541/baegmon.com.bosstimer E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: baegmon.com.bosstimer, PID: 8541
java.lang.RuntimeException: Unable to start activity ComponentInfo{baegmon.com.bosstimer/baegmon.com.bosstimer.MainActivity}: java.lang.NullPointerException: Attempt to read from null array
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
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:5257)
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 read from null array
at baegmon.com.bosstimer.MainActivity.onCreate(MainActivity.java:67)
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:2390)
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:5257)
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)
How do I modify it so that it doesn't return a null-pointer error and returns the correct time to my list view?
Handler handler=new Handler();
handler.post(new Runnable(){
#Override
public void run() {
// upadte textView here
handler.postDelayed(this,500); // set time here to refresh textView
}
});
Just pass your textview in the hanlder method. That works fine.
try to implement this code from the below site.
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
String strDate = sdf.format(c.getTime());
Hope any queries or concerns, do let me know.
You get the NullPointerException because the Thread isn't finished when you create the Adapter.
After the Thread was started you are immediately reading the results from boss_title.
This not possible because you have to wait for it to be finished.
You should use an AsyncTask for this and create your Adapter inside the onPostExecute (http://developer.android.com/reference/android/os/AsyncTask.html).
Also the SimpleDateFormat class is not thread-safe:
public static Date dateToString(Date date, final String format, final Locale locale)
ThreadLocal<SimpleDateFormat> formater = new ThreadLocal<SimpleDateFormat>() {
#Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat(format, locale);
}
};
return formater.get().format(string);
}
Related
Everytime the application gets to my second activity it crashes, giving the error.
My activity:
public class SecondActivity extends AppCompatActivity {
EditText barcodeText = findViewById(R.id.barcodeText);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
IntentFilter filter = new IntentFilter();
filter.addCategory(Intent.CATEGORY_DEFAULT);
filter.addAction(getResources().getString(R.string.activity_intent_filter_action));
registerReceiver(myBroadcastReceiver, filter);
}
private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Bundle b = intent.getExtras();
if (action.equals(getResources().getString(R.string.activity_intent_filter_action))) {
try {
displayScanResult(intent);
} catch (Exception e) {
}
}
}
};
private void displayScanResult(Intent initiatingIntent)
{
String decodedSource = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_source));
String decodedData = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_data));
String decodedLabelType = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_label_type));
barcodeText.setText(decodedData);
}
}
Logcat:
07-01 12:37:03.373 349-349/com.example.provatimer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.provatimer, PID: 349
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.provatimer/com.example.provatimer.SecondActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
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:5256)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:149)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:99)
at android.content.Context.obtainStyledAttributes(Context.java:438)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at com.example.provatimer.SecondActivity.<init>(SecondActivity.java:14)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
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:5256)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
I think it may have something to do with the context in the BroadcastReceiver, but I tried to declare it in the onCreate method but nothing changed.
Maybe I don't initialize correctly the intent in which the data should be stored, if so, how can I do it correctly?
All the Strings should be correct int the string.xml file, if the error may come from that I'll write them.
I think the error is happening here:
EditText barcodeText = findViewById(R.id.barcodeText);
You are invoking findViewById() directly in the class member declaration.
You have invoke findViewById() after setContentView()
EditText barcodeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
barcodeText = findViewById(R.id.barcodeText);
}
Hi I am trying to parse JSON using Retrofit, save it on Sqlite and display on RecyclerView. However my app crashes when I try to open the activity.
Below is my full codes of related activity. Could you please help me with resolving the issue?
Thank you
public class InventoryProductActivity extends AppCompatActivity implements InventoryProductListAdapter.CustomClickListener {
private static final String TAG = InventoryProductActivity.class.getSimpleName();
private InventoryProductListAdapter mInventoryProductListAdapter;
private RecyclerView mRecyclerView;
private RetrofitClient mRetrofitClient;
LinearLayoutManager mLinearLayoutManager;
private WarehouseDatabase mDatabase;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventory_product);
configViews();
mRetrofitClient = new RetrofitClient();
mDatabase = new WarehouseDatabase(this);
loadInventoryProductFeed();
}
private void configViews() {
mRecyclerView = findViewById(R.id.recycler_view_inventory_product);
mRecyclerView.setHasFixedSize(true);
mLinearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
mInventoryProductListAdapter = new InventoryProductListAdapter(this);
mRecyclerView.setAdapter(mInventoryProductListAdapter);
}
private void loadInventoryProductFeed() {
mProgressDialog = new ProgressDialog(InventoryProductActivity.this);
mProgressDialog.setMessage("Loading Inventory Data...");
mProgressDialog.setCancelable(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setIndeterminate(true);
mProgressDialog.show();
mInventoryProductListAdapter.reset();
if (getNetworkAvailability()) {
getFeed();
} else {
getFeedFromDatabase();
}
}
private void getFeed() {
Call<List<InventoryProductModel>> listCall = mRetrofitClient.getWarehouseServiceInventoryProduct().getAllInventoryProducts();
listCall.enqueue(new Callback<List<InventoryProductModel>>() {
#Override
public void onResponse(Call<List<InventoryProductModel>> call, Response<List<InventoryProductModel>> response) {
if (response.isSuccessful()) {
List<InventoryProductModel> inventoryProductModelList = response.body();
for (int i = 0; i < inventoryProductModelList.size(); i++) {
InventoryProductModel inventoryProductModel = inventoryProductModelList.get(i);
mInventoryProductListAdapter.notifyDataSetChanged();
}
} else {
int sc = response.code();
switch (sc) {
}
}
mProgressDialog.dismiss();
}
#Override
public void onFailure(Call<List<InventoryProductModel>> call, Throwable t) {
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void getFeedFromDatabase() {
List<InventoryProductModel> inventoryProductModelList = mDatabase.getInventoryProducts();
for (int i = 0; i < inventoryProductModelList.size(); i++) {
InventoryProductModel inventoryProductModel = inventoryProductModelList.get(i);
Log.d(TAG, inventoryProductModel.getName() + "||" + inventoryProductModel.getCountryId());
}
mProgressDialog.dismiss();
}
private boolean getNetworkAvailability() {
return Utils.isNetworkAvailable(getApplicationContext());
}
#Override
public void onClick(int position) {
}
}
E/WindowManager: android.view.WindowLeaked: Activity
codes.bala.bmsfinal1.activity.MainActivity has leaked window
DecorView#52c3fcd[] that was originally added here
at android.view.ViewRootImpl.(ViewRootImpl.java:418)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:331)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at android.app.Dialog.show(Dialog.java:322)
at android.app.ProgressDialog.show(ProgressDialog.java:116)
at android.app.ProgressDialog.show(ProgressDialog.java:104)
at codes.bala.bmsfinal1.activity.MainActivity.login(MainActivity.java:61)
at codes.bala.bmsfinal1.activity.MainActivity$1.onClick(MainActivity.java:41)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)
I/ViewConfigCompat: Could not find method getScaledScrollFactor() on
ViewConfiguration D/AndroidRuntime: Shutting down VM
--------- beginning of crash E/AndroidRuntime: FATAL EXCEPTION: main
Process: codes.bala.bmsfinal1, PID: 12077
java.lang.RuntimeException: Unable to start activity ComponentInfo{codes.bala.bmsfinal1/codes.bala.bmsfinal1.activity.InventoryProductActivity}:
java.lang.NullPointerException: Attempt to invoke interface method
'retrofit2.Call
codes.bala.bmsfinal1.iinterface.WarehouseService.getAllInventoryProducts()'
on a null object reference
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.NullPointerException: Attempt to invoke interface
method 'retrofit2.Call
codes.bala.bmsfinal1.iinterface.WarehouseService.getAllInventoryProducts()'
on a null object reference
at codes.bala.bmsfinal1.activity.InventoryProductActivity.getFeed(InventoryProductActivity.java:88)
at codes.bala.bmsfinal1.activity.InventoryProductActivity.loadInventoryProductFeed(InventoryProductActivity.java:70)
at codes.bala.bmsfinal1.activity.InventoryProductActivity.onCreate(InventoryProductActivity.java:46)
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)
Application terminated.
getWarehouseServiceInventoryProduct()
method return null.
You should set breakpoint inside this method and check what happening (or add some logs to this method).
This is my first time asking questions here.
I am trying to make my TextView text color changing to a random color time by time when the application is started.
This is what I tried but it made my app crash.
TextView txtLucky;
Random rd;
int r = 0, g = 0, b = 0;
Thread stopper = new Thread();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLucky = findViewById(R.id.txtLucky);
while (true){
try {
wait(2000);
rd = new Random();
int rdcolor = Color.argb(255, rd.nextInt(256), rd.nextInt(256), rd.nextInt(256));
txtLucky.setTextColor(rdcolor);
} catch (InterruptedException e) {
e.printStackTrace();
}
stopper.start();
}
}
Error Log:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.max.threadstopper, PID: 14708
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.max.threadstopper/com.example.max.threadstopper.MainActivity}: java.lang.IllegalMonitorStateException: object not locked by thread before wait()
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.IllegalMonitorStateException: object not locked by thread before wait()
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:422)
at com.example.max.threadstopper.MainActivity.onCreate(MainActivity.java:27)
at android.app.Activity.performCreate(Activity.java:6999)
at android.app.Activity.performCreate(Activity.java:6990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Try this
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
rd = new Random();
final int rdcolor = Color.argb(255, rd.nextInt(256), rd.nextInt(256), rd.nextInt(256));
runOnUiThread(new Runnable() {
#Override
public void run() {
txtLucky.setTextColor(rdcolor);
}
});
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
2000);
Text color change code put in runOnUiThread. because you already start one Thread.
runOnUiThread(new Runnable() {
#Override
public void run() {
txtLucky.setTextColor(rdcolor);
}
});
This question already has an answer here:
getFileDir() cause NullPointer exception
(1 answer)
Closed 5 years ago.
I'm writing a simple journal app. I've currently got it to the point where I can open it, type stuff into a text box, and click the button to save it (but not yet actually save it). If I run it as is below (with the /commented out/ parts comment out) then it works, but if I make the comments be code, it crashes on launch. I've narrowed it down to the first commented line of code: File path = this.getFilesDir(); as causing the crash, though there may be more problems elsewhere that I haven't found yet.
Any idea why it's crashing? Or a better way for me to save text to a file?
public class MainActivity extends AppCompatActivity {
/* File path = this.getFilesDir();
File file = new File(path, "dreamWritings.txt");
FileOutputStream stream;*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView tv = (TextView)findViewById(dreamText);
final Button button = (Button) findViewById(R.id.recordDream);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String dreamWords = tv.getText().toString();
/* try {
stream = new FileOutputStream(file, true);
}
catch(FileNotFoundException ex2){
System.out.println(ex2);
}
try {
stream.write(dreamWords.getBytes());
stream.close();
tv.setText("Hey I think we wrote that to a file!");
}
catch(IOException ex) {
System.out.println(ex);
}*/
tv.setText("Your dream has been recorded");
}
});
}
}
And here is the crash log:
08-11 22:23:22.772 1443-1443/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sixpencegames.www.dreamjournal, PID: 1443
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.sixpencegames.www.dreamjournal/com.sixpencegames.www.dreamjournal.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getFilesDir()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2568)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2727)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1478)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6121)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getFilesDir()' on a null object reference
at android.content.ContextWrapper.getFilesDir(ContextWrapper.java:223)
at com.sixpencegames.www.dreamjournal.MainActivity.<init>(MainActivity.java:22)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2558)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2727)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1478)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6121)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
Problem is you can't access this globally as context won't be assigned and hence returns null.
Try below
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView tv = (TextView)findViewById(dreamText);
final Button button = (Button) findViewById(R.id.recordDream);
File path = this.getFilesDir();
File file = new File(path, "dreamWritings.txt");
FileOutputStream stream;
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String dreamWords = tv.getText().toString();
try {
stream = new FileOutputStream(file, true);
}
catch(FileNotFoundException ex2){
System.out.println(ex2);
}
try {
stream.write(dreamWords.getBytes());
tv.setText("Hey I think we wrote that to a file!");
}
catch(IOException ex) {
System.out.println(ex);
}finally{
stream.close();
}
tv.setText("Your dream has been recorded");
}
});
}
I am making an app to display data from a database into a list view. When an item on the list view is clicked, it takes the user to a new activity where they can view more details about that item. I want to make the details page dynamic to display the details and have managed to show the title of the list view item in a toast.
Now, I am trying to display this by using setText() to show the title in a string but am getting the error:
AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kathe.parenttripapp, PID: 22849
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.kathe.parenttripapp/com.example.kathe.parenttripapp.Details}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
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 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference
at com.example.kathe.parenttripapp.Details.<init>(Details.java:23)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
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)
this is the class the error occurs at:
TextView titletext;
final List<Activitytable> activityTable = Activitytable.listAll(Activitytable.class);
String data = getIntent().getSerializableExtra("listPosition").toString();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
TextView titletext = (TextView) findViewById(R.id.titletext);
String data = getIntent().getSerializableExtra("listPosition").toString();
Toast.makeText(getBaseContext(),String.valueOf(data),Toast.LENGTH_LONG).show();
setData();
}
private void setData() {
Intent i = getIntent();
Bundle b = i.getExtras();
if (data != null) {
String j = (String) b.get("listPosition");
titletext.setText(j);
}
else{
titletext.setText("Hello");
}
}
This is the activity it has come from:
final ListView listView = (ListView) findViewById(R.id.viewAll_listview);
long count = Activitytable.count(Activitytable.class);
if(count>0) {
final List<Activitytable> activitytable = Activitytable.listAll(Activitytable.class);
final ViewAllListView madapter = new ViewAllListView(getApplicationContext(), activitytable);
listView.setAdapter(madapter);
listView.setClickable(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?>parent, View v, int position, long id) {
String title = activitytable.get(position).Title.toString();
Activitytable AT = Activitytable.findById(Activitytable.class,activitytable.get(position).getId());
Intent i = new Intent(getApplicationContext(),Details.class);
i.putExtra("listPosition",title);
startActivity(i);
}
public Object getItem(int position) {return position;}
});
}
else
{
Toast.makeText(getApplicationContext(), "No Data Available in Table", Toast.LENGTH_LONG);
}
}
What I would like to do is to put the intent data into the TextView 'titletext' and then do an if statement saying if the passed intent data is equal to an activity title then display the following data but can't work out what is going wrong. I have tried using getStringExtra() instead of getSerializableExtra but no such luck. Works on toast but not on TextView.
If you don't have some good understanding of why you are doing so, try not to initialize your variables until you are in onCreate, also to prevent a NullPointerException, it is a good habit to use if (variable != null).
And you are storing an int, so use getIntExtra
TextView titletext;
List<Activitytable> activityTable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
activityTable = Activitytable.listAll(Activitytable.class);
titletext = (TextView) findViewById(R.id.titletext);
Intent i = getIntent();
if (i != null) {
String data = i.getStingExtra("listPosition");
titletext.setText(String.valueOf(data));
}
}
In onCreate() and don't do it as a member variable.
Bundle intentBundle = getIntent().getExtras();
if (intentBundle != null) {
lastPosition = getInt( "lastPostion" );
}
The null pointer you are receiving is in the Details class on line 23
at com.example.kathe.parenttripapp.Details.<init>(Details.java:23)