ETL PARA O ANDROID e APRESENTAÇÃO DAS INFORMAÇÕES
Autor: Roberval Junior | Publicado: 2012-08-17T04:36:00-07:00




Foi usado esse código&nbsp;para a extração das informações que serão apresentadas na&nbsp;aplicação&nbsp;android.



A aplicação ira fazer uma solicitação ao servidor web PHP, que respondera por meio do JSON, o resultado &nbsp; é a apresentação da lista dos itens carregados no celular.



________________________________________________________________________________



&gt; LaudoActivity.java




package com.rober.clinica_laudo;



import java.io.IOException;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;



import org.apache.http.NameValuePair;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.HttpClient;

import org.apache.http.client.ResponseHandler;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.BasicResponseHandler;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.params.BasicHttpParams;

import org.apache.http.params.HttpConnectionParams;

import org.apache.http.params.HttpParams;

import org.json.JSONArray;

import org.json.JSONObject;



import com.rober.clinica_laudo.R;



import android.R.string;

import android.annotation.SuppressLint;

import android.app.ListActivity;

import android.content.Context;

import android.content.Intent;

import android.database.Cursor;

import android.os.AsyncTask;

import android.os.Bundle;

import android.util.Log;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.BaseAdapter;

import android.widget.Button;

import android.widget.ListAdapter;

import android.widget.ListView;

import android.widget.SimpleCursorAdapter;

import android.widget.TextView;

import android.widget.Toast;



public class LaudoActivity extends ListActivity {

 //ListAdapter adapter;

 LaudoAdapter adapter;

 DBAdapter datasource;

 Button btNovoContacto;

 Button btBuscarServer;

 TextView textRober;

 private List&lt;Laudo&gt; laudoList = new ArrayList&lt;Laudo&gt;();



 ListView listView;



 // comunicação server

 private static final int TIMEOUT_MILLISEC = 0;



 @Override

 public void onCreate(Bundle savedInstanceState) {



  super.onCreate(savedInstanceState);

  setContentView(R.layout.main);



  listView = (ListView) findViewById(R.id.linearLayout1);



  datasource = new DBAdapter(this);

  datasource.open();

  Cursor cursor = datasource.getLaudos();



  for (int i = 0; i &lt; cursor.getCount(); i++) {

   cursor.moveToPosition(i);

   

   Laudo laudo = new Laudo(cursor.getLong(0), cursor.getLong(1),

     cursor.getString(2), cursor.getString(3),

     cursor.getString(4), cursor.getString(5),

     cursor.getString(6));

   laudoList.add(laudo);

  }



  setListAdapter(new LaudoAdapter(this, laudoList));

  datasource.close();



  btBuscarServer = (Button) findViewById(R.id.btBuscarServer);



  btBuscarServer.setOnClickListener(new View.OnClickListener() {

   public void onClick(View v) {

    // TODO Auto-generated method stub



    String max_cod = "";



    datasource.open();

    Cursor cursor = datasource.getMaxLaudo();



    for (int i = 0; i &lt; cursor.getCount(); i++) {

     cursor.moveToPosition(i);

     Log.i("MAX", "max - " + cursor.getString(0));

     if (cursor.getString(0) != null) {



      max_cod = cursor.getString(0);



     } else {

      max_cod = "0";

     }

    }



    datasource.close();



    HttpAsyncTask asyncTask = new HttpAsyncTask(max_cod);

    asyncTask.execute();



    // asyncTask.cancel(true);

   }

  });

 }



 @Override

 protected void onResume() {

  // TODO Auto-generated method stub

  super.onResume();



 }



 @Override

 protected void onListItemClick(ListView l, View v, int position, long id) {

  

 }



 private class HttpAsyncTask extends AsyncTask&lt;String, Integer, ArrayList&gt; {



  String max_cod;



  public HttpAsyncTask(String max_cod) {

   // TODO Auto-generated constructor stub

   this.max_cod = max_cod;

  }



  @Override

