Guest User

Untitled

a guest
Mar 13th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.82 KB | None | 0 0
  1. public class cliente extends Activity implements Runnable {
  2. Context context=this;
  3. ArrayList<paquete> array;
  4.  
  5. paquete_adapter adaptador;
  6. ListView lista;
  7. Handler mHandler;
  8. paquete paquete=new paquete();//instancia a la clase paquete
  9. backup_men backup;//=new backup_men();
  10. Thread hilo=new Thread(this);
  11. private String ipservidor="192.168.137.100";
  12.  
  13.  
  14.  
  15. protected void onCreate(Bundle savedInstanceState) {
  16. super.onCreate(savedInstanceState);
  17. setContentView(R.layout.activity_cliente);
  18. String usuario=getIntent().getStringExtra("usuario");
  19. final String correo=getIntent().getStringExtra("correo");
  20. final String ip=getIntent().getStringExtra("ip");
  21.  
  22.  
  23. final datos_usuario datos_usuario=new datos_usuario();
  24. solicitud_mensajes(datos_usuario.getCorreo_electronico(),correo);//ejecutamos la funcion solicitud_mensajes le enviamos el correo del usuario y el de la conversacion
  25.  
  26. TextView tusuario=(TextView) this.findViewById(R.id.usuario);
  27. TextView tip=(TextView)this.findViewById(R.id.estado);
  28. ImageView foto=(ImageView)this.findViewById(R.id.foto);
  29. ImageView tenviar=(ImageView)this.findViewById(R.id.enviar);
  30. final EditText mensaje=(EditText)this.findViewById(R.id.mensageenvio);
  31.  
  32. foto.setImageResource(R.drawable.nofoto);
  33. tusuario.setText(usuario);
  34. tip.setText(ip);
  35. tenviar.setImageResource(R.drawable.enviar);
  36.  
  37. System.out.println("onCreate en la actividad cliente");
  38.  
  39.  
  40. lista=findViewById(R.id.lista);
  41. array=new ArrayList<paquete>();
  42.  
  43. paquete.setNombre_us("cargando....");
  44. paquete.setMensaje_env("cargando....");
  45. adaptador=new paquete_adapter(getApplicationContext(),array);
  46. lista.setAdapter(adaptador);
  47.  
  48.  
  49. hilo.start();
  50. View.OnClickListener enviar= new View.OnClickListener() {
  51. @Override
  52. public void onClick(View view) {
  53. if(!mensaje.getText().toString().isEmpty())
  54. {
  55. runOnUiThread(new Runnable() {
  56. @Override
  57. public void run() {
  58. // Código a ejecutar
  59. try {
  60.  
  61. Socket socket = new Socket(ipservidor, 44827);
  62. paquete paqueteen = (paquete) paquete.clone();
  63. paqueteen.setNombre_us(datos_usuario.getNombre());
  64. System.out.println("paquete ----------" + datos_usuario.getNombre() + datos_usuario.getCorreo_electronico() + correo + ip + mensaje.getText().toString());
  65.  
  66. paqueteen.setCorreo_us(datos_usuario.getCorreo_electronico());
  67. paqueteen.setCorreo_env(correo.toString());
  68. paqueteen.setIp_env(ip);
  69.  
  70. paqueteen.setMensaje_env(mensaje.getText().toString());
  71. DataOutputStream sal = new DataOutputStream(socket.getOutputStream());
  72. sal.writeUTF("MENSAJE");
  73. //sal.close();
  74. ObjectOutputStream salida = new ObjectOutputStream(socket.getOutputStream());
  75. salida.writeObject(paqueteen);//enviamos el objeto
  76. salida.close();//cerramos el flujo de salida
  77. socket.close();//cerramos el socket
  78. mensaje.setText("");//limpiamos la entrada de texto
  79.  
  80. array.add(paqueteen);
  81. System.out.println("objetos en el array="+array.size());
  82. adaptador.notifyDataSetChanged();//actualizamos el adaptador
  83. } catch (Exception ei) {
  84. System.out.println("Le excepcion es:" + ei.getMessage());
  85. System.out.println("La excepcion" + ei.getCause() + ei.getLocalizedMessage() + ei.getClass());
  86. }
  87.  
  88. }
  89. });
  90. }
  91. else
  92. {
  93. System.out.println("Entrada de texto es null");
  94. }
  95. };
  96. };
  97. tenviar.setOnClickListener(enviar);
  98.  
  99. }
  100.  
  101. @Override
  102. protected void onStart() {
  103. super.onStart();
  104. System.out.println("Start en la actividad cliente");
  105. //adaptador.clearData();
  106. //adaptador.notifyDataSetChanged();
  107. }
  108.  
  109. @Override
  110. protected void onPause() {
  111. super.onPause();
  112. System.out.println("Pause en la actividad cliente");
  113. }
  114.  
  115.  
  116.  
  117. @Override public void onBackPressed()
  118. {
  119. //Intent backIntent = new Intent(this, principal.class);
  120. // backIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
  121. //startActivity(backIntent);
  122. array.clear();
  123. adaptador.clearData();
  124. backup=null;
  125. //paquete=null;
  126. System.out.println("Elementos en arry"+array.size());
  127. System.out.println("Se ejecuto OnBackPressed");
  128. finish();
  129.  
  130. }
  131.  
  132. @Override
  133. public void run() {
  134. try
  135. {
  136. ServerSocket sersocket=new ServerSocket(2345);//2345creamos un socket para recibir datos y ponemos a la escucha en el puerto 999
  137. int i=1;//creamos una variable para un contador
  138. while(true)//bucle infinito
  139. {
  140. Socket socket=sersocket.accept();//creamos una variable de tipo socket y atravez de este aceptamos la conexion
  141. DataInputStream entrada=new DataInputStream(socket.getInputStream());//creamos un flujo de entrada de tipo dato de texto plano
  142. String tipo=entrada.readUTF();//guardamos en la variable tipo lo que entra en el flujo de entrada
  143. if(tipo.equals("MENSAJE"))//comparamos si el texto que entro es igual a MENSAJE
  144. {
  145. System.out.println("NUEVO MENSAJE");//mostramos en consola que entro un mensaje
  146. ObjectInputStream flujo_entrada=new ObjectInputStream(socket.getInputStream());//creamos un flujo de entrada de tipo objeto
  147.  
  148. 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
  149. final paquete paquetclone=(paquete)paquetemen.clone();
  150. System.out.println("el mensaje es: "+paquetclone.getMensaje_env());
  151.  
  152. this.runOnUiThread(new Runnable() {
  153. @Override
  154. public void run() {
  155. StrictMode.ThreadPolicy policy = new
  156. StrictMode.ThreadPolicy.Builder()
  157. .permitAll().build();
  158. StrictMode.setThreadPolicy(policy);
  159. array.add(paquetclone);
  160. System.out.println("Tratando de actualizar la lista de mensajes");
  161. System.out.println("objetos en el array="+array.size());
  162. adaptador.notifyDataSetChanged();
  163.  
  164. }});
  165. }
  166. else if(tipo.equals("MENSAJES_GUARDADOS"))
  167. {
  168. System.out.println("Entro un backup");
  169. ObjectInputStream flujo_entrada=new ObjectInputStream(socket.getInputStream());
  170. backup=(backup_men) flujo_entrada.readObject();
  171. mensajes_guardados();
  172. System.out.println("cantidad de mensajes recibidos "+backup.getMen().length);
  173. }
  174. }
  175. } catch (IOException ex) {
  176. System.out.println("se lanzon una excepcion en el hilo a la escucha:"+ex.getMessage()+ex.getCause()+ex.getLocalizedMessage()+ex.getClass());
  177. } catch (ClassNotFoundException ea) {
  178. System.out.println("se lanzon una excepcion en el hilo a la escucha:"+ea.getMessage());
  179. }
  180.  
  181.  
  182.  
  183. }
  184.  
  185. /*
  186. @Override
  187. protected void onResume() {
  188. super.onResume();
  189. System.out.println("Resume en la actividad cliente");
  190. array.clear();
  191. lista.setAdapter(null);
  192. }*/
  193.  
  194.  
  195.  
  196. public boolean solicitud_mensajes(String correo1, String correo2)
  197. {
  198. final solicitud_men solicitud=new solicitud_men();
  199. solicitud.setCorreo1(correo1);
  200. solicitud.setIp(getIP());
  201. solicitud.setCorreo2(correo2);
  202.  
  203. new Thread(new Runnable() {
  204.  
  205. @Override
  206. public void run() {
  207. try {
  208. Socket socket = new Socket(ipservidor, 44827);
  209. DataOutputStream streamsalida = new DataOutputStream(socket.getOutputStream());
  210. streamsalida.writeUTF("MENSAJES_GUARDADOS");
  211. ObjectOutputStream salida = new ObjectOutputStream(socket.getOutputStream());
  212. salida.writeObject(solicitud);
  213. } catch (IOException e) {
  214. System.out.println(e.getMessage());
  215. }
  216. }
  217. }).start();
  218. return true;
  219. }
  220.  
  221. public void mensajes_guardados()
  222. {
  223. runOnUiThread(new Runnable() {
  224. @Override
  225. public void run() {
  226. try
  227. {
  228. //System.out.println("mostrando mensajes guardados");
  229. String[][] datosbackup = backup.getMen();
  230. int i = 0;
  231. // System.out.print("antes de empezar el while");
  232. while (datosbackup[i][0] != null)
  233. {
  234.  
  235. //System.out.println("entrando al blucle de datos");
  236. paquete paquetecopy = (paquete) paquete.clone();
  237. /*
  238. System.out.println("datos backup="+datosbackup[i][1]);
  239. System.out.println("datos backup="+datosbackup[i][2]);*/
  240. paquetecopy.setMensaje_env(datosbackup[i][1]);
  241. paquetecopy.setNombre_us(datosbackup[i][2]);
  242. array.add(paquetecopy);
  243. adaptador.notifyDataSetChanged();
  244. System.out.println("objetos en el array="+array.size());
  245. System.out.println("se actualizo el adaptadosr de items");
  246. i++;
  247. }
  248.  
  249.  
  250. }catch (Exception e)
  251. {
  252. System.out.println("Hay una excepcion y es:"+e.getMessage());
  253. }
  254. }
  255. });
  256.  
  257. }
  258.  
  259. public String getIP()
  260. {
  261. try {
  262. WifiManager wifimanager= (WifiManager) context.getSystemService(Context.WIFI_SERVICE);//a travez del manejador del wifi obtenemos el wifi servicio
  263. WifiInfo wifiInfo = wifimanager.getConnectionInfo();//obtenemos la informacion del wifi
  264. int IpAddress = wifiInfo.getIpAddress();//obtenemos la ip a travez de wifiInfo
  265. return String.format(Locale.getDefault().getDefault(), "%d.%d.%d.%d",
  266. (IpAddress & 0xff), (IpAddress >> 8 & 0xff),
  267. (IpAddress >> 16 & 0xff), (IpAddress >> 24 & 0xff));//retornamos la ip convertida a string
  268. }
  269. catch (Exception e) {
  270. Log.e(TAG,e.getMessage());
  271. return null;
  272. }
  273. }
  274.  
  275. }
  276.  
  277. class paquete_adapter extends BaseAdapter
  278. {
  279. Context context;
  280. List<paquete> listaobjetos;
  281.  
  282. public paquete_adapter(Context context, List<paquete> listaobjetos)
  283. {
  284. this.context=context;
  285. this.listaobjetos=listaobjetos;
  286. }
  287.  
  288. public void clearData() {
  289. // clear the data
  290. listaobjetos.clear();
  291. }
  292.  
  293. @Override
  294. public int getCount() {
  295.  
  296. return listaobjetos.size();
  297. }
  298.  
  299. @Override
  300. public Object getItem(int posicion) {
  301. return listaobjetos.get(posicion);
  302. }
  303.  
  304. @Override
  305. public long getItemId(int posicion) {
  306. return listaobjetos.get(posicion).getId();
  307. }
  308.  
  309. @Override
  310. public View getView(int posicion, View convertView, ViewGroup parents) {
  311. View vista=convertView;
  312.  
  313. //obtener inflater
  314. // if(vista==null) {
  315. LayoutInflater inflater = LayoutInflater.from(context);
  316. vista = inflater.inflate(R.layout.mensaje_enviado, null);
  317. //}
  318.  
  319. //referencias UI
  320. ImageView fotousuario=(ImageView) vista.findViewById(R.id.fotousuario);
  321. TextView mensage = (TextView) vista.findViewById(R.id.mensage);
  322. TextView usuario = (TextView) vista.findViewById(R.id.usuario);
  323. TextView fecha = (TextView) vista.findViewById(R.id.fecha);
  324.  
  325.  
  326. //setup
  327. fotousuario.setImageResource(R.drawable.nofoto);
  328. mensage.setText(listaobjetos.get(posicion).getMensaje_env().toString());
  329. usuario.setText(listaobjetos.get(posicion).getNombre_us());
  330. fecha.setText("12/12/12");
  331. System.out.println("adaptador="+listaobjetos.get(posicion).getMensaje_env().toString());
  332. //System.out.println("adaptador="+listaobjetos.get(posicion).getNombre_us());
  333.  
  334.  
  335. return vista;
  336. }
  337. }
Add Comment
Please, Sign In to add comment