Threads e Conexão Http

8 respostas
hayase

Pessoal alguém pode me ajudar a incluir um método thread nesse código… sem a thread o código ñ vai funcionar
obrigada…

/* ViewPng.java

  • Faz download e vê um arquivo png
  • Capítulo 14 - Estrutura de Conexão Genérica
  • Exemplo 14.1: Download e visualização da Imagem PNG */
import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.InputStream;
import javax.microedition.io.Connector;

import javax.microedition.io.ContentConnection;

import javax.microedition.lcdui.Command;

import javax.microedition.lcdui.CommandListener;

import javax.microedition.lcdui.Display;

import javax.microedition.lcdui.Displayable;

import javax.microedition.lcdui.Form;

import javax.microedition.lcdui.Image;

import javax.microedition.lcdui.ImageItem;

import javax.microedition.lcdui.TextBox;

import javax.microedition.midlet.MIDlet;

import javax.microedition.midlet.MIDletStateChangeException;
public class ViewPng extends MIDlet implements CommandListener

{

private Display display;

private TextBox tb_main;

private Form f_VPng;

private Command c_exit;

private Command c_view;

private Command c_back;
public ViewPng()
{
	display = Display.getDisplay(this);
	tb_main = new TextBox("Digite a url", "http://www.corej2me.com/midpbook_v1e1/ch14/duke.png", 75, 0);
	c_exit = new Command("sair", Command.EXIT, 1);
	c_view = new Command("Ver", Command.SCREEN, 2);
	tb_main.addCommand(c_exit);
	tb_main.addCommand(c_view);
	tb_main.setCommandListener(this);
	f_VPng = new Form(" ");
	c_back = new Command("Voltar", Command.BACK, 1);
	f_VPng.addCommand(c_back);
	f_VPng.setCommandListener(this);
}

protected void destroyApp(boolean unconditional) throws MIDletStateChangeException { }

protected void pauseApp() { }

protected void startApp() throws MIDletStateChangeException
{
	display.setCurrent(tb_main);
}

public void commandAction(Command c, Displayable d)
{
	if(c == c_exit)
	{
		try { destroyApp(false); }
		catch (MIDletStateChangeException e) { e.printStackTrace(); }
		notifyDestroyed();
	}
	else if(c == c_view)
	{
		try
		{
			Image im;
			if((im = getImage(tb_main.getString())) != null)
			{
				ImageItem ii = new ImageItem(null, im, ImageItem.LAYOUT_DEFAULT, null);
				if(f_VPng.size() != 0)
					f_VPng.set(0, ii);
				else
					f_VPng.append(ii);
			}
			else
				f_VPng.append("download sem sucesso");
			display.setCurrent(f_VPng);
		}
		catch (Exception e) { System.err.println("Msg: " + e.toString()); }
	}
	else if(c == c_back)
			display.setCurrent(tb_main);
}

private Image getImage(String url) throws IOException
{
	ContentConnection connection = (ContentConnection) Connector.open(url);
	InputStream iStrm = connection.openInputStream();
	Image im = null;
	try
	{
		byte imageData[];
		int length = (int) connection.getLength();
		if (length != -1)
		{
			imageData = new byte[length];
			iStrm.read(imageData);
		}
		else
		{
			ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
			int ch;
			while ((ch = iStrm.read()) != -1)
				bStrm.write(ch);
			imageData = bStrm.toByteArray();
			bStrm.close();
		}
		im = Image.createImage(imageData, 0, imageData.length);
	}
	finally
	{
		if(iStrm != null)
			iStrm.close();
		if(connection != null)
			connection.close();
	}
	return (im == null ? null : im);
}

}

8 Respostas

davidbuzatto

Método thread?

Primeiro vc vai precisar saber como funcionam as threads para utilizá-las, ou então descrever melhor seu problema. Aonde vc quer usar uma thread?

fabianofrizzo

Amigo da proxima usa BBCode para colocar seu código fonte dai fica melhor praentender…

Retirei este exemplo do Livro Core J2me

