Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class cliente extends Activity implements Runnable {
- Context context=this;
- ArrayList<paquete> array;
- paquete_adapter adaptador;
- ListView lista;
- Handler mHandler;
- paquete paquete=new paquete();//instancia a la clase paquete
- backup_men backup;//=new backup_men();
- Thread hilo=new Thread(this);
- private String ipservidor="192.168.137.100";
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_cliente);
- String usuario=getIntent().getStringExtra("usuario");
- final String correo=getIntent().getStringExtra("correo");
- final String ip=getIntent().getStringExtra("ip");
- final datos_usuario datos_usuario=new datos_usuario();
- solicitud_mensajes(datos_usuario.getCorreo_electronico(),correo);//ejecutamos la funcion solicitud_mensajes le enviamos el correo del usuario y el de la conversacion
- TextView tusuario=(TextView) this.findViewById(R.id.usuario);
- TextView tip=(TextView)this.findViewById(R.id.estado);
- ImageView foto=(ImageView)this.findViewById(R.id.foto);
- ImageView tenviar=(ImageView)this.findViewById(R.id.enviar);
- final EditText mensaje=(EditText)this.findViewById(R.id.mensageenvio);
- foto.setImageResource(R.drawable.nofoto);
- tusuario.setText(usuario);
- tip.setText(ip);
- tenviar.setImageResource(R.drawable.enviar);
- System.out.println("onCreate en la actividad cliente");
- lista=findViewById(R.id.lista);
- array=new ArrayList<paquete>();
- paquete.setNombre_us("cargando....");
- paquete.setMensaje_env("cargando....");
- adaptador=new paquete_adapter(getApplicationContext(),array);
- lista.setAdapter(adaptador);
- hilo.start();
- View.OnClickListener enviar= new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- if(!mensaje.getText().toString().isEmpty())
- {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- // Código a ejecutar
- try {
- Socket socket = new Socket(ipservidor, 44827);
- paquete paqueteen = (paquete) paquete.clone();
- paqueteen.setNombre_us(datos_usuario.getNombre());
- System.out.println("paquete ----------" + datos_usuario.getNombre() + datos_usuario.getCorreo_electronico() + correo + ip + mensaje.getText().toString());
- paqueteen.setCorreo_us(datos_usuario.getCorreo_electronico());
- paqueteen.setCorreo_env(correo.toString());
- paqueteen.setIp_env(ip);
- paqueteen.setMensaje_env(mensaje.getText().toString());
- DataOutputStream sal = new DataOutputStream(socket.getOutputStream());
- sal.writeUTF("MENSAJE");
- //sal.close();
- ObjectOutputStream salida = new ObjectOutputStream(socket.getOutputStream());
- salida.writeObject(paqueteen);//enviamos el objeto
- salida.close();//cerramos el flujo de salida
- socket.close();//cerramos el socket
- mensaje.setText("");//limpiamos la entrada de texto
- array.add(paqueteen);
- System.out.println("objetos en el array="+array.size());
- adaptador.notifyDataSetChanged();//actualizamos el adaptador
- } catch (Exception ei) {
- System.out.println("Le excepcion es:" + ei.getMessage());
- System.out.println("La excepcion" + ei.getCause() + ei.getLocalizedMessage() + ei.getClass());
- }
- }
- });
- }
- else
- {
- System.out.println("Entrada de texto es null");
- }
- };
- };
- tenviar.setOnClickListener(enviar);
- }
- @Override
- protected void onStart() {
- super.onStart();
- System.out.println("Start en la actividad cliente");
- //adaptador.clearData();
- //adaptador.notifyDataSetChanged();
- }
- @Override
- protected void onPause() {
- super.onPause();
- System.out.println("Pause en la actividad cliente");
- }
- @Override public void onBackPressed()
- {
- //Intent backIntent = new Intent(this, principal.class);
- // backIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
- //startActivity(backIntent);
- array.clear();
- adaptador.clearData();
- backup=null;
- //paquete=null;
- System.out.println("Elementos en arry"+array.size());
- System.out.println("Se ejecuto OnBackPressed");
- finish();
- }
- @Override
- public void run() {
- try
- {
- ServerSocket sersocket=new ServerSocket(2345);//2345creamos un socket para recibir datos y ponemos a la escucha en el puerto 999
- int i=1;//creamos una variable para un contador
- while(true)//bucle infinito
- {
- Socket socket=sersocket.accept();//creamos una variable de tipo socket y atravez de este aceptamos la conexion
- DataInputStream entrada=new DataInputStream(socket.getInputStream());//creamos un flujo de entrada de tipo dato de texto plano
- String tipo=entrada.readUTF();//guardamos en la variable tipo lo que entra en el flujo de entrada
- if(tipo.equals("MENSAJE"))//comparamos si el texto que entro es igual a MENSAJE
- {
- System.out.println("NUEVO MENSAJE");//mostramos en consola que entro un mensaje
- ObjectInputStream flujo_entrada=new ObjectInputStream(socket.getInputStream());//creamos un flujo de entrada de tipo objeto
- paquete paquetemen=(paquete) flujo_entrada.readObject();//obtenemos el objeto del flujo de entrada y a travez de un cast se lo asignnamos a la referencia de paquete
- final paquete paquetclone=(paquete)paquetemen.clone();
- System.out.println("el mensaje es: "+paquetclone.getMensaje_env());
- this.runOnUiThread(new Runnable() {
- @Override
- public void run() {
- StrictMode.ThreadPolicy policy = new
- StrictMode.ThreadPolicy.Builder()
- .permitAll().build();
- StrictMode.setThreadPolicy(policy);
- array.add(paquetclone);
- System.out.println("Tratando de actualizar la lista de mensajes");
- System.out.println("objetos en el array="+array.size());
- adaptador.notifyDataSetChanged();
- }});
- }
- else if(tipo.equals("MENSAJES_GUARDADOS"))
- {
- System.out.println("Entro un backup");
- ObjectInputStream flujo_entrada=new ObjectInputStream(socket.getInputStream());
- backup=(backup_men) flujo_entrada.readObject();
- mensajes_guardados();
- System.out.println("cantidad de mensajes recibidos "+backup.getMen().length);
- }
- }
- } catch (IOException ex) {
- System.out.println("se lanzon una excepcion en el hilo a la escucha:"+ex.getMessage()+ex.getCause()+ex.getLocalizedMessage()+ex.getClass());
- } catch (ClassNotFoundException ea) {
- System.out.println("se lanzon una excepcion en el hilo a la escucha:"+ea.getMessage());
- }
- }
- /*
- @Override
- protected void onResume() {
- super.onResume();
- System.out.println("Resume en la actividad cliente");
- array.clear();
- lista.setAdapter(null);
- }*/
- public boolean solicitud_mensajes(String correo1, String correo2)
- {
- final solicitud_men solicitud=new solicitud_men();
- solicitud.setCorreo1(correo1);
- solicitud.setIp(getIP());
- solicitud.setCorreo2(correo2);
- new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- Socket socket = new Socket(ipservidor, 44827);
- DataOutputStream streamsalida = new DataOutputStream(socket.getOutputStream());
- streamsalida.writeUTF("MENSAJES_GUARDADOS");
- ObjectOutputStream salida = new ObjectOutputStream(socket.getOutputStream());
- salida.writeObject(solicitud);
- } catch (IOException e) {
- System.out.println(e.getMessage());
- }
- }
- }).start();
- return true;
- }
- public void mensajes_guardados()
- {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- try
- {
- //System.out.println("mostrando mensajes guardados");
- String[][] datosbackup = backup.getMen();
- int i = 0;
- // System.out.print("antes de empezar el while");
- while (datosbackup[i][0] != null)
- {
- //System.out.println("entrando al blucle de datos");
- paquete paquetecopy = (paquete) paquete.clone();
- /*
- System.out.println("datos backup="+datosbackup[i][1]);
- System.out.println("datos backup="+datosbackup[i][2]);*/
- paquetecopy.setMensaje_env(datosbackup[i][1]);
- paquetecopy.setNombre_us(datosbackup[i][2]);
- array.add(paquetecopy);
- adaptador.notifyDataSetChanged();
- System.out.println("objetos en el array="+array.size());
- System.out.println("se actualizo el adaptadosr de items");
- i++;
- }
- }catch (Exception e)
- {
- System.out.println("Hay una excepcion y es:"+e.getMessage());
- }
- }
- });
- }
- public String getIP()
- {
- try {
- WifiManager wifimanager= (WifiManager) context.getSystemService(Context.WIFI_SERVICE);//a travez del manejador del wifi obtenemos el wifi servicio
- WifiInfo wifiInfo = wifimanager.getConnectionInfo();//obtenemos la informacion del wifi
- int IpAddress = wifiInfo.getIpAddress();//obtenemos la ip a travez de wifiInfo
- return String.format(Locale.getDefault().getDefault(), "%d.%d.%d.%d",
- (IpAddress & 0xff), (IpAddress >> 8 & 0xff),
- (IpAddress >> 16 & 0xff), (IpAddress >> 24 & 0xff));//retornamos la ip convertida a string
- }
- catch (Exception e) {
- Log.e(TAG,e.getMessage());
- return null;
- }
- }
- }
- class paquete_adapter extends BaseAdapter
- {
- Context context;
- List<paquete> listaobjetos;
- public paquete_adapter(Context context, List<paquete> listaobjetos)
- {
- this.context=context;
- this.listaobjetos=listaobjetos;
- }
- public void clearData() {
- // clear the data
- listaobjetos.clear();
- }
- @Override
- public int getCount() {
- return listaobjetos.size();
- }
- @Override
- public Object getItem(int posicion) {
- return listaobjetos.get(posicion);
- }
- @Override
- public long getItemId(int posicion) {
- return listaobjetos.get(posicion).getId();
- }
- @Override
- public View getView(int posicion, View convertView, ViewGroup parents) {
- View vista=convertView;
- //obtener inflater
- // if(vista==null) {
- LayoutInflater inflater = LayoutInflater.from(context);
- vista = inflater.inflate(R.layout.mensaje_enviado, null);
- //}
- //referencias UI
- ImageView fotousuario=(ImageView) vista.findViewById(R.id.fotousuario);
- TextView mensage = (TextView) vista.findViewById(R.id.mensage);
- TextView usuario = (TextView) vista.findViewById(R.id.usuario);
- TextView fecha = (TextView) vista.findViewById(R.id.fecha);
- //setup
- fotousuario.setImageResource(R.drawable.nofoto);
- mensage.setText(listaobjetos.get(posicion).getMensaje_env().toString());
- usuario.setText(listaobjetos.get(posicion).getNombre_us());
- fecha.setText("12/12/12");
- System.out.println("adaptador="+listaobjetos.get(posicion).getMensaje_env().toString());
- //System.out.println("adaptador="+listaobjetos.get(posicion).getNombre_us());
- return vista;
- }
- }
Add Comment
Please, Sign In to add comment