  protected ArrayList doInBackground(String... max_cod) {

   try {



    HttpParams httpParams = new BasicHttpParams();

    HttpConnectionParams.setConnectionTimeout(httpParams,

      TIMEOUT_MILLISEC);

    HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);

    //

    HttpParams p = new BasicHttpParams();



    p.setParameter("user", "1");

    // Instantiate an HttpClient

    HttpClient httpclient = new DefaultHttpClient(p);

    String url = "http://10.0.2.2:80/clinica/"

      + "clinica.php?max_cod=" + this.max_cod

      + "&amp;user=1&amp;format=json";

    HttpPost httppost = new HttpPost(url);



    // Instantiate a GET HTTP method

    try {

     Log.i(getClass().getSimpleName(), "send &nbsp;task - start");

     //

     List&lt;NameValuePair&gt; nameValuePairs = new ArrayList&lt;NameValuePair&gt;(

       2);

     nameValuePairs.add(new BasicNameValuePair("user", "1"));

     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

     ResponseHandler&lt;String&gt; responseHandler = new BasicResponseHandler();



     Log.i(getClass().getSimpleName(), "funcionou ate");

     String responseBody = httpclient.execute(httppost,

       responseHandler);

     Log.d("TESTE", responseBody);



     // Parse

     JSONObject json = new JSONObject(responseBody);

     JSONArray jArray = json.getJSONArray("posts");

     ArrayList&lt;HashMap&lt;String, String&gt;&gt; mylist = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;();



     for (int i = 0; i &lt; jArray.length(); i++) {

      HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();

      JSONObject e = jArray.getJSONObject(i);

      String s = e.getString("post");

      JSONObject jObject = new JSONObject(s);



      map.put("codigo",

        jObject.getString("clin_func_empr_exam_codigo"));

      map.put("medico", jObject.getString("medi_nome"));

      map.put("func", jObject.getString("func_empr_nome"));

      map.put("exame", jObject.getString("exam_nome"));

      map.put("data", jObject

        .getString("clin_func_empr_exam_data_exame"));

      map.put("valor",

        jObject.getString("clin_func_empr_exam_valor"));



      mylist.add(map);

     }



     datasource.open();

     HashMap&lt;String, String&gt; map_2 = new HashMap&lt;String, String&gt;();

     for (Iterator&lt;HashMap&lt;String, String&gt;&gt; it = mylist

       .iterator(); it.hasNext();) {

      map_2 = it.next();

      datasource.createLaudo(map_2.get("codigo"),

        map_2.get("medico"), map_2.get("func"),

        map_2.get("exame"), map_2.get("data"),

        map_2.get("valor"));

     }

     datasource.close();



     return mylist;



    } catch (ClientProtocolException e) {

     // TODO Auto-generated catch block

     e.printStackTrace();

    } catch (IOException e) {

     // TODO Auto-generated catch block

     e.printStackTrace();

    }



   } catch (Throwable t) {

    Log.i("Contactos", t.getMessage());

   }



   return null;

  }



  @Override

  protected void onProgressUpdate(Integer... values) {

   // TODO Auto-generated method stub

   super.onProgressUpdate(values);

  }



  @SuppressLint("ParserError")

  @Override

  protected void onPostExecute(ArrayList result) {

   // TODO Auto-generated method stub



   super.onPostExecute(result);

   

   laudoList.clear();



   datasource.open();

   Cursor cursor = datasource.getLaudos();



   for (int i = 0; i &lt; cursor.getCount(); i++) {

    cursor.moveToPosition(i);

    Laudo contacto = new Laudo(cursor.getLong(0),

      cursor.getLong(1), cursor.getString(2),

      cursor.getString(3), cursor.getString(4),

      cursor.getString(5), cursor.getString(6));

    laudoList.add(contacto);

   }



   adapter = new LaudoAdapter(LaudoActivity.this, laudoList);

   

   setListAdapter(adapter);

   adapter.notifyDataSetChanged();

   datasource.close();



  }



 }



}




/*******************************************************************************/



&gt; DbHelper.java



Classe&nbsp;responsável&nbsp;pela conexão com o banco sqllite.&nbsp;




package com.rober.clinica_laudo;



import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteDatabase.CursorFactory;

import android.database.sqlite.SQLiteOpenHelper;

import android.util.Log;



public class DbHelper extends SQLiteOpenHelper {



 

 private static final int DATABASE_VERSION = 1;

 public static final String TABLE_NAME = "exames";

 private static final String DATABASE_NAME = " clinica_laudo.db";



 public static final String ID = "id";

 public static final String CODIGO = "clin_func_empr_exam_codigo";

 public static final String MEDICO = "medi_nome";

 public static final String FUNCIONARIO = "func_empr_nome";

 public static final String EXAME = "exam_nome";

 public static final String DATA = "clin_func_empr_exam_data_exame";

 public static final String VALOR = "clin_func_empr_exam_valor";

 

 private static final String DATABASE_CREATE = "create table "

   + TABLE_NAME + "( " + ID

   + " integer primary key autoincrement, " + CODIGO

   + " integer not null, " + MEDICO

   + " text not null, " + FUNCIONARIO&nbsp;

   + " text not null, " + EXAME&nbsp;

