How to retrieve an id from the HashMap [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
I have the below script where I get the id correctly but when I append it to the url I am getting as
java null pointer Exception.
Below is the method I used to store the ids:
public static HashMap<String, String> createdValue;
public static void getid(WebDriver driver) throws InterruptedException
{
String pendingconfirm = buttonXpath_Replace.replace("XXXX", "Pending confirm");
clickOnButton(driver, pendingconfirm);
createdValue = new HashMap<String, String>();
List<WebElement> tableValues = driver.findElements(By.xpath("//table//tr//td[contains(#class,'mat-column-demandId')]//span"));
int tableValueSize = tableValues.size();
System.out.println("Get the no of rows:"+tableValueSize);
WebElement latestId = driver.findElement(By.xpath("(//table//tr//td[contains(#class,'mat-column-demandId')]//span)["+tableValueSize +"]"));
System.out.println("Latest DemandIds: "+ latestId .getText());
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("(//table//tr//td[contains(#class,'mat-column-demandId')]//span)["+tableValueSize +"]")));
createdValue.put("latestDataId", latestId.getText());
System.out.println(createdValue.put("latestDataId", latestId.getText()));
}
Then I call the above method in order to append the latestId to the url:
String confirmationURL = "https://test-webapp.net/#/type=confirm";
List<String> newurls = new ArrayList<String>();
newurls.add(confirmationURL + "&id=" + createdValue.get("latestDataId"));
so in this case I fetch the id from the previous method by appending as above but when I do this it is not fetching the id and causes a null pointer Exception.
Any inputs on what I can do to get this resolved.

basically createdValue and getid both are static, so when you are calling it like this :
newurls.add(confirmationURL + "&id=" + createdValue.get("latestDataId"));
this is getting called :
public static HashMap<String, String> createdValue;
and since it does not have anything, you are getting the null pointer exception.
Also, I think if you call this :
getid first and then calling like this :
String confirmationURL = "https://test-webapp.net/#/type=confirm";
List<String> newurls = new ArrayList<String>();
getid(driver);
newurls.add(confirmationURL + "&id=" + createdValue.get("latestDataId"));
should help you by past this issue.

Related

java.lang.NullPointerException even though it's instanciated as global var [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
my problem is easy normally but i just don't see where is the problem.
-i am declaring an array of a class as a global variable that i reuse in multiple functions inside this other class.
the class instantiated is:
public class Service {
int numticketsin;
String name="mi";
int[] perhour={0,0,0,0,0,0,0,0,0,0};
int moyenneticketperday;
int[] moyenneticketperdayperhour={0,0,0,0,0,0,0,0,0,0};
public Service(){}
}
global var:
Service[] services=new Service[10];
the function where i use try to fill the array:
public void getnamesofservices(){
int x=0;
Connection conn=db.java_db();
try {
Statement stmt = conn.createStatement();
String qry = "SELECT service_name from service ";
ResultSet rs = stmt.executeQuery(qry);
int i=0;
while (rs.next()) {
String namee=rs.getString("service_name");
System.out.println(namee);
services[i].name = namee;
i++;
}
conn.close();
}
catch (SQLException ex)
{
System.err.println("SQLException: " + ex);
}
}
the error:
''' Exception in thread "main" java.lang.NullPointerException: Cannot assign field "name" because "this.services[i]" is null
at com.mycompany.stats.NewJFrame.getnamesofservices(NewJFrame.java:195)
at com.mycompany.stats.NewJFrame.<init>(NewJFrame.java:122)
at com.mycompany.stats.Main.main(Main.java:16)'''
thank you in advance!!
Service[] services=new Service[10];
This means you created and array with 10 positions, but all those positions are empty (meaning they have null inside each and every position of the array).
So, when trying services[i].name you get the NullPointerException because services[i] is null.
There are plenty of ways to do the initialization, that depends on your business cases. But just to name two possibilities:
Initialize it at the declaration:
Service services[] = new Service[] {
new Service(),new Service(), new Service(), new Service(),new Service(),
new Service(),new Service(), new Service(), new Service(),new Service()
};
Or just before using it, in case you are not overriding it:
services[i] = new Service();
services[i].name = namee;