/*--------------------------------------------------
* ViewPngThread.java
*
* Download and view a png file. The download is
* done in the background with a separate thread 
*
* Example from the book:     Core J2ME Technology
* Copyright John W. Muchow   http://www.CoreJ2ME.com
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;

public class ViewPngThread extends MIDlet implements CommandListener
{
  private Display display;
  private TextBox tbMain;
	private Alert alStatus;
  private Form fmViewPng;
  private Command cmExit;
  private Command cmView;
  private Command cmBack;
  private static final int ALERT_DISPLAY_TIME = 3000;
  Image im = null;  

  public ViewPngThread()
  {
    display = Display.getDisplay(this);

    // Create the Main textbox with a maximum of 75 characters
    tbMain = new TextBox("Enter url", "http://www.corej2me.com/midpbook_v1e1/ch14/bird.png", 75, 0);

    // Create commands and add to textbox
    cmExit = new Command("Exit", Command.EXIT, 1);
    cmView = new Command("View", Command.SCREEN, 2);    
    tbMain.addCommand(cmExit);
    tbMain.addCommand(cmView );    

    // Set up a listener for textbox
    tbMain.setCommandListener(this);

    // Create the form that will hold the png image
    fmViewPng = new Form("");

    // Create commands and add to form
    cmBack = new Command("Back", Command.BACK, 1);
    fmViewPng.addCommand(cmBack);

    // Set up a listener for form
    fmViewPng.setCommandListener(this);
  }

  public void startApp()
  {
    display.setCurrent(tbMain);
  }

  public void pauseApp()
  { }

  public void destroyApp(boolean unconditional)
  { }

  /*--------------------------------------------------
  * Process events
  *-------------------------------------------------*/
  public void commandAction(Command c, Displayable s)
  {
    // If the Command button pressed was "Exit"
    if (c == cmExit)
    {
      destroyApp(false);
      notifyDestroyed();
    }
    else if (c == cmView)
    {
      // Show alert indicating we are starting a download.
      // This alert is NOT modal, it appears for
      // approximately 3 seconds (see ALERT_DISPLAY_TIME)
      showAlert("Downloading", false, tbMain);

      // Create an instance of the class that will
      // download the file in a separate thread
      Download dl = new Download(tbMain.getString(), this);
      
      // Start the thread/download
      dl.start(); 
    } 
    else if (c == cmBack)
    {
      display.setCurrent(tbMain);
    }
  }

  /*--------------------------------------------------
  * Called by the thread after attempting to download
  * an image. If the parameter is 'true' the download
  * was successful, and the image is shown on a form. 
  * If  parameter is 'false' the download failed, and
  * the user is returned to the textbox.  
  *
  * In either case, show an alert indicating the 
  * the result of the download.
  *-------------------------------------------------*/
  public void showImage(boolean flag)
  {
    // Download failed... 
    if (flag == false)
    {
      // Alert followed by the main textbox
      showAlert("Download Failure", true, tbMain);
    }
    else  // Successful download...
    {
      ImageItem ii = new ImageItem(null, im, ImageItem.LAYOUT_DEFAULT, null);
          
      // If there is already an image, set (replace) it
      if (fmViewPng.size() != 0)
        fmViewPng.set(0, ii);
      else  // Append the image to the empty form
        fmViewPng.append(ii);

      // Alert followed by the form holding the image      
      showAlert("Download Successful", true, fmViewPng);
    }      
  }
  
  /*--------------------------------------------------
  * Show an alert with the parameters determining
  * the type (modal or not) and the displayable to
  * show after the alert is dismissed
  *-------------------------------------------------*/
  public void showAlert(String msg, boolean modal, Displayable displayable)
  {
     // Create alert, add text, associate a sound
    alStatus = new Alert("Status", msg, null, AlertType.INFO);

    // Set the alert type
    if (modal)
      alStatus.setTimeout(Alert.FOREVER);
    else
      alStatus.setTimeout(ALERT_DISPLAY_TIME);

    // Show the alert, followed by the displayable
    display.setCurrent(alStatus, displayable);
  }
}

/*--------------------------------------------------
* Class - Download
*
* Download an image file in a separate thread
*-------------------------------------------------*/  
class Download implements Runnable
{
  private String url;
  private ViewPngThread MIDlet;
  private boolean downloadSuccess = false;  
  
  public Download(String url, ViewPngThread MIDlet)
  { 
    this.url = url;
    this.MIDlet = MIDlet;
  }

