Parsing JSON format from an HttpConnection - java

I am trying to read an API link which contains data of JSON format. this is what i am trying to read and display on the phone:
[[],{"index":"2","name":"jim","email":"jim#outlook.com","contact":"0122511336","username":"jim","password":"jim","photo":"student.jpg","status":"Active"}]
The program supposed to authenticate the username and password inputs and this dipsplay the content of the above from URL.
Below is the codes and so far what I have done. Please someone help me to get this through.
package org.json.me;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class Login extends MIDlet implements CommandListener {
private String name;
private String email;
private int contact;
private String username;
private String password;
private String status;
private final String JSONformat = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name=name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email=email;
}
public int getContact() {
return contact;
}
public void setContact (int contact) {
this.contact=contact;
}
public String getUsername () {
return username;
}
public void setUsername (String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword (String Password) {
this.password = password;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status=status;
}
public String toString() {
return getName()+""+getEmail()+""+getContact()+""+getUsername()+""+getPassword()+""+getStatus();
}
public String fromJSON(String jsonString) {
try {
JSONObject json = new JSONObject(jsonString);
setName(json.getString("name"));
setEmail(json.getString("email"));
setContact(json.getInt("contact"));
setUsername(json.getString("username"));
setPassword(json.getString("password"));
setStatus(json.getString("status"));
}
catch (JSONException e) {
e.printStackTrace();
}
return JSONformat;
}
TextField UserName = null;
TextField Password = null;
Form authForm, mainscreen;
TextBox t = null;
StringBuffer b = new StringBuffer();
private Display myDisplay = null;
private Command okCommand = new Command("OK", Command.OK, 1);
private Command exitCommand = new Command("Exit", Command.EXIT, 2);
private Command backCommand = new Command("Back", Command.BACK, 2);
private Alert alert = null;
public Login() {
myDisplay = Display.getDisplay(this);
UserName = new TextField("Username", "", 10, TextField.ANY);
Password = new TextField("Password", "", 10, TextField.ANY);
authForm = new Form("Identification");
mainscreen = new Form("Logging IN");
mainscreen.append("Logging in....");
mainscreen.addCommand(backCommand);
authForm.append(UserName);
authForm.append(Password);
authForm.addCommand(okCommand);
authForm.addCommand(exitCommand);
authForm.setCommandListener(this);
myDisplay.setCurrent(authForm);
}
public void startApp() throws MIDletStateChangeException {
}
public void pauseApp() {
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
}
public void commandAction(Command c, Displayable d) {
if ((c == okCommand) && (d == authForm)) {
if (UserName.getString().equals("") || Password.getString().equals("")) {
alert = new Alert("Error", "You should enter Username and Password", null,AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
myDisplay.setCurrent(alert);
}
else {
//myDisplay.setCurrent(mainscreen);
login(UserName.getString(), Password.getString());
}
}
if ((c == backCommand) && (d == mainscreen)) {
myDisplay.setCurrent(authForm);
}
if ((c == exitCommand) && (d == authForm)) {
notifyDestroyed();
}
}
public void login(String UserName, String PassWord) {
HttpConnection connection = null;
DataInputStream in = null;
String base = "http://sunday-tech.com/chunghua/api/login.php";
String url = base + "?username=" + UserName + "&password=" + PassWord;
OutputStream out = null;
try
{
connection = (HttpConnection) Connector.open(url);
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("IF-Modified-Since", "2 Oct 2002 15:10:15 GMT");
connection.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
connection.setRequestProperty("Content-Language", "en-CA");
connection.setRequestProperty("Content-Length", "" + (UserName.length() + PassWord.length()));
connection.setRequestProperty("UserName", UserName);
connection.setRequestProperty("PassWord", PassWord);
out = connection.openDataOutputStream();
out.flush();
in = connection.openDataInputStream();
int ch;
while ((ch = in.read()) != -1) {
b.append((char) ch);
//System.out.println((char)ch);
}
mainscreen.append(fromJSON(b.toString()));
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (connection != null) {
connection.close();
}
}
catch (Exception x) {
}
myDisplay.setCurrent(mainscreen);
}
}

Change your setter methods to also change the TextField values. For example
public void setUsername (String username) {
this.username = username;
this.UserName.setString(username);
}

Related

How to send data to a discord webhook in java using a single .java file?

I'm working on a Minecraft mod that requires sending a string of data to a discord webhook. What would the most efficient way to achieve this using a singular .java file?
You can use this which personally works for me. This is the full code if the gist expire:
import javax.net.ssl.HttpsURLConnection;
import java.awt.Color;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Class used to execute Discord Webhooks with low effort
* Come from: https://gist.github.com/k3kdude/fba6f6b37594eae3d6f9475330733bdb
*/
public class DiscordWebhook {
private final String url;
private String content;
private String username;
private String avatarUrl;
private boolean tts;
private List<EmbedObject> embeds = new ArrayList<>();
/**
* Constructs a new DiscordWebhook instance
*
* #param url The webhook URL obtained in Discord
*/
public DiscordWebhook(String url) {
this.url = url;
}
public void setContent(String content) {
this.content = content;
}
public void setUsername(String username) {
this.username = username;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
public void setTts(boolean tts) {
this.tts = tts;
}
public void addEmbed(EmbedObject embed) {
this.embeds.add(embed);
}
public void execute() throws IOException {
if (this.content == null && this.embeds.isEmpty()) {
throw new IllegalArgumentException("Set content or add at least one EmbedObject");
}
JSONObject json = new JSONObject();
json.put("content", this.content);
json.put("username", this.username);
json.put("avatar_url", this.avatarUrl);
json.put("tts", this.tts);
if (!this.embeds.isEmpty()) {
List<JSONObject> embedObjects = new ArrayList<>();
for (EmbedObject embed : this.embeds) {
JSONObject jsonEmbed = new JSONObject();
jsonEmbed.put("title", embed.getTitle());
jsonEmbed.put("description", embed.getDescription());
jsonEmbed.put("url", embed.getUrl());
if (embed.getColor() != null) {
Color color = embed.getColor();
int rgb = color.getRed();
rgb = (rgb << 8) + color.getGreen();
rgb = (rgb << 8) + color.getBlue();
jsonEmbed.put("color", rgb);
}
EmbedObject.Footer footer = embed.getFooter();
EmbedObject.Image image = embed.getImage();
EmbedObject.Thumbnail thumbnail = embed.getThumbnail();
EmbedObject.Author author = embed.getAuthor();
List<EmbedObject.Field> fields = embed.getFields();
if (footer != null) {
JSONObject jsonFooter = new JSONObject();
jsonFooter.put("text", footer.getText());
jsonFooter.put("icon_url", footer.getIconUrl());
jsonEmbed.put("footer", jsonFooter);
}
if (image != null) {
JSONObject jsonImage = new JSONObject();
jsonImage.put("url", image.getUrl());
jsonEmbed.put("image", jsonImage);
}
if (thumbnail != null) {
JSONObject jsonThumbnail = new JSONObject();
jsonThumbnail.put("url", thumbnail.getUrl());
jsonEmbed.put("thumbnail", jsonThumbnail);
}
if (author != null) {
JSONObject jsonAuthor = new JSONObject();
jsonAuthor.put("name", author.getName());
jsonAuthor.put("url", author.getUrl());
jsonAuthor.put("icon_url", author.getIconUrl());
jsonEmbed.put("author", jsonAuthor);
}
List<JSONObject> jsonFields = new ArrayList<>();
for (EmbedObject.Field field : fields) {
JSONObject jsonField = new JSONObject();
jsonField.put("name", field.getName());
jsonField.put("value", field.getValue());
jsonField.put("inline", field.isInline());
jsonFields.add(jsonField);
}
jsonEmbed.put("fields", jsonFields.toArray());
embedObjects.add(jsonEmbed);
}
json.put("embeds", embedObjects.toArray());
}
URL url = new URL(this.url);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.addRequestProperty("Content-Type", "application/json");
connection.addRequestProperty("User-Agent", "Java-DiscordWebhook-BY-Gelox_");
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream stream = connection.getOutputStream();
stream.write(json.toString().getBytes());
stream.flush();
stream.close();
connection.getInputStream().close(); //I'm not sure why but it doesn't work without getting the InputStream
connection.disconnect();
}
public static class EmbedObject {
private String title;
private String description;
private String url;
private Color color;
private Footer footer;
private Thumbnail thumbnail;
private Image image;
private Author author;
private List<Field> fields = new ArrayList<>();
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getUrl() {
return url;
}
public Color getColor() {
return color;
}
public Footer getFooter() {
return footer;
}
public Thumbnail getThumbnail() {
return thumbnail;
}
public Image getImage() {
return image;
}
public Author getAuthor() {
return author;
}
public List<Field> getFields() {
return fields;
}
public EmbedObject setTitle(String title) {
this.title = title;
return this;
}
public EmbedObject setDescription(String description) {
this.description = description;
return this;
}
public EmbedObject setUrl(String url) {
this.url = url;
return this;
}
public EmbedObject setColor(Color color) {
this.color = color;
return this;
}
public EmbedObject setFooter(String text, String icon) {
this.footer = new Footer(text, icon);
return this;
}
public EmbedObject setThumbnail(String url) {
this.thumbnail = new Thumbnail(url);
return this;
}
public EmbedObject setImage(String url) {
this.image = new Image(url);
return this;
}
public EmbedObject setAuthor(String name, String url, String icon) {
this.author = new Author(name, url, icon);
return this;
}
public EmbedObject addField(String name, String value, boolean inline) {
this.fields.add(new Field(name, value, inline));
return this;
}
private class Footer {
private String text;
private String iconUrl;
private Footer(String text, String iconUrl) {
this.text = text;
this.iconUrl = iconUrl;
}
private String getText() {
return text;
}
private String getIconUrl() {
return iconUrl;
}
}
private class Thumbnail {
private String url;
private Thumbnail(String url) {
this.url = url;
}
private String getUrl() {
return url;
}
}
private class Image {
private String url;
private Image(String url) {
this.url = url;
}
private String getUrl() {
return url;
}
}
private class Author {
private String name;
private String url;
private String iconUrl;
private Author(String name, String url, String iconUrl) {
this.name = name;
this.url = url;
this.iconUrl = iconUrl;
}
private String getName() {
return name;
}
private String getUrl() {
return url;
}
private String getIconUrl() {
return iconUrl;
}
}
private class Field {
private String name;
private String value;
private boolean inline;
private Field(String name, String value, boolean inline) {
this.name = name;
this.value = value;
this.inline = inline;
}
private String getName() {
return name;
}
private String getValue() {
return value;
}
private boolean isInline() {
return inline;
}
}
}
private class JSONObject {
private final HashMap<String, Object> map = new HashMap<>();
void put(String key, Object value) {
if (value != null) {
map.put(key, value);
}
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
Set<Map.Entry<String, Object>> entrySet = map.entrySet();
builder.append("{");
int i = 0;
for (Map.Entry<String, Object> entry : entrySet) {
Object val = entry.getValue();
builder.append(quote(entry.getKey())).append(":");
if (val instanceof String) {
builder.append(quote(String.valueOf(val)));
} else if (val instanceof Integer) {
builder.append(Integer.valueOf(String.valueOf(val)));
} else if (val instanceof Boolean) {
builder.append(val);
} else if (val instanceof JSONObject) {
builder.append(val.toString());
} else if (val.getClass().isArray()) {
builder.append("[");
int len = Array.getLength(val);
for (int j = 0; j < len; j++) {
builder.append(Array.get(val, j).toString()).append(j != len - 1 ? "," : "");
}
builder.append("]");
}
builder.append(++i == entrySet.size() ? "}" : ",");
}
return builder.toString();
}
private String quote(String string) {
return "\"" + string + "\"";
}
}
}
To use it, you have to do something like that:
DiscordWebhook webhook = new DiscordWebhook("https://discordapp.com/api/webhooks/...");
webhook.setContent("Any message!");
webhook.setAvatarUrl("https://your.awesome/image.png");
webhook.setUsername("Custom Usernames!");
webhook.setTts(true);
webhook.addEmbed(new DiscordWebhook.EmbedObject()
.setTitle("Title")
.setDescription("This is a description")
.setColor(Color.RED)
.addField("1st Field", "Inline", true)
.addField("2nd Field", "Inline", true)
.addField("3rd Field", "No-Inline", false)
.setThumbnail("https://kryptongta.com/images/kryptonlogo.png")
.setFooter("Footer text", "https://kryptongta.com/images/kryptonlogodark.png")
.setImage("https://kryptongta.com/images/kryptontitle2.png")
.setAuthor("Author Name", "https://kryptongta.com", "https://kryptongta.com/images/kryptonlogowide.png")
.setUrl("https://kryptongta.com"));
webhook.addEmbed(new DiscordWebhook.EmbedObject()
.setDescription("Just another added embed object!"));
webhook.execute(); //Handle exception

Age filter in Java with ArrayList

I want to make a method that tells me who is the oldest person in the ArrayList and who is the youngest person. The method will receive the arraylist that i want to apply the method, i have 3 in my code, each one is an contact list.
The method is suppose to return the name of the person, but i don't know how to do it. Familia, Profissional and Amigos are my arraylists and "idade" = age and "nome" = name.
package com.company;
public class Contato {
public String nome;
public int idade;
public String sexo;
public String profissao;
public String telefone;
public String email;
public Contato(String nome, int idade, String sexo, String profissao, String telefone, String email) {
this.nome = nome;
this.idade = idade;
this.sexo = sexo;
this.profissao = profissao;
this.telefone = telefone;
this.email = email;
}
#Override
public String toString() {
return "" +
nome + ',' +
idade + " anos de idade, " +
"do sexo " + sexo + ',' +
profissao + ',' +
" telefone nÂș " + telefone + ", " +
"e-mail:" + email;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getIdade() {
return idade;
}
public void setIdade(int idade) {
this.idade = idade;
}
public String getSexo() {
return sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
public String getProfissao() {
return profissao;
}
public void setProfissao(String profissao) {
this.profissao = profissao;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
package com.company;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class GestaoContatos extends Contato {
ArrayList<Contato> Familia = new ArrayList();
ArrayList<Contato> Amigos = new ArrayList();
ArrayList<Contato> Profissional = new ArrayList();
public GestaoContatos(Contato c) {
super(c.nome, c.idade, c.sexo, c.profissao, c.telefone, c.email);
}
public void adicionaContato(String nomeAgenda, Contato contato) {
if( nomeAgenda == "Familia"){
Familia.add(contato);
} else
if(nomeAgenda == "Amigos"){
Amigos.add(contato);
} else
if(nomeAgenda == "Profissional") {
Profissional.add(contato);
} else
System.out.println("IndispnĂ­vel");
}
public void eliminaContato(String nomeContato) {
for(int i = 0; i < Familia.size(); i++) {
if(getFamilia().contains(nomeContato)) {
Familia.remove(nomeContato);
}
}
}
public void printaLista(String nomeAgenda){
if(nomeAgenda.equals("Familia")) {
Familia.forEach(System.out::println);
}
if(nomeAgenda.equals("Amigos")) {
Amigos.forEach(System.out::println);
}
if(nomeAgenda.equals("Profissional")) {
Profissional.forEach(System.out::println);
}
else {
throw new RuntimeException("Opcao invalida");
}
}
public void tooString() {
var contatos = new ArrayList<Contato>();
Familia.forEach(it -> contatos.add(it));
Amigos.forEach(it -> contatos.add(it));
Profissional.forEach(it -> contatos.add(it));
System.out.println(contatos.toString());
}
public void olderPerson(String nomeAgenda){
int i = 0;
if (nomeAgenda.equals("Amigos")) {
for (i = 0; Familia.size(); i++) {
Familia.stream().filter();
}
}
}
public void geraListaBinaria() throws IOException {
var file = new File("C:\\Users\\Jorge Luiz\\Desktop\\contatos.txt");
var writer = new FileWriter(file.getName());
writer.write(this.getProfissional().toString());
writer.write(this.getFamilia().toString());
writer.write(this.getProfissional().toString());
writer.close();
}
public ArrayList<Contato> getFamilia() {
return Familia;
}
public void setFamilia(ArrayList<Contato> familia) {
Familia = familia;
}
public ArrayList<Contato> getAmigos() {
return Amigos;
}
public void setAmigos(ArrayList<Contato> amigos) {
Amigos = amigos;
}
public ArrayList<Contato> getProfissional() {
return Profissional;
}
public void setProfissional(ArrayList<Contato> profissional) {
Profissional = profissional;
}
}
If you want to return oldest person in one list:
public Contato oldestPerson(String nomeAgenda){
return Familia.stream()
.filter(c -> c.getNome().equals(nomeAgenda)) // contatos named nomeAgenda
.max(Comparator.comparingInt(Contato::getIdade)) // take oldest
.get();
}
For all lists you can do:
public Contato oldestPerson(){
return Stream.of(Familia, Amigos, Profissional)
.flatMap(Collection::stream) // flatting to one long stream
.filter(c -> c.getNome().equals(nomeAgenda)) // contatos named nomeAgenda
.max(Comparator.comparingInt(Contato::getIdade))
.get();
}
EDIT
Based on the comment, we should change a couple of things to achieve what you want. First, we should define a Map<String, List<Contato>> and populate it in the constructor:
private Map<String, List<Contato>> contatoGroups;
private static final String familiaKey = "Familia";
private static final String amogisKey = "Amigos";
private static final String profissionalKey = "Profissional";
public GestaoContatos(Contato c) {
super(c.nome, c.idade, c.sexo, c.profissao, c.telefone, c.email);
contatoGroups.put(familiaKey, new ArrayList<>());
contatoGroups.put(amogisKey, new ArrayList<>());
contatoGroups.put(profissionalKey, new ArrayList<>());
}
(Consider using enum instead of String as key in the map)
Then wherever you want to get a group, for example: Familia, you should do:
List<Contato> contatoes = contatoGroups.get(familiaKey);
And then we should change the oldestPerson() like this:
public Contato oldestPerson(String nomeAgenda){ // nomeAgenda could be "Familia", "Amigos"...
List<Contato> selectedGroup = contatoGroups.get(nomeAgenda);
return selectedGroup.stream()
.max(Comparator.comparingInt(Contato::getIdade)) // take oldest
.get();
}

Authentication code Java

after some research and help from a friend I could make a method (authentificate) that compare the username and password given by the user in the Main and the ones presents in the loginList. The problems is the methode always return false, and I can't find the problem.
Thanks in advance for your help.
Main
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String username;
String password;
System.out.println("Enter your username");
username = input.nextLine();
System.out.println("Enter your password");
password = input.nextLine();
UserList test2 = new UserList();
if (test2.authenticate(username, password) == true) {
System.out.println("Hi");
} else {
System.out.println("Username or/and password are wrong.");
}
}
}
User
public class User {
protected String username;
protected String password;
public User(String username, String password) {
this.password = password;
this.username = username;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
#Override
public boolean equals(Object o) {
if (o instanceof User) {
return ((User) o).username.equals(username);
}
return false;
}
#Override
public int hashCode() {
int hash = 7;
hash = 97 * hash + Objects.hashCode(this.username);
return hash;
}
}
UserList
public class UserList {
private HashSet<User> loginList;emphasized text
public UserList() {
Scanner scan;
loginList = new HashSet();
try {
scan = new Scanner(new File("src/boitedejeux/Logins.txt"));
String ligne = scan.nextLine();
while (scan.hasNext()) {
ligne = scan.nextLine();
String[] res = ligne.split(",");
loginList.add(new User(res[0], (res[1])));
}
} catch (FileNotFoundException e) {
System.out.println("Erreur");
}
}
public boolean authenticate(String username, String password) {
if (null == loginList) {
throw new IllegalStateException("The user list isn't initialised");
}
return loginList.stream()
.filter(usern -> usern.getUsername().equals(username))
.filter(passw -> passw.getPassword().equals(password))
.findFirst()
.isPresent();
}
}
Login.txt
Test, Password
Test2, Password2
Remove spaces after commas in your txt, or change the line of String[] res = ligne.split(",") to split with spaces String[] res = ligne.split(", ").

Expected BEGIN_OBJECT but was STRING at line 1 column 1 GSON

I am getting this error when querying a URL and get a json object. My json:
{"status":1,"username":"admin","nombre":"Username","email":"example#example.cl","codigo_usuario":"1","hash":"2938632bfdklsngh","imagen":"05c151584cc1e9aa2985b5bd0a3a4cd2.jpeg"}
Create the User class
public class User {
private int status;
private String username;
private String nombre;
private String email;
private String codigo_usuario;
private String hash;
private String imagen;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
public String getImagen() {
return imagen;
}
public void setImagen(String imagen) {
this.imagen = imagen;
}
public String getCodigo_usuario() {
return codigo_usuario;
}
public void setCodigo_usuario(String codigo_usuario) {
this.codigo_usuario = codigo_usuario;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "User [status=" + status + ", username=" + username
+ ", nombre=" + nombre + ", email=" + email
+ ", codigo_usuario=" + codigo_usuario + ", hash=" + hash
+ ", imagen=" + imagen + "]";
}
}
And in my class, I make the request to the URL I have this code:
public static boolean authenticate(String username, String password){
boolean error = false;
User user = null;
try {
String request = Config.getText("URL_BASE")+Config.getText("URL_AUTHENTICATE")+username+"/"+password;
HttpURLConnection conn = (HttpURLConnection) new URL(request).openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new Exception("Failed : HTTP error code : " + conn.getResponseCode());
}
user = new Gson().fromJson(new InputStreamReader(conn.getInputStream()), User.class);
System.out.println(user.toString());
conn.disconnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return error;
}
And I get the exception. I saw other post with this same error and in most the error was the json format or class that did not have the same fields. Now, check well and everything should be OK. But for some reason I receive this error
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
at com.google.gson.Gson.fromJson(Gson.java:803)
at com.google.gson.Gson.fromJson(Gson.java:741)
at controller.WService.authenticate(WService.java:29)
at view.Login._verificarLogin(Login.java:77)
at view.Login$2.actionPerformed(Login.java:44)
I'm new to Java and try to consume a web service for data and use. I think this is my best option but still do not understand the error.

java.lang.NullPointerException when populating Jtextfield using a bean class

Here is my class which is a gui consisting of two tabs, my profile and edit profile. I am having a problem at the 'myProfileTabStateChanged' method when the index value changes to 1. When tab index is 0, 'myProfile()' method executes successfully, but when index is 1, 'editProfile()' is giving too many errors. The purpose of editprofile() is simply to extract the values from a bean class and set it to the textfields appropriately. What am I doing wrong? Please note the bean class variables are being populated correctly using setter methods, but in this class I am unable to retrieve the values using the getters? Perhaps it is retrieving but problem lies in being unable to set it to textfield.
public class MainMenu extends javax.swing.JFrame {
Academic ac = new Academic();
academicBean bn = new academicBean();
/**
* Creates new form MainMenu
*/
public MainMenu() {
initComponents();
// myProfile();
// editProfile();
}
public void myProfile() {
ac.retrieveAcademic();
nameLabel.setText(""+ac.title+" "+ac.forename+" "+ac.surname);
roleLabel.setText("Role: " + ac.role);
roomLabel.setText("Room: " + ac.room);
pageLabel.setText("Page: " + ac.page);
hoursLabel.setText("Hours: " + ac.hours);
phoneLabel.setText("Phone: " + ac.phone);
mobileLabel.setText("Mobile: " + ac.mobile);
emailLabel.setText("Email: " + ac.email);
imageLabel.setIcon(ac.format);
}
public void editProfile() {
ac.retrieveAcademic();
idLabel.setText("Academic Id: "+bn.getAcademicId());
txt_title.setSelectedItem(bn.getTitle().toString());
txt_fn.setText(bn.getForename().toString());
txt_ln.setText(bn.getSurname().toString());
combo_role.setSelectedItem(bn.getRole().toString());
txt_room.setText(bn.getRoom().toString());
txt_page.setText(bn.getPage().toString());
txt_hours.setText(bn.getHours().toString());
txt_phone.setText(bn.getPhone().toString());
txt_mobile.setText(bn.getMobile().toString());
txt_email.setText(bn.getEmail().toString());
}
private void myProfileTabStateChanged(javax.swing.event.ChangeEvent evt) {
JTabbedPane sourceTabbedPane = (JTabbedPane) evt.getSource();
int index = sourceTabbedPane.getSelectedIndex();
if (index == 0) {
myProfile();
}
else if (index == 1) {
editProfile();
}
}
//Class Academic
public class Academic extends javax.swing.JFrame {
String filename = null;
int s = 0;
byte[] person_image = null;
ImageIcon format = null;
LoginBean l = new LoginBean();
Connection con = javaconnect.ConnectDB();
academicBean bean = new academicBean();
PreparedStatement pst = null;
ResultSet rs = null;
int id;
String title;
String titleValue;
String forename;
String surname;
String role;
String roleValue;
String room;
String page;
String hours;
String phone;
String mobile;
String email;
byte[] imagedata = null;
public Academic() {
initComponents();
}
#SuppressWarnings("unchecked")
public void retrieveAcademic() {
try {
pst = con
.prepareStatement("SELECT * FROM AcademicInfo where Email=? and Password=?");
pst.setString(1, l.getUsername());
pst.setString(2, l.getPassword());
rs = pst.executeQuery();
while (rs.next()) {
id = (rs.getInt(1));
bean.setAcademicId(id);
title = (rs.getString(2));
bean.setTitle(title);
forename = (rs.getString(3));
bean.setForename(forename);
surname = (rs.getString(4));
bean.setSurname(surname);
role = (rs.getString(5));
bean.setRole(role);
room = (rs.getString(6));
bean.setRoom(room);
page = (rs.getString(7));
bean.setPage(page);
hours = (rs.getString(8));
bean.setHours(hours);
phone = (rs.getString(9));
bean.setPhone(phone);
mobile = (rs.getString(10));
bean.setMobile(mobile);
email = (rs.getString(11));
bean.setEmail(email);
imagedata = (rs.getBytes("Image"));
format = new ImageIcon(imagedata);
} // end while
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Academic.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (pst != null) {
pst.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Academic.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
}
// Bean Class
public class AcademicBean {
private int academicid;
private String title;
private String forename;
private String surname;
private String role;
private String room;
private String page;
private String hours;
private String phone;
private String mobile;
private String email;
private byte [] image;
private String pass;
//Setters
public void setAcademicId (int academicid) {
this.academicid = academicid;
}
public void setTitle(String title) {
this.title = title;
}
public void setForename(String forename) {
this.forename = forename;
}
public void setSurname(String surname) {
this.surname = surname;
}
public void setRole(String role) {
this.role = role;
}
public void setRoom(String room) {
this.room = room;
}
public void setPage(String page) {
this.page = page;
}
public void setHours(String hours) {
this.hours = hours;
}
public void setPhone(String phone) {
this.phone = phone;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public void setEmail(String email) {
this.email = email;
}
public void setImage (byte [] image) {
this.image = image;
}
public void setPassword (String pass) {
this.pass= pass;
}
//Gettters
public String getPassword () {
return pass;
}
public int getAcademicId() {
return academicid;
}
public byte [] getImage() {
return image;
}
public String getTitle() {
return title;
}
public String getForename() {
return forename;
}
public String getSurname() {
return surname;
}
public String getRole() {
return role;
}
public String getRoom() {
return room;
}
public String getPage() {
return page;
}
public String getHours() {
return hours;
}
public String getPhone() {
return phone;
}
public String getMobile() {
return mobile;
}
public String getEmail() {
return email;
}
}
//Stacktrace
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at org.sqlite.PrepStmt.(PrepStmt.java:37)
at org.sqlite.Conn.prepareStatement(Conn.java:231)
at org.sqlite.Conn.prepareStatement(Conn.java:224)
at org.sqlite.Conn.prepareStatement(Conn.java:213)
at eecsCRM.Academic.retrieveAcademic(Academic.java:68)
at eecsCRM.MainMenu.editProfile(MainMenu.java:50)
at eecsCRM.MainMenu.myProfileTabStateChanged(MainMenu.java:569)
at eecsCRM.MainMenu.access$300(MainMenu.java:13)
at eecsCRM.MainMenu$4.stateChanged(MainMenu.java:194)
at javax.swing.JTabbedPane.fireStateChanged(JTabbedPane.java:400)
at javax.swing.JTabbedPane$ModelListener.stateChanged(JTabbedPane.java:253)
at javax.swing.DefaultSingleSelectionModel.fireStateChanged(DefaultSingleSelectionModel.java:116)
at javax.swing.DefaultSingleSelectionModel.setSelectedIndex(DefaultSingleSelectionModel.java:50)
at javax.swing.JTabbedPane.setSelectedIndexImpl(JTabbedPane.java:599)
at javax.swing.JTabbedPane.setSelectedIndex(JTabbedPane.java:574)
at javax.swing.plaf.basic.BasicTabbedPaneUI$Handler.mousePressed(BasicTabbedPaneUI.java:3628)
at javax.swing.plaf.synth.SynthTabbedPaneUI$1.mousePressed(SynthTabbedPaneUI.java:279)
at java.awt.AWTEventMulticaster.mousePressed(AWTEventMulticaster.java:262)
at java.awt.Component.processMouseEvent(Component.java:6264)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6032)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4235)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Just a wild a***'d guess: You appear to have at least two completely unrelated academicBean objects (note that the class should be named AcademicBean), one in Academic, and one in MainMenu. I have a suspicion that they should be one and the same.
Perhaps MainMenu should have:
academicBean bn = ac.getAcademicBean();
and Academic have:
public academicBean getAcademicBean() {
return bean;
}
so that MainMenu can extract Academic's bean making the bean variables refer to one and the same bean object.

Categories