null object reference - confused with Objects in Java [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm confused with the objects and constructor in Java. I query from a SQLiteDatabase but I couldn't get the correct object/answer. I know my codes look messy and I need to clean it up but I don't know where to start...
public static class QObject {
public String word;
public String definition;
public QObject(String word, String definition) {
this.word = word;
this.definition = definition;
}
public QObject getAnswer(String message) {
QObject quizObject = null;
String query = "select * from " + TABLE_NAME + " where " + COL_WORD + " = '" + message + "'";
Cursor cursor = this.getDbConnection().rawQuery(query, null);
if(cursor.moveToFirst()) {
do {
String myword = cursor.getString(cursor.getColumnIndexOrThrow(COL_WORD));
String mydefinition = cursor.getString(cursor.getColumnIndexOrThrow(COL_DEFINITION));
quizObject = new QObject(word, definition);
} while (cursor.moveToNext());
}
cursor.close();
return quizObject;
}
private SQLiteDatabase getDbConnection() {
return dbHelper.getReadableDatabase();
}
}
}
public void searchName(View view) {
String word = null;
String definition = null;
DatabaseTable db = new DatabaseTable(this);
DatabaseBackend dbBackend = new DatabaseBackend(MainActivity.this);
DatabaseObject dbo = new DatabaseObject(this);
DatabaseB.QObject quizobject = new DatabaseB.QObject(word, definition);
DatabaseB.QObject allQuizQuestions = quizobject.getAnswer(message);
String answer = allQuizQuestions.definition;
TextView textView = findViewById(R.id.textView2);
textView.setText(answer);
}
The error message is null object reference:
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
...
Caused by: java.lang.NullPointerException: Attempt to read from field 'java.lang.String com.justkitting.orion.databasetest.MainActivity$DatabaseB$QObject.definition' on a null object reference
at com.justkitting.orion.databasetest.MainActivity.searchName(MainActivity.java:139)
at java.lang.reflect.Method.invoke(Native Method)
...
Many many thanks.
Your exception is thrown at this line: String answer = allQuizQuestions.definition; and it means that allQuizQuestions is null. So in the line above (DatabaseB.QObject allQuizQuestions = quizobject.getAnswer(message);) you get null from getAnswer(message) method. And this can happen if cursor.moveToFirst() returns false and you never call this line of code: quizObject = new QObject(word, definition);.
One more thing I found: constructor in this line quizObject = new QObject(word, definition); is not using Strings you found in your DB, but values of word and definition from QObject class, which are null at this point. You should use myword and mydefinition instead.
Can you post the code with the line numbers(If you are on eclipse right click on the far left side of the editor and select 'show line numbers' ). it looks like you are calling a method on an object which is null. You night need to do a null check before method invocation

Mapping key and values, adding message in Java