  /*--------------------------------------------------
  * Download the image
  *-------------------------------------------------*/
  public void run() 
  {
    try
    {
      getImage(url);
    }
    catch (Exception e)
    { 
      System.err.println("Msg: " + e.toString());
    }      
  }

  /*--------------------------------------------------
  * Create and start the new thread
  *-------------------------------------------------*/  
  public void start()
  {
    Thread thread = new Thread(this);
    try
    {
      thread.start();
    }
    catch (Exception e)
    {
    }
  }
  
  /*--------------------------------------------------
  * Open connection and download png into a byte array.
  *-------------------------------------------------*/
  private void getImage(String url) throws IOException
  {
    ContentConnection connection = (ContentConnection) Connector.open(url);
    
    // * There is a bug in MIDP 1.0.3 in which read() sometimes returns
    //   an invalid length. To work around this, I have changed the 
    //   stream to DataInputStream and called readFully() instead of read()
//    InputStream iStrm = connection.openInputStream();
    DataInputStream iStrm = connection.openDataInputStream();    
    
    ByteArrayOutputStream bStrm = null;
    Image im = null;

    try
    {
      // ContentConnection includes a length method
      byte imageData[];      
      int length = (int) connection.getLength();
      if (length != -1)
      {
        imageData = new byte[length];

        // Read the png into an array        
//        iStrm.read(imageData);        
        iStrm.readFully(imageData);
      }
      else  // Length not available...
      {       
        bStrm = new ByteArrayOutputStream();
        
        int ch;
        while ((ch = iStrm.read()) != -1)
          bStrm.write(ch);
        
        imageData = bStrm.toByteArray();
      }
 
      // Create the image from the byte array
      im = Image.createImage(imageData, 0, imageData.length);        
    }
    finally
    {
      // Clean up
      if (connection != null)
        connection.close();      
      if (iStrm != null)
        iStrm.close();
      if (bStrm != null)
        bStrm.close();                        
    }

    // Return to the caller the status of the download
    if (im == null)
      MIDlet.showImage(false);
    else
    {
      MIDlet.im = im;
      MIDlet.showImage(true);              
    }
  }
}
hayase

nossa mas que coincidencia
eu tb retirei o exemplo acima do livro core j2me
aehiaehieahieahiea
q coisa não…
mas muito obrigada
eu já entendi como funcionam as threads e o método run nas midlets…
obrigada
detalhe… sou AMIGA e não AMIGO…
desculpe pelo código, é q foi o primeiro post no fórun, não percebi o detalhe
até

fabianofrizzo

Bom desculpa por tela chamada de Amigo é costume…

Mas prometo que vou tomar mais cuidado…

Precisando estamos a disposição

hayase

obrigada

DEAD

Galera eu postei um exemplo para isso esses tempos como teste na comunidade. Uma vez sabendo-se conectar vc pode adicionar conexões ao banco de dados e retorno via a servelt. Confiram ai o exemplo que não foi tirado do livro Core Java.

http://www.guj.com.br/posts/list/66258.java

Até mais!!!

hayase

hehehehe
obrigada

DEAD

Tudo bem Hayase, qualquer coisa lembre-se que o conhecimento não é algo que tem dono é de toda humanidade.
Tenho de arrumar um tempo para fazer aquele tutorial/artigo que havia dito que iria fazer, gostaria de entrar a fundo nas tecnologias para pode-las explica-las melhor mas infelizmente agora tou meio sem tempo para fazer isso.
Mesmo assim Hayase quando tiver um tempo vou montar aquele sistema de Login, se der mando via pdf pra cá com um caso de uso e algumas explicações.
Enquanto ao Core J2ME é bom mais deixa a desejar, afinal esta defazado já o livro, era uma época que nem o CLDC 1.1 nem o MIDP 2.0 existiam… hj em dia temos MIDP 2.1(indo para o 3.0).
Então vendo o quadro de livros traduzidos… o programador de JME tem de saber inglês kkkk pois o negócio aqui tá feio. Alguem conheçe algum livro mesmo de algum autor Brasileiro sobre JME? é lógico se vc’s souberem postem tbm uma referência ao mesmo se é bom ou se é uma $#@$@#$ para sabermos se vale apena comprar kkkk. Até mais!

Criado 5 de agosto de 2007
Ultima resposta 29 de ago. de 2007
Respostas 8
Participantes 4