Get the file path from jcombobox - java

I am trying to select my file from the jcombobox and display the data in a text area. Currently, I have list out the file name but now once i select the filename from the dropdown its showing me this error:
SEVERE: null
This is my current code:
private void jCmboxActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//JComboBox jCmbox = (JComboBox)evt.getSource();
String stateName = (String)jCmbox.getSelectedItem();
updateData(stateName);
}
public void updateData(String path){
String csvFilename = "";
URL url;
try {
url = new URL(csvFilename);
} catch (MalformedURLException ex) {
Logger.getLogger(VisualizationPanel.class.getName()).log(Level.SEVERE, null, ex);
}
url = VisualizationPanel.class.getResource(path);
CSVData data = CSVData.loadFromFile(url.toString()); //loads the csv data
VisualizationPanel visPanel = new VisualizationPanel(this, data); //draws the vis panel and adds the data to it
}
I am new to java can someone pls help me on this. Thank you.

In updateData() you are creating a new URL from an empty string. This is what is throwing your exception.
You can see that on the first line of updateData() you define csvFilename to be an empty string. You never reassign a value to that variable so when you come to use it in the URL constructor it is still empty.
We can see from the URL constructor spec that a the exception you are seeing will be thrown if something is wrong with the spec.
What you could do is change the line String csvFilename = ""; to String csvFilename = path;, and see if that fixes your issue.
In fact, though, since you are rewriting your URL variable straight after the try catch you should just be able to remove that block and avoid the issue completely. Try this:
public void updateData(String path){
String csvFilename = "";
URL url = VisualizationPanel.class.getResource(path);
CSVData data = CSVData.loadFromFile(url.toString()); //loads the csv data
VisualizationPanel visPanel = new VisualizationPanel(this, data); //draws the vis panel and adds the data to it
}

Related

Requested data cannot be store inside variable in Java