   + " text not null, " + DATA &nbsp;

   + " text not null, " + VALOR&nbsp;

   + " text not null);";

 

 public DbHelper(Context context) {

  super(context, DATABASE_NAME, null, DATABASE_VERSION);

  //super()

 }



 @Override

 public void onCreate(SQLiteDatabase db) {

  db.execSQL(DATABASE_CREATE);

 }



 @Override

 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

  Log.w(DbHelper.class.getName(), "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");

 db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

  onCreate(db);

 }





}




/********************************************************************************/



&gt; DBAdapter.java




package com.rober.clinica_laudo;



import java.io.ByteArrayOutputStream;



import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.database.SQLException;

import android.database.sqlite.SQLiteDatabase;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;



public class DBAdapter {

 private SQLiteDatabase database;

 private DbHelper dbHelper;

 private String[] allColumns = { dbHelper.ID, dbHelper.CODIGO,

   dbHelper.MEDICO, dbHelper.FUNCIONARIO, dbHelper.EXAME,

   dbHelper.DATA, dbHelper.VALOR };



 public DBAdapter(Context context) {

  dbHelper = new DbHelper(context);

 }



 public void open() throws SQLException {

  database = dbHelper.getWritableDatabase();

 }



 public void close() {

  dbHelper.close();

 }



 public Void createLaudo(String codigo, String medico, String func,

   String exame, String data, String valor) {

  ContentValues values = new ContentValues();

  values.put(dbHelper.CODIGO, codigo);

  values.put(dbHelper.MEDICO, medico);

  values.put(dbHelper.FUNCIONARIO, func);

  values.put(dbHelper.EXAME, exame);

  values.put(dbHelper.DATA, data);

  values.put(dbHelper.VALOR, valor);



  long insertId = database.insert(dbHelper.TABLE_NAME, null, values);

  // To show how to query

  Cursor cursor = database.query(dbHelper.TABLE_NAME, allColumns,

    dbHelper.ID + " = " + insertId, null, null, null, null);

  cursor.moveToFirst();

  return null;

 }





 private Laudo cursorToLaudo(Cursor cursor) {

  Laudo laudo = new Laudo(cursor.getLong(0),

    cursor.getLong(1), cursor.getString(2), cursor.getString(3),

    cursor.getString(4), cursor.getString(5), cursor.getString(6));

  return laudo;

 }



 public Cursor getLaudos() {

  Cursor cursor = database.rawQuery("select " + dbHelper.ID + ", "

    + dbHelper.CODIGO + ", " + dbHelper.MEDICO + ", "

    + dbHelper.FUNCIONARIO + ", " + dbHelper.EXAME + ", "

    + dbHelper.DATA + ", " + dbHelper.VALOR + " from exames ORDER BY " + dbHelper.CODIGO + " desc", null);

  return cursor;

 }



 public Laudo getLaudo(int idLaudo) {

  Cursor cursor = database.query(dbHelper.TABLE_NAME, allColumns,

    dbHelper.CODIGO + " = " + idLaudo, null, null, null, null);

  cursor.moveToFirst();

  return cursorToLaudo(cursor);

 }



 public Cursor getMaxLaudo() {

  Cursor cursor = database.rawQuery("select MAX(" + dbHelper.CODIGO

    + ") " + " from exames", null);

  return cursor;

 }



}




/*******************************************************************************/



&gt; Laudo.java




package com.rober.clinica_laudo;





public class Laudo {

 private long id;

 private long clin_func_empr_exam_codigo;

 private String medi_nome;

 private String func_empr_nome;

 private String exam_nome;

 private String clin_func_empr_exam_data_exame;

 private String clin_func_empr_exam_valor;

 

 public Laudo(long id, long codigo, String medico, String func,String exame,String data,String valor){

  this.id=id;

  this.clin_func_empr_exam_codigo=codigo;

  this.medi_nome=medico;

  this.func_empr_nome=func;

  this.exam_nome=exame;

  this.clin_func_empr_exam_data_exame=data;

  this.clin_func_empr_exam_valor=valor;

 }

 

 public long getId() {

  return id;

 }

 

 public void setId(long id) {

  this.id = id;

 }





 public long getClin_func_empr_exam_codigo() {

  return clin_func_empr_exam_codigo;

 }



 public void setClin_func_empr_exam_codigo(long clin_func_empr_exam_codigo) {

  this.clin_func_empr_exam_codigo = clin_func_empr_exam_codigo;

 }



 public String getMedi_nome() {

  return medi_nome;

 }



 public void setMedi_nome(String medi_nome) {

  this.medi_nome = medi_nome;

 }



