im developing a webbapp wich receives image resources from users, but i want to validate these image to be uploaded to have specific dimensions like 600X800 etc.
I am trying to fin answers but im running out of options :).
It would be great if someone has done this before.
Thanks your help will be apreciated
Try
BufferedImage bi = ImageIO.read (file);
bi.getWidth();//width
bi.getHeight ();//height
Finally i did find the way to do it: we first get the file that its going to be uploaded, then i use a created class wich i found here on stack overflow, to find width and height of dimesions, i just play with if's then, heres the code, hope helps someone!!
public class AddPromo extends WebPage {
/**
*
*/
private FileUploadField fileUpload;
private String UPLOAD_FOLDER = "..\\Promociones\\";
private static final long serialVersionUID = 1L;
#SuppressWarnings({ "rawtypes", "unchecked" })
public AddPromo(){
add(new Label("user",ActiveUser.USER));
//Add Feedback panel
add(new FeedbackPanel("feedback_2"));
//LOGOUT LINK
Logout logoutLink = new Logout("logout");
add(logoutLink);
//Add backlink to SuccesPage
add(new Link("link_atras"){
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public void onClick(){
SuccesPage nueva = new SuccesPage("",1);
setResponsePage(nueva);
}
});
//Definitions for date attributes
final Locale selectedLocale = Session.get().getLocale();
add(new StaticImage("image_test",new Model("http://1-ps.googleusercontent.com/h/www.bizreport.com/2011/02/03/200x200xandroid-logo-200x200.jpg.pagespeed.ic.SONOBLzFc5.jpg")));
Form<?> form = new Form<Void>("form") {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void onSubmit() {
JPEGDim dims = new JPEGDim();
final FileUpload uploadedFile = fileUpload.getFileUpload();
if (uploadedFile != null) {
// write to a new file
File newFile = new File(UPLOAD_FOLDER
+ uploadedFile.getClientFileName());
try {
final Dimension d = dims.getJPEGDimension(newFile);
if (d.getWidth()==1024 || d.getHeight()==768 ) {
try {
if (newFile.exists()) {
newFile.delete();
}
newFile.createNewFile();
uploadedFile.writeTo(newFile);
info("saved file: " + uploadedFile.getClientFileName());
info("Imagen cumple con dimensiones " + d.getHeight() + " x " + d.getWidth());
} catch (Exception e) {
throw new IllegalStateException("Error "+e.toString());
}
} else {
error("Archivo no valido... " + + d.getHeight() + " x " + d.getWidth());
}
} catch (IOException e1) {
// TODO Auto-generated catch block
error(e1.toString());
}
}
}
};
// Enable multipart mode (need for uploads file)
form.setMultiPart(true);
// max upload size, 10k
form.setMaxSize(Bytes.megabytes(10));
form.add(fileUpload = new FileUploadField("fileUpload"));
add(form);
}
class JPEGDim {
public Dimension getJPEGDimension(File f) throws IOException {
FileInputStream fis = new FileInputStream(f);
// check for SOI marker
if (fis.read() != 255 || fis.read() != 216)
throw new RuntimeException("SOI (Start Of Image) marker 0xff 0xd8 missing");
Dimension d = null;
while (fis.read() == 255) {
int marker = fis.read();
int len = fis.read() << 8 | fis.read();
if (marker == 192) {
fis.skip(1);
int height = fis.read() << 8 | fis.read();
int width = fis.read() << 8 | fis.read();
d = new Dimension(width, height);
break;
}
fis.skip(len - 2);
}
fis.close();
return d;
}
}
}
Related
I'm using Encog and I ran the ocr sample. It works fine. However, I want to pass an image file (png, jpg,...) as a parameter. This image contains the text to to be recognized. Then, the system should return a string with the "same" text.
Has someone already did something similar? How should I start?
Thanks!
Step 1: In GUI create file input and take file from user
JFileChooser fc;
JButton b, b1;
JTextField tf;
FileInputStream in;
Socket s;
DataOutputStream dout;
DataInputStream din;
int i;
public void actionPerformed(ActionEvent e) {
try {
if (e.getSource() == b) {
int x = fc.showOpenDialog(null);
if (x == JFileChooser.APPROVE_OPTION) {
fileToBeSent = fc.getSelectedFile();
tf.setText(f1.getAbsolutePath());
b1.setEnabled(true);
} else {
fileToBeSent = null;
tf.setText(null;);
b1.setEnabled(false);
}
}
if (e.getSource() == b1) {
send();
}
} catch (Exception ex) {
}
}
public void copy() throws IOException {
File f1 = fc.getSelectedFile();
tf.setText(f1.getAbsolutePath());
in = new FileInputStream(f1.getAbsolutePath());
while ((i = in.read()) != -1) {
System.out.print(i);
}
}
public void send() throws IOException {
dout.write(i);
dout.flush();
}
Step 2: Down sample it
private void processNetwork() throws IOException {
System.out.println("Downsampling images...");
for (final ImagePair pair : this.imageList) {
final MLData ideal = new BasicMLData(this.outputCount);
final int idx = pair.getIdentity();
for (int i = 0; i < this.outputCount; i++) {
if (i == idx) {
ideal.setData(i, 1);
} else {
ideal.setData(i, -1);
}
}
final Image img = ImageIO.read(fc.getFile());
final ImageMLData data = new ImageMLData(img);
this.training.add(data, ideal);
}
final String strHidden1 = getArg("hidden1");
final String strHidden2 = getArg("hidden2");
this.training.downsample(this.downsampleHeight, this.downsampleWidth);
final int hidden1 = Integer.parseInt(strHidden1);
final int hidden2 = Integer.parseInt(strHidden2);
this.network = EncogUtility.simpleFeedForward(this.training
.getInputSize(), hidden1, hidden2,
this.training.getIdealSize(), true);
System.out.println("Created network: " + this.network.toString());
}
Step 3: Begin Training with training set
private void processTrain() throws IOException {
final String strMode = getArg("mode");
final String strMinutes = getArg("minutes");
final String strStrategyError = getArg("strategyerror");
final String strStrategyCycles = getArg("strategycycles");
System.out.println("Training Beginning... Output patterns="
+ this.outputCount);
final double strategyError = Double.parseDouble(strStrategyError);
final int strategyCycles = Integer.parseInt(strStrategyCycles);
final ResilientPropagation train = new ResilientPropagation(this.network, this.training);
train.addStrategy(new ResetStrategy(strategyError, strategyCycles));
if (strMode.equalsIgnoreCase("gui")) {
TrainingDialog.trainDialog(train, this.network, this.training);
} else {
final int minutes = Integer.parseInt(strMinutes);
EncogUtility.trainConsole(train, this.network, this.training,
minutes);
}
System.out.println("Training Stopped...");
}
Step 4: Give down sampled file to neural network
public void processWhatIs() throws IOException {
final String filename = getArg("image");
final File file = new File(filename);
final Image img = ImageIO.read(file);
final ImageMLData input = new ImageMLData(img);
input.downsample(this.downsample, false, this.downsampleHeight,
this.downsampleWidth, 1, -1);
final int winner = this.network.winner(input);
System.out.println("What is: " + filename + ", it seems to be: "
+ this.neuron2identity.get(winner));
}
Step 5: Check Result
I have to build a GPS parser. I need to parse the NMEA string in another thread, which will be parsing a single NMEA string and update chart at 1 Hz. For now I build part of my code, but I parse data in main thread in while loop; my teacher said that is wrong. I was programming some on Java but not in multi-threading aspects. How I could move parsing process and refreshing chart to background thread?
public class MainFrame extends JFrame {
private JButton btnWybPlik;
private JLabel jlDroga;
private JLabel jlPredkosc;
private JLabel jlCzas;
private JPanel mainjpanel;
private JPanel jpMenu;
private JPanel jpTablica;
//private String sciezkaPliku;
private SekwencjaGGA sekGGA = null;
private SekwencjaGGA popSekGGA = null;
private SekwencjaGSA sekGSA;
private SekwencjaGLL sekGLL;
private SekwencjaRMC sekRMC;
private double droga;
private double predkosc;
private XYSeries series1;
private XYSeriesCollection dataset;
public MainFrame() {
droga = 0;
btnWybPlik.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(mainjpanel);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
//System.out.println("Selected file: " + selectedFile.getAbsolutePath());
String sciezkaPliku = selectedFile.getAbsolutePath();
wczytaniePliku(sciezkaPliku);
}
}
});
jpTablica = new JPanel();
mainjpanel.add(jpTablica);
this.series1 = new XYSeries("Trasa", false);
final XYSeriesCollection dataset = new XYSeriesCollection(this.series1);
final JFreeChart chart = createChart(dataset);
final ChartPanel chartPanel = new ChartPanel(chart);
jpTablica.add(chartPanel);
}
private void wczytaniePliku(String sciezkaDoPliku) {
try (BufferedReader br = new BufferedReader(new FileReader(sciezkaDoPliku))) {
String line;
//series1.add(53.448, 14.4907);
while ((line = br.readLine()) != null) {
parseLine(line);
}
//series1.add(53.4485, 14.4910);
} catch (IOException e) {
e.printStackTrace();
}
}
private void parseLine(String line) {
String bezSumKont = line.substring(0, line.length() - 3);
List<String> podzSekw = Arrays.asList(bezSumKont.split(","));
if (podzSekw.get(0).equalsIgnoreCase("$GPGGA")) {
if (check(line)) {
if (sekGGA != null)
popSekGGA = sekGGA;
sekGGA = new SekwencjaGGA(podzSekw);
if (popSekGGA != null) {
droga += obliczOdleglosc(popSekGGA, sekGGA);
jlDroga.setText(String.valueOf(droga));
}
series1.add(sekGGA.getWspolzedne().getLongitude(), sekGGA.getWspolzedne().getLatitude());
System.out.println(sekGGA.getWspolzedne().getLatitude() + " " + sekGGA.getWspolzedne().getLongitude());
//System.out.println(series1.getMaxY() + " " + series1.getMinY());
} else {
//TODO: Zlicz błąd
}
}
if (podzSekw.get(0).equalsIgnoreCase("$GPGSA")) {
if (check(line)) {
sekGSA = new SekwencjaGSA(podzSekw);
} else {
//TODO: Zlicz błąd
}
}
if (podzSekw.get(0).equalsIgnoreCase("$GPGLL")) {
if (check(line)) {
sekGLL = new SekwencjaGLL(podzSekw);
} else {
//TODO: Zlicz błąd
}
}
if (podzSekw.get(0).equalsIgnoreCase("$GPRMC")) {
//TODO: Sekwencja RMC (Recommended minimum of data)
if (check(line)) {
sekRMC = new SekwencjaRMC(podzSekw);
} else {
//TODO: Zlicz błąd
}
}
}
private double obliczOdleglosc(SekwencjaGGA pkt1, SekwencjaGGA pkt2) {
double odleglosc = 0;
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(pkt2.getWspolzedne().getLatitude() - pkt1.getWspolzedne().getLatitude());
double dLng = Math.toRadians(pkt2.getWspolzedne().getLongitude() - pkt1.getWspolzedne().getLongitude());
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(Math.toRadians(pkt1.getWspolzedne().getLatitude())) * Math.cos(Math.toRadians(pkt1.getWspolzedne().getLatitude())) *
Math.sin(dLng / 2) * Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
odleglosc = earthRadius * c;
return odleglosc;
}
/**
* Funkcja sprawdzająca sume kontrolną
*
* #param tekst cała linia NMEA
* #return true jeśli się suma kontrolna zgadza
*/
private boolean check(String tekst) {
String suma = tekst.substring(tekst.length() - 2, tekst.length());
tekst = tekst.substring(1, tekst.length() - 3);
int checksum = 0;
for (int i = 0; i < tekst.length(); i++) {
checksum = checksum ^ tekst.charAt(i);
}
if (Integer.parseInt(suma, 16) == checksum) {
return true;
}
return false;
}
private JFreeChart createChart(final XYDataset dataset) { ... }
private void customizeChart(JFreeChart chart) { ... }
public static void main(String[] args) {
JFrame frame = new JFrame("MainFrame");
frame.setContentPane(new MainFrame().mainjpanel);
frame.setPreferredSize(new Dimension(640, 480));
frame.pack();
frame.setVisible(true);
}
To avoid blocking the event dispatch thread, construct an instance of SwingWorker. Collect data in your implementation of doInBackground(), publish() intermediate results, and update the XYSeries in your implementation of process(). The listening chart will update itself in response. A related example that uses jfreechart is seen below and examined here.
I've created an app with utilities I usually use on my pc (like sending shutdown to cmd.exe) and as some friends asked me to give it to them I was trying to add an update system that checks for updates on a server to make it easier that their version is always updated.
The thing is that I've been over the net searching any solution but all of them just tell to use .close() and my file has it right after stop needing it. When I run it everything works fine and there are no exceptions thrown, so I just dunno what can be wrong.
Whole class:
public class Main_Gui extends JFrame {
private Thread worker;
private final String root = "update/";
private JTextArea outText;
private JButton cancel;
private JButton launch;
private JScrollPane sp;
private JPanel pan1;
private JPanel pan2;
private String zipFile = "Actualización.zip";
private String path = "http://ritsu.hol.es/url.html";
private String TITLE = "RitsUtilities | Actualizador";
public Main_Gui() {
initComponents();
outText.setText("Conectando con el servidor...");
download();
}
private void initComponents() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
setTitle(TITLE);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
pan1 = new JPanel();
pan1.setLayout(new BorderLayout());
pan2 = new JPanel();
pan2.setLayout(new FlowLayout());
outText = new JTextArea();
sp = new JScrollPane();
sp.setViewportView(outText);
launch = new JButton("Ejecutar RitsUtilities");
launch.setEnabled(false);
launch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String[] run = { "java", "-jar", "RitsUtilities.jar" };
try {
Runtime.getRuntime().exec(run);
} catch (Exception ex) {
ex.printStackTrace();
}
System.exit(0);
launch();
}
});
pan2.add(launch);
cancel = new JButton("Salir");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
pan2.add(cancel);
pan1.add(sp, BorderLayout.CENTER);
pan1.add(pan2, BorderLayout.SOUTH);
add(pan1);
pack();
setSize(500, 400);
setLocationRelativeTo(null);
}
private void download() {
worker = new Thread(new Runnable() {
public void run() {
try {
downloadFile(getDownloadLinkFromHost());
unzip();
copyFiles(new File(root), new File("").getAbsolutePath());
cleanup();
launch.setEnabled(true);
outText.setText(outText.getText() + "\n¡Actualización completada con éxito!");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Ha ocurrido un error al descargar y descomprimir la actualización.", "Error 1", JOptionPane.WARNING_MESSAGE);
}
}
});
worker.start();
}
private void launch() {
String[] run = { "java", "-jar", "update app.jar" };
try {
Runtime.getRuntime().exec(run);
} catch (Exception ex) {
ex.printStackTrace();
}
System.exit(0);
}
private void cleanup() {
outText.setText(outText.getText() + "\nLimpiando archivos temporales...");
remove(new File(root));
new File(root).delete();
}
private void remove(File f) {
File[] files = f.listFiles();
for (File ff : files) {
if (ff.isDirectory()) {
remove(ff);
ff.delete();
} else {
ff.delete();
}
}
}
private void copyFiles(File f, String dir) throws IOException {
File[] files = f.listFiles();
for (File ff : files) {
if (ff.isDirectory()) {
new File(dir + "/" + ff.getName()).mkdir();
copyFiles(ff, dir + "/" + ff.getName());
} else {
copy(ff.getAbsolutePath(), dir + "/" + ff.getName());
}
}
}
public void copy(String srFile, String dtFile) throws FileNotFoundException, IOException {
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
private void unzip() throws IOException {
int BUFFER = 2048;
BufferedOutputStream dest = null;
BufferedInputStream is = null;
ZipEntry entry;
ZipFile zipfile = new ZipFile(zipFile);
Enumeration e = zipfile.entries();
(new File(root)).mkdir();
while (e.hasMoreElements()) {
entry = (ZipEntry) e.nextElement();
outText.setText(outText.getText() + "\nExtrayendo: " + entry);
if (entry.isDirectory())
(new File(root + entry.getName())).mkdir();
else {
(new File(root + entry.getName())).createNewFile();
is = new BufferedInputStream(zipfile.getInputStream(entry));
int count;
byte data[] = new byte[BUFFER];
FileOutputStream fos = new FileOutputStream(root + entry.getName());
dest = new BufferedOutputStream(fos, BUFFER);
while ((count = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
is.close();
}
}
}
private void downloadFile(String link) throws MalformedURLException, IOException {
URL url = new URL(link);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
long max = conn.getContentLength();
outText.setText(outText.getText() + "\n" + "Descargando archivo...\nTamaño de la actualización(comprimida): " + max + " Bytes");
BufferedOutputStream fOut = new BufferedOutputStream(new FileOutputStream(new File(zipFile)));
byte[] buffer = new byte[32 * 1024];
int bytesRead = 0;
int in = 0;
while ((bytesRead = is.read(buffer)) != -1) {
in += bytesRead;
fOut.write(buffer, 0, bytesRead);
}
fOut.flush();
fOut.close();
is.close();
outText.setText(outText.getText() + "\n¡Descarga completada!");
}
private String getDownloadLinkFromHost() throws MalformedURLException, IOException {
URL url = new URL(path);
InputStream html = null;
html = url.openStream();
int c = 0;
StringBuilder buffer = new StringBuilder("");
while (c != -1) {
c = html.read();
buffer.append((char) c);
}
return buffer.substring(buffer.indexOf("[url]") + 5, buffer.indexOf("[/url]"));
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main_Gui().setVisible(true);
}
});
}
}
EDIT: changed private String zipFile = "Actualización.zip"; to private String zipFile = "Update.zip"; but still just deleting temp files/directories but not that "Update.zip" folder that the app downloads.
The File#delete() method you are using doesn't throw an error if the file can't be deleted, it returns false. This is documented in the Javadoc, together with an alternative solution (emphasize mine):
Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted.
Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.
Finally it's working, just added a forced delete on run() inside download() so now my code looks like
public void run() {
try {
downloadFile(getDownloadLinkFromHost());
unzip();
copyFiles(new File(root), new File("").getAbsolutePath());
cleanup();
launch.setEnabled(true);
+ System.gc();
+ File tmpf = new File(zipFile);
+ tmpf.deleteOnExit();
outText.setText(outText.getText() + "\n¡Actualización completada con éxito!");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Ha ocurrido un error al descargar y descomprimir la actualización.", "Error 1", JOptionPane.WARNING_MESSAGE);
}
}
I'm pretty sure that there are way better ways to do this, but that one seems to work for me.
Thanks to everyone that answered and tried to help me. =D
I would suggest improving your remove(File f) method. Add some checks for the Boolean return value of ff.delete(), that will tell you if the file is actually being deleted or not.
Also, you could add some logs into that method, so you could debug what is actually doing, perhaps it's not seeing the files or something.
One last comment. You should make your code more modular. Create more abstractions and give each of them a simple task. That is the essence of Object Oriented Design. Then, you can program some JUnit tests for each object, and you can run the tests every time you make a change. I reccomend you give a look to this article on Cohesion
i have created a list filed which contains a Picture and some data in one row
the picture and data i am getting from Json. My code is working but after getting the list my UI is hanging,
There are Two steps
1) parse the data and image URL from json
2) and show in list field
I'll post my code and screen shot of List below
http://supportforums.blackberry.com/t5/image/serverpage/image-id/19759iD4089A71454F66E0/image-size/large/is-moderation-mode/true?v=mpbl-1&px=600
public final class MyScreen extends MainScreen implements ListFieldCallback
{
HttpConnection httpConn;
int responseCode;
private static ListField _list;
private static Vector listElements = new Vector();
private static Vector elements = new Vector();
private static Vector contentelements = new Vector();
private static Vector datelements = new Vector();
private static Vector Imageselements = new Vector();
LabelField label;
String imagename;
Bitmap bit ;
Connection connectionthread;
public MyScreen()
{
// Set the displayed title of the screen
//setTitle("MyTitle");
_list = new ListField();
_list.invalidate();
_list.setEmptyString("please wait..", DrawStyle.HCENTER);
_list.setRowHeight(100);
_list.setCallback(this);
add(_list);
connectionthread = new Connection();
connectionthread.start();
}
public class Connection extends Thread{
public void run() {
try {
String httpURL = "http://192.168.1.91/bjp_app/program"+ getConnectionString();
httpConn = (HttpConnection) Connector.open(httpURL);
httpConn.setRequestMethod(HttpConnection.GET);
responseCode = httpConn.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK)
{
throw new IOException("HTTP response code: "+ responseCode);
//System.out.println("\n Internaet problem HttpConnection. = "+responseCode);
}else{
System.out.println("\n elseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee= ");
System.out.println("\nHttpConnection.HTTP_OK = "+responseCode);
DataOutputStream _outStream = new DataOutputStream(httpConn.openDataOutputStream());
byte[] request_body = httpURL.getBytes();
for (int i = 0; i < request_body.length; i++) {
_outStream.writeByte(request_body[i]);
}
DataInputStream _inputStream = new DataInputStream(
httpConn.openInputStream());
StringBuffer _responseMessage = new StringBuffer();
int ch;
while ((ch = _inputStream.read()) != -1) {
_responseMessage.append((char) ch);
}
String res = (_responseMessage.toString());
String responce = res.trim();
System.out.println("\nresponce= "+responce);
JSONArray jsnarry = new JSONArray(responce);
System.out.println("\n--length----- "+jsnarry.length());
for (int i = 0; i < jsnarry.length(); i++){
JSONArray inerarray = jsnarry.getJSONArray(i);
System.out.println("\n-innerarray-length----- "+inerarray.length());
//for (int i1 = 0; i1 < inerarray.length(); i1++) {
//System.out.println("\n-inerarray-values----- "+inerarray.getString(i1));
String ID = inerarray.getString(0);
String TITTLE = inerarray.getString(1);
String CONTENT = inerarray.getString(2);
String DATE = inerarray.getString(3);
String IMAGE = inerarray.getString(4);
String six = inerarray.getString(5);
System.out.println("................................................");
System.out.println("ID= "+ID);
System.out.println("TITTLE= "+TITTLE);
System.out.println("CONTENT= "+CONTENT);
System.out.println("DATE= "+DATE);
System.out.println("IMAGE= "+IMAGE);
imagename = "http://sanjaytandon.in/admin/image/"+IMAGE.trim();
System.out.println("imagename= "+imagename);
//System.out.println("six "+six);
System.out.println("....................................................=");
// String jsonresponse = ""+inerarray.getString(i1);
//label = new LabelField(jsonresponse,LabelField.FOCUSABLE);
//add(label);
//}
elements.addElement(TITTLE);
contentelements.addElement(CONTENT);
datelements.addElement(DATE);
Imageselements.addElement(imagename);
}
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
try {
_list.setSize(elements.size());
_list.setSize(contentelements.size());
_list.setSize(datelements.size());
_list.setSize(Imageselements.size());
//invalidate();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("error _list.setSize"+e.toString());
}
}
});
}
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("\nresponce code error "+e.toString());
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Status.show("Check your internet connection!", 2000);
}
});
}
}
}
public void drawListRow (ListField listField, Graphics graphics, int index, int y, int w) {
try {
graphics.setGlobalAlpha(255);
final int margin =5;
String tittle = (String)elements.elementAt(index);
String content = (String)contentelements.elementAt(index);
String date = (String)datelements.elementAt(index);
String imagesurl = (String)Imageselements.elementAt(index);
UrlToImage img = new UrlToImage( imagesurl);
bit =img.getbitmap();
graphics.drawText(tittle.trim(), 3*margin+bit.getWidth(), y+margin);
graphics.drawText(content.trim(), 3*margin+bit.getWidth(), y+ margin+30);
graphics.drawText(date.trim(), 3*margin+bit.getWidth(), y+ margin+60);
graphics.drawBitmap(2, y+margin+5, bit.getWidth(), bit.getHeight(), bit, 0, 0);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("error drawListRow"+e.toString());
}
}
public Object get(ListField listField, int index) {
// TODO Auto-generated method stub
return null;
}
public int getPreferredWidth(ListField listField) {
// TODO Auto-generated method stub
return 0;
}
public int indexOfList(ListField listField, String prefix, int start) {
// TODO Auto-generated method stub
return 0;
}
and MY UrlToImage.java class whcih downloads the images from URL
public class UrlToImage {
public static Bitmap _bmap;
UrlToImage(final String url){
HttpConnection connection = null;
InputStream inputStream = null;
EncodedImage bitmap;
byte[] dataArray = null;
try {
connection = (HttpConnection) Connector.open(url+ getConnectionString(), Connector.READ, true);
inputStream = connection.openInputStream();
byte[] responseData = new byte[10000];
int length = 0;
StringBuffer rawResponse = new StringBuffer();
while (-1 != (length = inputStream.read(responseData)))
{
rawResponse.append(new String(responseData, 0, length));
}
int responseCode = connection.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK)
{
throw new IOException("HTTP response code: "+ responseCode);
}else{
System.out.println("\nHttpConnection.HTTP_OK = "+responseCode);
}
final String result = rawResponse.toString();
dataArray = result.getBytes();
/*System.out.println("\ndataArray.length = "+dataArray.length);
System.out.println("\ndataArray.length = "+dataArray[0]);
System.out.println("\ndataArray.length = "+dataArray[1]);
System.out.println("\ndataArray.length = "+dataArray[2]);
System.out.println("\ndataArray.length = "+dataArray[3]);*/
} catch (final Exception ex) {
}finally {
try {
inputStream.close();
inputStream = null;
connection.close();
connection = null;
}
catch(Exception e){
}
}
bitmap = EncodedImage.createEncodedImage(dataArray, 0,dataArray.length);
// this will scale your image acc. to your height and width of bitmapfield
int multH;
int multW;
int currHeight = bitmap.getHeight();
int currWidth = bitmap.getWidth();
multH= Fixed32.div(Fixed32.toFP(currHeight),Fixed32.toFP(80));//height
multW = Fixed32.div(Fixed32.toFP(currWidth),Fixed32.toFP(80));//width
bitmap = bitmap.scaleImage32(multW,multH);
_bmap=bitmap.getBitmap();
}
public String getConnectionString() {
String connectionString = null;
// Simulator behaviour is controlled by the USE_MDS_IN_SIMULATOR
// variable.
if (DeviceInfo.isSimulator()) {
connectionString = ";deviceside=true";
System.out.println("11111111111111111");
}
// Wifi is the preferred transmission method
else if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
connectionString = ";interface=wifi";
System.out.println("222222222222222222");
}
// Is the carrier network the only way to connect?
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT)
{
String carrierUid = getCarrierBIBSUid();
if (carrierUid == null) {
// Has carrier coverage, but not BIBS. So use the carrier's TCP
// network
System.out.println("33333333333333333");
connectionString = ";deviceside=true";
} else {
// otherwise, use the Uid to construct a valid carrier BIBS
// request
System.out.println("444444444444444444");
connectionString = ";deviceside=false;connectionUID="+carrierUid + ";ConnectionType=mds-public";
}
}
// Check for an MDS connection instead (BlackBerry Enterprise Server)
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS)
{
System.out.println("55555555555555555555");
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid hassling the user
// unnecssarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE)
{
System.out.println("66666666666666666666");
connectionString = "none";
}
// In theory, all bases are covered by now so this shouldn't be reachable.But hey, just in case ...
else {
System.out.println("77777777777777777777777");
connectionString = ";deviceside=true";
}
return connectionString;
}
/**//**
* Looks through the phone's service book for a carrier provided BIBS
* network
*
* #return The uid used to connect to that network.
*//*
*/ private synchronized String getCarrierBIBSUid() {
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
if (records[currentRecord].getName().toLowerCase()
.indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
return null;
}
public Bitmap getbitmap()
{
return _bmap;
}
}
For a ListField, this method:
public void drawListRow (ListField listField, Graphics graphics, int index, int y, int w)
will be called on the main (a.k.a. "UI") thread. This method is intended for drawing. However, you have these lines of code in that method:
UrlToImage img = new UrlToImage( imagesurl);
bit =img.getbitmap();
As you have implemented the UrlToImage class, that code is making a network call. Network calls should not be made on the UI thread. If you do so, your UI will hang/freeze.
What you should do is create a background worker (thread) that will go to the network to fetch your images. You can decide whether you need to load all images immediately in the background, or only load images as the user scrolls the ListField. When the images arrive (on the background thread), then you should tell the list field to redraw itself, row by row.
You might want to take a look at this recent answer, which performs lazy loading of imagery in the background. That answer is a little different, in that it uses a custom list, not the standard ListField. For a standard ListField, you can trigger a redraw of a list row with ListField#invalidate(int):
// image for row 'x' download complete. save image as member data
// that can be accessed in drawListRow().
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
_list.invalidate(x);
}
});
As you see, I've been researching and tried to set a thread in main.java class. This is the main method:
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new main().setVisible(true);
check ch = new check();
ch.start();
}
});
}
Main method calls a thread called ch , from check.java class.
This is the thread class:
public class check extends Thread {
public JTextArea estado = new JTextArea();
public JTextField updatedVersion = new JTextField();
public JLabel updatedLabel = new JLabel();
public String catchUpdatedVersion;
int UPDATENUMBER;
int CURRENTNUMBER;
public void run() {
String infURL = "https://thread.googlecode.com/svn/trunk/thread.inf";
String name = "thread.inf";
File file = new File(name);
try {
URLConnection conn = new URL(infURL).openConnection();
conn.connect();
estado.append("Conectando al servidor...");
estado.append(System.getProperty("line.separator"));
estado.append(" -- Buscando actualizaciones... --");
estado.append(System.getProperty("line.separator"));
InputStream in = conn.getInputStream();
OutputStream out = new FileOutputStream(file);
int b = 0;
while (b != -1) {
b = in.read();
if (b != -1) {
out.write(b);
}
}
out.close();
in.close();
} catch (MalformedURLException ex) {
} catch (IOException ioe) { }
String fileToReadUpdatedVersion = "thread.inf";
try {
BufferedReader br = new BufferedReader(
new FileReader(fileToReadUpdatedVersion));
String brr = br.readLine();
catchUpdatedVersion = brr.substring(34,42);
String catchUpdatedShortVersion = brr.substring(15,16);
UPDATENUMBER = Integer.parseInt(catchUpdatedShortVersion);
String fileToReadCurrentVer = "thread.inf";
BufferedReader brrw = new BufferedReader(
new FileReader(fileToReadCurrentVer));
String brrwREAD = brrw.readLine();
String catchCurrentShortVersion = brrwREAD.substring(15,16);
CURRENTNUMBER = Integer.parseInt(catchCurrentShortVersion);
if (CURRENTNUMBER >= UPDATENUMBER) {
estado.setText("No se han encontrado actualizaciones.");
} else {
updatedVersion.setForeground(new Color(0,102,0));
updatedLabel.setForeground(new Color(0,153,51));
updatedVersion.setText(catchUpdatedVersion);
estado.append("-------------------" +
"NUEVA ACTUALIZACIÓN DISPONIBLE: " +
catchUpdatedVersion + " -------------------");;
estado.append(System.getProperty("line.separator"));
estado.append("Descargando actualizaciones... " +
"Espere por favor, no cierre este " +
"programa hasta que esté completado...");
try {
String updateURL = "https://thread.googlecode.com/" +
"svn/trunk/thread.inf";
String updatedname = (catchUpdatedVersion + ".zip");
File updatedfile = new File(updatedname);
URLConnection conn = new URL(updateURL).openConnection();
conn.connect();
estado.append(System.getProperty("line.separator"));
estado.append(" Archivo actual: " + updatedname);
estado.append(System.getProperty("line.separator"));
estado.append(" Tamaño: " +
conn.getContentLength() / 1000 / 1000 + " MB");
InputStream in = conn.getInputStream();
OutputStream out = new FileOutputStream(updatedfile);
int c = 0;
while (c != -1) {
c = in.read();
if (c != -1) {
out.write(c);
}
}
out.close();
in.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
}
} catch (IOException ioe) {
System.out.println(ioe);
ioe.printStackTrace();
}
}
}
When I run the program, the thread does not work fine. It is supposed to download a file and then display its progress in a JTextArea in main.java class. It does download the file, but nothing appears in JTextArea.
Where is my mistake?
EDIT: Showing all the code.
Problem #1
The components you are trying to update are not, in any way, connected to the screen...
public JTextArea estado = new JTextArea();
public JTextField updatedVersion = new JTextField();
public JLabel updatedLabel = new JLabel();
That means, anytime you interact with these components, it's doing nothing to what's on the screen...
Problem #2
You're trying to make modifications to the UI from outside the context of the Event Dispatching Thread. This is significant violation of the Swing threading rules.
public class Check extends SwingWorker<String, String> {
private JTextArea estado;
Private JTextField updatedVersion;
private JLabel updatedLabel;
private String catchUpdatedVersion;
int UPDATENUMBER;
int CURRENTNUMBER;
public Check(JTextArea estado, JTextField updatedVersion, JLabel updatedLabel) {
this.estado = estado;
this.updatedVersion = updatedVersion;
this.updatedLabel = updatedLabel;
}
protected void process(List<String> values) {
for (String value : values) {
estado.append(value);
}
}
protected String doInBackground() throws Exception {
String infURL = "https://thread.googlecode.com/svn/trunk/thread.inf";
String name = "thread.inf";
File file = new File(name);
URLConnection conn = new URL(infURL).openConnection();
conn.connect();
publish("Conectando al servidor...");
publish(System.getProperty("line.separator"));
publish(" -- Buscando actualizaciones... --");
publish(System.getProperty("line.separator"));
/*...*/
}
}
IfYou need to do any post-processing, then you also override done which will be called after doInBackground has existed, but is called within the context of the EDT
For more details read through Concurrency in Swing