I am trying getting data from an API using volley. I am trying to store it as a global variable, but it always returns null. Why?
Here is my sample code:
JsonObjectRequest jsonRequest = new JsonObjectRequest
(Request.Method.GET, url, null, response -> {
try {
if (response.getString("action").equals("success")) {
checkInTime = response.getString("checkin");
checkOutTime = response.getString("chekout");
System.out.println(response);
}
} catch (JSONException e) {
e.printStackTrace();
}
}, Throwable::printStackTrace);
Volley.newRequestQueue(MainActivity.this).add(jsonRequest);
What is the problem here?
here is my api json response
{"action":"success","checkin":"08:30:25","chekout":"blank"}
It does not working out of the request parenthesis
because this variable is temporary and it can be null if no data found.
So you have to write looks like
public static String checkInTime = "";
public static String checkOutTime = "";
After declaring global variable of String you can store data and can access from anywhere
checkInTime = response.getString("checkin");
checkOutTime = response.getString("chekout");
Its actually working for me
From the context you provided I guess you have a problem with some of these lines:
if (response.getString("action").equals("success")) {
checkInTime = response.getString("checkin");
checkOutTime = response.getString("chekout");
Reason 1 - you are not entering the if body
Reason 2 - you are not getting the response values properly
Try to debug the function
If I need to debug it I will:
Print the response before the IF statement
Print these values:
response.getString("action") checkInTime = response.getString("checkin"); checkOutTime = response.getString("chekout");
If it's being done from an Activity:
create a variable, e.g.:
public class MainActivity extends AppCompatActivity {
private String checkInTime;
Then in the code you posted above, add:
if (response.getString("action").equals("success")) {
this.checkInTime = response.getString("checkin");
Now try to access it from other places.
If it's not what you are looking for, please update the question with the relevant code regarding your global variable.

Java Swing app trying to populate JComboBox on button click

I am learning Java Swing. I am trying to develop as simple app for learning purpose. There is are multiple issues in following code. I try to read a csv file and populate JComboBox on button click.
public class MyForm {
private JButton btnRead;
private JButton btnRead2;
private JComboBox cbCodes;
private JPanel mainPanel;
private DefaultComboBoxModel comboBoxModel;
public MyForm(){
// issue 1: I always get null pointer exception in this line
comboBoxModel = new DefaultComboBoxModel();
cbCodes = new JComboBox(comboBoxModel);
btnRead.addActionListener( e -> {
List<String[]> data = readData();
comboBoxModel.removeAllElements();
data.forEach(item -> comboBoxModel.addElement(item));
});
// issue 2: Since DefaultComboBoxModel was not working. I tried without it. As this I get correct data in the array. But when I make JComboBox with array. Nothing is filled. It is empty.
btnRead2.addActionListener( e -> {
List<String[]> data = readData();
String[] array = new String[data.size()];
data.toArray(array);
cbCodes = new JComboBox(array);
});
}
// issue 3: I can't complie the code without this empty method. Why do I need it?
// error: Form contains components with Custom Create option but no createUIComponents() method
void createUIComponents(){
}
public List<String[]> readData() {
String file = "data.csv";
List<String[]> content = new ArrayList<>();
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
String line = "";
while ((line = br.readLine()) != null) {
if(line.contains("\"")){
content.add(line.split(" "));
}
content.add(line.split(","));
}
} catch (FileNotFoundException e) {
//Some error logging
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
public static void main(String[] args) {
JFrame frame = new JFrame("MyForm");
frame.setContentPane(new MyForm().mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
I make my question in the source code with the comment to show exactly here those issues are involved.
You don't get the NullPointerException in the lines you indicated, but in the line btnRead.addActionListener( e -> { because btnRead has not been initialized yet!
When you create a new JComboBox, you have to add it to the panel, too. Just creating it with new will not display it. But the real problem behind it is: you're using the model wrong. Write
comboBoxModel.removeAllElements();
for (final String string : array) {
comboBoxModel.addElement(string);
}
to solve that.
The problem you have here does not lie within the code you provided, but from another component. At some point, someone used a UI designer. Those designers usually create initialization methods, just like createUIComponents. See where that method gets called.
Synopsis:
All in all, your code is really chaotic. Restructure from new, this will clean up a lot of problems.
And initialize UI components as soon as possible, best do it in the declaration line: private final JButton btnRead = new JButton("Read!");
I strongly recommend using an IDE like Eclipse or IntelliJ that will help you write clean code and see and correct problems easier.

How can I get a variable from a method in java without invoking said method?

I'm coding a small audio player and need help here; the method fopen() is called by a button press in another class (not the issue here); the problem is that I cannot get the file's path as a string without calling the method.
The playsound() method needs the filepath variable from fopen(), and if I use the String 'path' (initialized after fopen()) it calls the method again.
I ONLY need the 'filepath' variable, but I cannot access it outside of fopen(), or at least not that I know of. Assistance on how I can access filepath without invoking fopen()?
EDIT: Fixed fopen() being set up to return a 'File' instead of a string. Also made some changes to the code; the issue of having fopen() called when it's not supposed to be is fixed, but now it gives me a java.io.FileNotFoundException: when I call playsound() (which, from what I understand, means that the file's path and/or name wasn't even recorded). What else is going on here?
Edit 2: I'm just going to ask another question, seeing as the problem at hand seems to have been answered, and I have an entirely different one on my hands.
package mediaz;
import javazoom.jl.player.*;
import javax.swing.filechooser.*;
import java.io.*;
import javax.swing.JFileChooser;
public class audio {
private String lastfilepath = "";
public String fopen(){
JFileChooser fc= new JFileChooser();
FileNameExtensionFilter filtermp3 = new FileNameExtensionFilter("MPEG-2
Audio Layer III", "mp3");
fc.setFileFilter(filtermp3);
int ret = fc.showOpenDialog(null);
if (ret == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
String filepath = file.getAbsolutePath();
this.lastfilepath = filepath;
return filepath;
}
else
return null;
}
String path = fopen();
void playsound(){
System.out.println("You pressed play.");
try{
FileInputStream fis = new FileInputStream(this.lastfilepath);
Player playMP3 = new Player(fis);
playMP3.play();
}
catch(Exception e){
System.out.println("Error: '" + e +"'");
}
}
// IGNORE WHAT'S BELOW HERE //
void rewsound(){
System.out.println("You pressed rewind.");
}
void pausesound(){
System.out.println("You pressed pause.");
}
/* void forwardsound(){
System.out.println("You pressed fast forward.");
}
*/
}
Create a String instance variable in audio, and then when you call fopen() store the currently selected file's path in that string.
See code below. Untested, but the idea is here. Also, the formatting of this code is pretty bad, it's hard to read. This is what it should look like (ish).
Edit: Added some comments in the code on general improvements/coding style
Edit: For more info on the try I updated in the code, see: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
package mediaz;
import javazoom.jl.player.*;
import javax.swing.filechooser.*;
import java.io.*;
import javax.swing.JFileChooser;
public class audio {
private String filePath = "";
public File fopen() {
JFileChooser fc = new JFileChooser();
FileNameExtensionFilter filtermp3 = new FileNameExtensionFilter("MPEG-2
Audio Layer III ", "
mp3 ");
fc.setFileFilter(filtermp3); int ret = fc.showOpenDialog(null);
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
this.filePath = file.getAbsolutePath()
return filepath; // should be file
} else // give me braces please!
return null;
}
// try to stick to camelCase, it is the 'Java' way
void playsound() {
System.out.println("You pressed play.");
// streams implement AutoCloseable, use it
// also, you were not closing fis as it was
try (FileInputStream fis = new FileInputStream(this.filePath)) {
Player playMP3 = new Player(fis);
playMP3.play();
} catch (Exception e) {
System.out.println("Error: '" + e + "'");
}
}
}
Your fopen() method is declared to return a File, yet in the method you return a String. If you returned the file that the user selected, and then stored this reference somewhere, you could ask that file for its path any time you wanted.
Create another method that returns the last filepath determined in fopen(), eg:
private String lastFilepath;
public String fopen() {
// logic for determining filepath
lastFilepath = filepath;
return filepath;
}
public String getLastFilepath() {
return lastFilepath;
}
First of all you should read about scopes in java programming.
What you currently have is a local scope for your variable "filepath". To make it accessible outside its method block you can either return it as the method result or asign it to a instance variable.
In addition please note that your fopen() method currently won't compile cause it is declared to return a File but inside tries to return a String type.
I would recommend the following:
public class foo {
private String filePath;
private void readFile() {
filePath = doReadingHere();
}
private void useFilePath() {
System.out.println(filePath);
// do what ever you like to do with the instance variable filePath
}
}

How to copy notes item using Java

I would like to copy note item from one note document to the other using Java below is the my lotus script version of what i want to achive in Java
Sub CopyItem(FromDoc As NotesDocument, ToDoc As NotesDocument, itemName As String)
Dim FromItem As NotesItem
Dim ToItem As NotesItem
If Not (FromDoc.Hasitem(itemName)) Then Exit Sub
Set FromItem = FromDoc.GetFirstItem(itemName)
If Not ToDoc.hasitem(itemName) Then Set ToItem = ToDoc.CreateItem(itemName)
ToItem.Values = FromDoc.Values
End Sub
I have tried the below:
public static void copyAnItem(Document FromDoc, Document ToDoc, String sItemName){
Vector<String> FromItem = new Vector<String>();
Vector<String> ToItem = new Vector<String>();
if(!FromDoc.hasItem((itemName))){
return;
}
FromItem = FromDoc.getItemValue(itemName);
if(!ToDoc.hasItem(sItemName)){
ToItem.add(itemName);
}
ToItem.addAll(FromDoc);
}
public static void copyAnItem(Document fromDoc, Document toDoc, String itemName){
try {
if(fromDoc.hasItem(itemName)) {
toDoc.copyItem(fromDoc.getFirstItem(itemName));
}
} catch (NotesException e) {
// your exception handling
}
}
You can get the whole item including all properties from fromDoc with getFirstItem and can copy it to toDoc with copyItem in just one line of code.
public static void copyAnItem(Document FromDoc, Document ToDoc, String sItemName){
if(FromDoc.hasItem(sItemName)){
ToDoc.replaceItemValue(sItemName, FromDoc.getItemValue(sItemName));
}
}
It won't work with Authors or Readers items. Better the Knut solution :)

How to pass a file location as a parameter as a string?

Currently I pass a hardcoded string file location to my object method which uses the string in the .getResources() method to load an image file. I am now trying to chooses an image using a load button and pass the loaded file location as a string into the getResource() method. I am using the filename.getAbsolutePath() method to retrieve the file location then passing the filename variable into the object method however this provides me with the following error -
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException.
The line of code that it points to having the error is the .getResources line where the image is loaded. I will post the code below to better understand my problem.
btnLoad.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
File loadImage = fc.getSelectedFile();
String filename = loadImage.getAbsolutePath();
filename = filename.replaceAll("\\\\", "\\\\\\\\");
picLocation = filename;
ImageSwing imageSwing = new ImageSwing(filename);
System.out.println(filename);
}
}
The output of the file name is correct yet it still wont pass into the object.
public class ImageSwing extends JFrame
{
public JLabel label;
public ImageSwing(String S){
super("Card Stunt"); //Window Title
setLayout(new FlowLayout()); //lookup grid layout
Icon flag = new ImageIcon(getClass().getResource(S));
label = new JLabel(flag);
label.setToolTipText(S);
setSize(1350, 800);
//setMinimumSize(new Dimension(1200, 760));
}//main
}
It seems like you create an absolute filename with loadImage.getAbsolutePath(), but then you try to use this as a class path resource with new ImageIcon(getClass().getResource(S)).
Instead, you should just pass the absolute filename, as a string, to ImageIcon:
Icon flag = new ImageIcon(S);
Also, don't forget to add the label to the frame...
getContentPane().add(label);
Also, I'm not on Windows right now, but I don't think filename.replaceAll("\\\\", "\\\\\\\\"); is necessary.

Categories

Resources