 public String getFunc_empr_nome() {

  return func_empr_nome;

 }



 public void setFunc_empr_nome(String func_empr_nome) {

  this.func_empr_nome = func_empr_nome;

 }



 public String getExam_nome() {

  return exam_nome;

 }



 public void setExam_nome(String exam_nome) {

  this.exam_nome = exam_nome;

 }



 public String getClin_func_empr_exam_data_exame() {

  return clin_func_empr_exam_data_exame;

 }



 public void setClin_func_empr_exam_data_exame(

   String clin_func_empr_exam_data_exame) {

  this.clin_func_empr_exam_data_exame = clin_func_empr_exam_data_exame;

 }



 public String getClin_func_empr_exam_valor() {

  return clin_func_empr_exam_valor;

 }



 public void setClin_func_empr_exam_valor(String clin_func_empr_exam_valor) {

  this.clin_func_empr_exam_valor = clin_func_empr_exam_valor;

 }

 

 

 



 

}




/*******************************************************************************/



&gt; LaudoAdapter.java




package com.rober.clinica_laudo;



import java.util.List;



import com.rober.clinica_laudo.R;



import android.annotation.SuppressLint;

import android.content.Context;

import android.util.Log;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.BaseAdapter;

import android.widget.TextView;



public class LaudoAdapter extends BaseAdapter {

 private Context context;

 private List&lt;Laudo&gt; laudoList;



 public LaudoAdapter(Context context, List&lt;Laudo&gt; laudoList) {

  this.context = context;

  this.laudoList = laudoList;

 }



 public int getCount() {

  return laudoList.size();

 }



 public Object getItem(int position) {

  return laudoList.get(position);

 }



 public long getItemId(int position) {

  return position;

 }



 public View getView(int position, View convertView, ViewGroup parent) {

  // Recupera o estado da posição atual

  Laudo laudo = laudoList.get(position);



  // Cria uma instância do layout XML para os objetos correspondentes

  // na View

  LayoutInflater inflater = (LayoutInflater) context

    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

  View view = inflater.inflate(R.layout.laudo_list_item, null);



  // Estado - Abreviação

  TextView textState = (TextView) view.findViewById(R.id.dado_1);

  textState.setText(laudo.getClin_func_empr_exam_codigo() + " - "

    + laudo.getFunc_empr_nome() + " - " + laudo.getExam_nome());



  // Capital

  TextView textCapital = (TextView) view.findViewById(R.id.dado_2);

  textCapital.setText(laudo.getClin_func_empr_exam_valor() + " ("

    + laudo.getClin_func_empr_exam_data_exame() + ")");



  Log.i("CoNT",

    "ID - " + laudo.getId() + " / "

      + laudo.getClin_func_empr_exam_codigo());



  return view;

 }



}




/********************************************************************************/



&gt; LaudoDetalhes.java




package com.rober.clinica_laudo;



import com.rober.clinica_laudo.R;



import android.app.Activity;

import android.app.AlertDialog;

import android.content.DialogInterface;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.ImageView;

import android.widget.TextView;



public class LaudoDetalhes extends Activity {



 int idLaudo;

 DBAdapter datasource;

 Laudo laudo;

 TextView edtNome;

 TextView edtEmail;

 TextView edtTelefone;

 Button btVoltar;

 Button btEliminar;



 @Override

 protected void onCreate(Bundle savedInstanceState) {

  // TODO Auto-generated method stub

  super.onCreate(savedInstanceState);

  setContentView(R.layout.detalhelaudo);



  edtNome = (TextView) findViewById(R.lista.txtnome);

  edtEmail = (TextView) findViewById(R.lista.txtEmail);

  edtTelefone = (TextView) findViewById(R.lista.txtTelefone);

  btEliminar = (Button) findViewById(R.id.btEliminar);

  btVoltar = (Button) findViewById(R.lista.btmenu);



  carregaDetalhesContacto();



  btVoltar.setOnClickListener(new View.OnClickListener() {

   public void onClick(View v) {

    // TODO Auto-generated method stub

    finish();

   }

  });



 }



 private void carregaDetalhesContacto() {

  idLaudo = getIntent().getIntExtra("idLaudo", 0);



  datasource = new DBAdapter(this);

  datasource.open();

  laudo = datasource.getLaudo(idLaudo);

  datasource.close();



  /*

   * ivFoto.setImageBitmap(contacto.getFoto());

   * edtNome.setText(contacto.getNome());

   * edtEmail.setText(contacto.getEmail());

   * edtTelefone.setText(contacto.getTelefone());

   */

 }



}