My Java Application produces Null Pointer Exception from JCalander Combobox. I tried to catch the error. But that didnt work. Can someone assist me to fix this. Please.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.util.Calendar.setTime(Calendar.java:1106)
at java.text.SimpleDateFormat.format(SimpleDateFormat.java:955)
at java.text.SimpleDateFormat.format(SimpleDateFormat.java:948)
at java.text.DateFormat.format(DateFormat.java:336)
at org.freixas.jcalendar.JCalendarCombo.paramString(JCalendarCombo.java:780)
at java.awt.Component.toString(Component.java:8095)
tbmodel = (DefaultTableModel)tblItmQty.getModel();
System.out.println(calRecvDate.getDate());
try{
if(calRecvDate.getDate()==null){ // Error
JOptionPane.showMessageDialog(null, "Please Select Shippment Received Date");
calRecvDate.requestFocus();
}else if(txtShipSs.getText().isEmpty()){
////////////////////////////////////////////////////////////////
if (inputValidate() == true) {
try {
String shipId = txtShipId.getText();
String invID = txtInvoice.getText();
String shipSs = txtShipSs.getText();
String address = txtNtfAddress.getText();
String sipper = txtAShipper.getText();
String vessal = txtVessal.getText();
Date rcvDate = calRecvDate.getDate(); // Jcalander
String consignee = txtConsigne.getText();
ArrayList<ShippmentItems> shipItems = new ArrayList<ShippmentItems>();
tbmodel = (DefaultTableModel) tblItmQty.getModel();
for (int i = 0; i < tbmodel.getRowCount(); i++) {
String itmcode = (String) tbmodel.getValueAt(i, 0);
String itmName = (String) tbmodel.getValueAt(i, 1);
int qty = (int) tbmodel.getValueAt(i, 2);
ShippmentItems shpItems = new ShippmentItems(shipId, itmcode, itmName, qty);
shipItems.add(shpItems);
}
Since this throws the NPE:
calRecvDate.getDate()==null
The calRecvDate variable is null, and you will either need to check if it's null before using it, or make sure that it isn't null by tracing back in your code to where you think you've initialized it and fix the problem (since it isn't initialized).
To check if it's null, you could do:
if (calRecvDate != null) {
// use the calRecvDate variable here
} else {
// initialize the calRecvDate variable here
// or perhaps better, display a JOptionPane error message to the user
// that the date hasn't been selected, and exit this method by calling return:
return;
}
Again, don't use try/catch blocks to handle NullPointerExceptions.
Related
I have an activity 'B'. I have 2 more activities A and C. Both the activities lead to B. But i pass different Data from A and C. So while fetching
String dataFromA = getIntent.getStringExtra("SomethingA");
String dataFromC = getIntent.getStringExtra("SomethingC");
How to not get an error. I wont know from where the user is getting to activity B So how do i add an If statement or seomthing to not get an error while fetching as Either line A or C will get a NullPOinterException
You can use hasExtra method to check if that String exists.
if (getIntent().hasExtra("SomethingA")) {
String dataFromA = getIntent.getStringExtra("SomethingA");
} else if (getIntent().hasExtra("SomethingC")) {
String dataFromC = getIntent.getStringExtra("SomethingC");
}
You can try this code.
Bundle arguments = getArguments();
if (arguments != null){
if (arguments.containsKey("SomethingA")) {
String somethingA = arguments.getString("SomethingA");
if (TextUtils.isEmpty(somethingA)){
// Your codes comes here
}
}
}
Bundle (arguments) can be null if there is no data passed.
To check if string is empty or not use below code :
if(TextUtils.isEmpty(yourString))
{
// String empty
}
else
{
// string not empty
}
In your case you check it as :
if (getIntent()!=null && getIntent().getStringExtra!=null )
{
if (getIntent().hasExtra("SomethingA") && getIntent().hasExtra("SomethingB"))
String dataFromA = getIntent.getStringExtra("SomethingA");
String dataFromB = getIntent.getStringExtra("SomethingB");
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
So, I was trying to add a class to an ArrayList, but when I do it gives me a Null Pointer Exception. I'm sure I am just overlooking a variable that I thought was initialized, but I can't figure it out.
This is the class:
enum WebType { GoogleResult, Webpage };
public class Webpage {
WebType type;
String pageName;
String content;
String url;
String MLA = "";
public Webpage(String pageName, String content, String url, WebType type){
this.type = type;
this.pageName = pageName;
this.content = content;
this.url = url;
this.MLA = ""; // Temp
}
// TODO: Make Citation Maker
}
This is where I add the class to the ArrayList:
public void Start(){
for(Integer i = 0; i < tags.size(); i++){
if(tags.get(i) == null)
return;
Webpage page = Google(tags.get(i));
parseList.add(page); // The Error is on this line!
log.append("Added " + page.url + " to parse list");
}
for(Integer i = 0; i < parseList.size(); i++){
ParsePageCode(parseList.get(i));
}
}
Here is the Google function, it googles whatever you tell it to and returns the page information:
public Webpage Google(String search){
String url = "https://www.google.com/search?q=" + search;
String content = "";
try {
URLEncoder.encode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
log.append("\n Unsupported Encoding Contacting Google");
}
try {
content = GetPageCode(url);
} catch (IOException e) {
log.append("\n Unable To Reach Google");
log.append(e.getMessage());
}
Webpage w = new Webpage("Google Result For " + search, content, url, WebType.GoogleResult);
// System.out.println(search + url + WebType.GoogleResult);
return w;
}
Any Ideas?
On the line that is throwing the exception, parseList is the only variable being dereferenced. The only other variable on that line is page, and it doesn't matter if page is null because you can add null elements to a List. So, it must be parseList causing the NPE.
Actually there is no problem adding null to a collection of Objects. Retrieving the object and invoking its members later may cause NPE.
You have told is that the problem is on the line where you do add the object. The only way there to cause NPE is calling add() upon null. So that's your collection parseList that is not initialized yet. Maybe it's a field in the class and was never initialized to an actual object of type ArrayList, but it's only declared.
In Java, what is the best way to check if an object has value or is returning null? Most examples I have found are not very good. Basically I have this code:
mDBApi.getSession().setAccessTokenPair(reAuthTokens);
System.out.println(reAuthTokens);
if(reAuthTokens.equals(null)) {
mDBApi.getSession().startAuthentication(Main.this);
Log.e(TAG, "Keys not set -- I'm starting authentication");
}
I'm trying to get reAuthTokens to be checked for value and if it has none, move on and authenticate. However, I just get a NullPointerException on the if statement line. Is there something I can do better?
____________OnCreate for rcook________________________
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
//AccessTokenPair tokens=null;
//AccessTokenPair tokens = getStoredKeys();
//System.out.println(access + "here I am");
//clearKeys();
//Log.e(TAG, "keys cleared");
AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
mDBApi = new DropboxAPI<AndroidAuthSession>(session);
AccessTokenPair reAuthTokens = new AccessTokenPair(APP_KEY, APP_SECRET);
mDBApi.getSession().setAccessTokenPair(reAuthTokens);
System.out.println(reAuthTokens);
if(reAuthTokens == null) {
mDBApi.getSession().startAuthentication(Main.this);
Log.e(TAG, "Keys not set -- I'm starting authentication");
}
//
/*read settings*/
mSettings = getSharedPreferences(PREFS_NAME, 0);
boolean hide = mSettings.getBoolean(PREFS_HIDDEN, false);
boolean thumb = mSettings.getBoolean(PREFS_THUMBNAIL, true);
int space = mSettings.getInt(PREFS_STORAGE, View.VISIBLE);
int color = mSettings.getInt(PREFS_COLOR, -1);
int sort = mSettings.getInt(PREFS_SORT, 3);
mFileMag = new FileManager();
mFileMag.setShowHiddenFiles(true);
mFileMag.setSortType(sort);
if (savedInstanceState != null)
mHandler = new EventHandler(Main.this, mFileMag, savedInstanceState.getString("location"));
else
mHandler = new EventHandler(Main.this, mFileMag);
mHandler.setTextColor(color);
mHandler.setShowThumbnails(thumb);
mTable = mHandler.new TableRow();
/*sets the ListAdapter for our ListActivity and
*gives our EventHandler class the same adapter
*/
mHandler.setListAdapter(mTable);
setListAdapter(mTable);
/* register context menu for our list view */
registerForContextMenu(getListView());
mStorageLabel = (TextView)findViewById(R.id.storage_label);
mDetailLabel = (TextView)findViewById(R.id.detail_label);
mPathLabel = (TextView)findViewById(R.id.path_label);
mPathLabel.setText("path: /sdcard");
updateStorageLabel();
mStorageLabel.setVisibility(space);
mHandler.setUpdateLabels(mPathLabel, mDetailLabel);
/* setup buttons */
int[] img_button_id = {R.id.help_button, R.id.home_button,
R.id.back_button, R.id.info_button,
R.id.manage_button, R.id.multiselect_button,
R.id.dropbox_button
};
int[] button_id = {R.id.hidden_copy, R.id.hidden_attach,
R.id.hidden_delete, R.id.hidden_move};
ImageButton[] bimg = new ImageButton[img_button_id.length];
Button[] bt = new Button[button_id.length];
for(int i = 0; i < img_button_id.length; i++) {
bimg[i] = (ImageButton)findViewById(img_button_id[i]);
bimg[i].setOnClickListener(mHandler);
if(i < 4) {
bt[i] = (Button)findViewById(button_id[i]);
bt[i].setOnClickListener(mHandler);
}
}
Intent intent = getIntent();
if(intent.getAction().equals(Intent.ACTION_GET_CONTENT)) {
bimg[5].setVisibility(View.GONE);
mReturnIntent = true;
} else if (intent.getAction().equals(ACTION_WIDGET)) {
Log.e("MAIN", "Widget action, string = " + intent.getExtras().getString("folder"));
mHandler.updateDirectory(mFileMag.getNextDir(intent.getExtras().getString("folder"), true));
}
}
Use if (reAuthTokens == null)) instead. You're not trying to compare contents of objects; you're trying to compare references. "is reAuthTokens points to the same address as null?"
EDIT following updates from OP: reAuthTokens is of type AccessTokenPair (and I'm betting many readers initially thought this to be a List... I know I did). It is instantiated in this line:
AccessTokenPair reAuthTokens = new AccessTokenPair(APP_KEY, APP_SECRET);
Which is why the following condition will always be false: reAuthTokens == null. That's why, when coding if (reAuthTokens == null), you get a "dead code" warning: the compiler knows that this condition can never be true, as you instantiate reAuthTokens a few lines above.
So, the type of comparison you're after is not about reference, but about content. You want to check whether reAuthTokens is "empty". But that doesn't make sense from the code you had quoted. How come you instantiate the object, and then want to check if it's "empty"?
I think your logic isn't right. You should first obtain the access token pair from where you expect it to be (the session?), and compare the result to null. Something like this:
AccessTokenPair reAuthTokens = mDBApi.getSession().getAccessTokenPair();
if (reAuthTokens == null) {
reAuthTokens = new AccessTokenPair(...);
mDBApi.getSession().setAccessTokenPair(reAuthTokens);
}
I am creating a keyboard but there is some error in local variable usage.
private void updateCandidateText(){
try{
ExtractedText r= getCurrentInputConnection().getExtractedText(new ExtractedTextRequest(),InputConnection.GET_EXTRACTED_TEXT_MONITOR);
String strbeforeCursor="";
String strafterCursor ="";
strbeforeCursor = getCurrentInputConnection().getTextBeforeCursor(1000000000, 0).toString();
strafterCursor = getCurrentInputConnection().getTextAfterCursor(1000000000, 0).toString();
String str = strbeforeCursor + "|"+strafterCursor;
if(mTamilPreviewView != null)
mTamilPreviewView.update(str, strbeforeCursor.length());
mTamilPreviewView.update(r.text.toString() , 0);
}
catch (Exception e) {
Log.e("t", "errr", e);
}
}
You test if mTamilPreviewView != null to call
mTamilPreviewView.update(str, strbeforeCursor.length());
but even if it's null, you'll do
mTamilPreviewView.update(r.text.toString() , 0);
and you'll get a NullPointerException. Is it really what you want to do? Don't you mean
if (mTamilPreviewView != null) {
mTamilPreviewView.update(str, strbeforeCursor.length());
mTamilPreviewView.update(r.text.toString() , 0);
}
Moreover, you initialize strbeforeCursor and strafterCursor with an empty string, and you give them other values at the next lines. You could simply remove
String strbeforeCursor="";
String strafterCursor ="";
and do
String strbeforeCursor = getCurrentInputConnection().getTextBeforeCursor(1000000000, 0).toString();
String strafterCursor = getCurrentInputConnection().getTextAfterCursor(1000000000, 0).toString();
I am trying to get the content of a single array item.
In my code, I want the value of String suitId to have the content of suitIdArray[getSuitId];, but it doesn't get the content.
Could you please help me to see what is wrong. Here is my code...
Object item1 = spinner1.getSelectedItem();
int getDragId = spinner1.getSelectedItemPosition();
String suitId;
if(!item1.equals("Choose size")) {
suitId = suitIdArray[getSuitId];
}
else {
pSuit = null;
}
Is is not working because you have a variable getdragid but you're using getsuitid in the array? ie, should it be the following...
Object item1 = spinner1.getSelectedItem();
int getdragtid = spinner1.getSelectedItemPosition();
if(!item1.equals("Choose size"))
{
suitid = suitidarray[getdragtid]; // I changed this line
}
else if(item1.equals("Choose size"))
{
psuit = null;
}
Otherwise, I'm not really sure what you're trying to do?