I have a question about mapping, map key and map values.
I am writing a chat program : I have a problem to add a message. I can't add a message. That puts me in a empty web page with an error(can't see the number and reason of error)
Can you tell me where is the problem ?
// add a message to a chatroom
#RequestMapping(value="/addMessageSalon/{salon}/{pseudo}/{message}", method = {RequestMethod.GET, RequestMethod.POST})
public String addMessageSalon(HttpServletRequest request, #PathVariable("salon") String chatroom, #PathVariable("pseudo") String username, #PathVariable("message") String message) {
Message mes = null;
mes.setMessage(message);
mes.setPseudo(username);
GestionMessages addition = (GestionMessages)request.getSession().getServletContext().getAttribute("gestionMessages");
Map<String, ArrayList<Message>> resultat = addition.getMessages();
Iterator<Map.Entry<String, ArrayList<Message>>> entries = resultat.entrySet().iterator();
// iteration
while(entries.hasNext()) {
Map.Entry<String, ArrayList<Message>> entry = entries.next();
if(!entries.hasNext() && !entry.getKey().contains(chatroom)) {
// if chatroom does not exist, we give an error
throw new IllegalArgumentException("Chatroom '" + chatroom + "' doesn't exist");
}
if(entry.getKey().contains(chatroom)){
ControleurPrincipal.getUsersInDataBase().add(username);
addition.getMessagesSalon(chatroom).add(mes);
break;
}
}
resultat = addition.getMessages();
return "redirect:/";
}
First of all:
Message mes = null;
mes.setMessage(message);
This will throw a NullPointerException, every time. So either that's the error you're getting, or that is not your code.
If that's your actual code, then you need to instantiate Message first, like this:
Message mes = new Message();
Instead of doing this
if(!entries.hasNext() && !entry.getKey().contains(monSalon)) {
you might want to do
if(!resultat.contains(monSalon)) {
and do it before the while.

add items to complicated data-struc `Map<String, Map<String,String>>` [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have the following complex data-structure:
Map<String, Map<String,String>> URL_and_entities = new HashMap<String, Map<String,String>>();
on the inside of a loop I finally want to populate it but I can't figure out how.
This is my code, it's essentially a series of nested loops that make an HTTP request to determine if they share a relationship, which is revealed by the presence (or absence) of a url. I'm trying to save the URL (if it exists), and the two entities that evoked it:
for (String entity_1 : Q_value_references_for_sentence_entities)
{
for (String entity_2 : Q_value_references_for_sentence_entities)
{
String URL_czech = "http://milenio.dcc.uchile.cl/sparql?default-graph-uri=&query=PREFIX+%3A+%3Chttp%3A%2F%2Fwww.wikidata.org%2Fentity%2F%3E%0D%0ASELECT+*+WHERE+%7B%0D%0A+++%3A"
+ entity_1 + "+%3FsimpleProperty+%3A"
+ entity_2 + "%0D%0A%7D%0D%0A&format=text%2Fhtml&timeout=0&debug=on";
URL wikidata_page = new URL(URL_czech);
HttpURLConnection wiki_connection = (HttpURLConnection)wikidata_page.openConnection();
InputStream wikiInputStream = null;
try
{
// try to connect and use the input stream
wiki_connection.connect();
wikiInputStream = wiki_connection.getInputStream();
}
catch(IOException error)
{
// failed, try using the error stream
wikiInputStream = wiki_connection.getErrorStream();
}
// parse the input stream using Jsoup
Document docx = Jsoup.parse(wikiInputStream, null, wikidata_page.getProtocol()+"://"+wikidata_page.getHost()+"/");
Elements link_text = docx.select("table.sparql > tbody > tr:nth-child(2) > td > a");
//link_text.text();
for (Element l : link_text)
{
String output = l.text();
output = output.substring(0, output.length()-1);
list_of_relation_URLs.add( output );
URL_and_entities.put( output , (entity_1, entity_2));
}
}
}
I'm not oppoed to using that crazy google library of wonky data-strucs, I've used it before, but in this case I can't see a compelling reason why it would be any better than Map<String, Map<String,String>>
Update
I'm having trouble getting the values out. This doesn't work it seems
String first__english_lang_Q = retrieved_entities.getKey();
String second_english_lang_Q = retrieved_entities.getValue();
System.out.println("`(" + value + ")'" + "`( " + entity_1 + ", " + entity_2 + ")'");
You just need a tuple, You can use the apache common Pair
Map<String, Pair<String,String>> URL_and_entities = new HashMap<String, Pair<String,String>>();
URL_and_entities.put("something", Pair.of("left", "right"))
URL_and_entities.get("something").getLeft();
URL_and_entities.get("something").getRight();
Try this:
Map<String,String> entities;
for (String entity_1 : Q_value_references_for_sentence_entities)
{
for (String entity_2 : Q_value_references_for_sentence_entities)
{
entities = new HashMap<String, String>();
entities.put(entity_1, entity_2);
...check that URL exist and doesn't return null, and then convert it to a String...
URL_and_entities.put(output, entities);
}
}
}
I don't understand though, why you are using a Map to store the two entities. Unless you plan on using one entity to reference the second entity, you can simply store the two entities in a simple array (or technically even an ArrayList or HashSet would be better than a Map).
Just do:
Map<String, String[]> URL_and_entities = new HashMap<String, String[]>();
String [] entities = new String[2];
for (String entity_1 : Q_value_references_for_sentence_entities)
{
for (String entity_2 : Q_value_references_for_sentence_entities)
{
entities[0] = entity_1;
entities[1] = entity_2;
...check that URL exist and doesn't return null, and then convert it to a String...
URL_and_entities.put(output, entities);
}
}
}
Then to retrieve and print all the values in the set you just do:
for (String url: byLetter.keySet()) {
String [] retrievedValues = URL_and_entities.get(url);
System.out.println(url + " " + retrievedValues[0] + ", " + retrievedValues[1];
}
If using an ArrayList do:
for (String url: byLetter.keySet()) {
ArrayList retrievedValues = URL_and_entities.get(url);
System.out.println(url + " " + retrievedValues.get(0) + ", " + retrievedValues.get(1);
}

why is there a null pointer exception in the for loop, when I can have access the array element?

I am using temboo to get all the events for a calendar. However, i am trying to create a hashtable of the events and the days. but the for loop says its a null pointer exception even though the program is actually able to access that ith element. I have even printed it and the i is less than the size of the array. Here is the snippet code: Error is in the second line of the for loop.Errr occurs when i = 23, but items.size is 41.
GetAllEvents getAllEventsChoreo = new GetAllEvents(session);
// Get an InputSet object for the choreo
GetAllEventsInputSet getAllEventsInputs = getAllEventsChoreo.newInputSet();
// Set inputs
getAllEventsInputs.set_AccessToken(accessToken);
getAllEventsInputs.set_ClientID(clientID);
getAllEventsInputs.set_ClientSecret(clientSecret);
getAllEventsInputs.set_CalendarID(callIDs[0]);
// Execute Choreo
GetAllEventsResultSet getAllEventsResults = getAllEventsChoreo.execute(getAllEventsInputs);
results = getAllEventsResults.get_Response();
System.out.println(results);
root = jp.parse(results);
rootobj = root.getAsJsonObject();
JsonArray items = rootobj.get("items").getAsJsonArray();
System.out.println("Abour to enter the for loop\nItems:\n"+items.toString());
System.out.println("****************************\nEnter the for loop");
System.out.println("iems Size: "+items.size());
System.out.println(items.get(23).toString());
for(int i = 0;i < items.size();i++)
{
System.out.println("i: "+i);
String startTime = items.get(i).getAsJsonObject().get("start").getAsJsonObject().get("dateTime").getAsString();
System.out.println("startTime: "+startTime);
String dayKey = startTime.split("T")[0];
if(dayKey.equals(beginDate)==false | dayKey.equals(endDate)==false)
{
System.out.println(startTime + " not the one interested so skipping");
continue;
}
System.out.println("passed the first if in for loop");
String endTime = items.get(i).getAsJsonObject().get("end").getAsJsonObject().get("dateTime").getAsString();
String name = items.get(i).getAsJsonObject().get("summary").getAsJsonPrimitive().getAsString();
calendarEvent eventTemp = new calendarEvent(name,startTime,endTime);
if(table.containsKey(dayKey))
table.get(dayKey).add(eventTemp);
else
{
ArrayList<calendarEvent> schedule = new ArrayList<calendarEvent>();
schedule.add(eventTemp);
table.put(dayKey,schedule);
}
}
Set<String> key = table.keySet();
Iterator<String> it = key.iterator();
while(it.hasNext())
{
String keyValue = it.next();
System.out.println("Events on "+keyValue);
ArrayList<calendarEvent> temp = table.get(keyValue);
for(int j =0;j<temp.size();j++)
{
System.out.println(temp.get(j));
}
}
After breaking down the exception line, the exception occurs when I try to get the dateTime as string, the last part creates an exception.
Just because the ith element of an array exists, it does not mean that the element is not null.
Referencing a property or method of such an element will yield a NullPointerException.
If i went beyond the bounds of the array, you would get an ArrayIndexOutOfBoundsException instead.
Check indexed array elements for null before using them.
Sorry to be brief and not reference your code or other sources. I am on my phone. The likely source of your problem is pretty clear, though.

Categories

Resources