Guest User

Untitled

a guest
Sep 3rd, 2015
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 28.13 KB | None | 0 0
  1. package com.example.prototiponfc.activities;
  2.  
  3. import com.example.prototiponfc.R;
  4. import com.example.prototiponfc.R.id;
  5. import com.example.prototiponfc.R.layout;
  6. import com.example.prototiponfc.R.menu;
  7.  
  8. import android.support.v7.app.ActionBarActivity;
  9. import android.content.Intent;
  10. import android.nfc.NfcAdapter;
  11. import android.os.Bundle;
  12. import android.view.Menu;
  13. import android.view.MenuItem;
  14. import android.view.View;
  15. import android.view.View.OnClickListener;
  16. import android.widget.Button;
  17. import android.widget.ImageView;
  18. import android.widget.Toast;
  19.  
  20.  
  21. public class MainActivity extends ActionBarActivity implements OnClickListener{
  22.  
  23. //ImageView
  24. ImageView imgHeader;
  25. //Botones
  26. Button btnBuscar, btnRegistrar, btnTerminar;
  27.  
  28. //Intent
  29. Intent intentBuscar, intentRegistrar;
  30.  
  31. //Adaptador de nfc
  32. //NfcAdapter mNfcAdapter;
  33. @Override
  34. protected void onCreate(Bundle savedInstanceState) {
  35. super.onCreate(savedInstanceState);
  36. setContentView(R.layout.activity_main);
  37.  
  38. imgHeader = (ImageView)findViewById(R.id.imageViewTitle);
  39.  
  40. btnBuscar = (Button) findViewById(R.id.btnBusqueda);
  41. btnRegistrar = (Button) findViewById(R.id.btnNuevoRegistro);
  42. btnTerminar = (Button) findViewById(R.id.btnTerminar);
  43.  
  44. btnBuscar.setOnClickListener(this);
  45. btnRegistrar.setOnClickListener(this);
  46. btnTerminar.setOnClickListener(this);
  47.  
  48. //iniciar adaptador de nfc, con un contexto (la actividad)
  49. // mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
  50. // verificarEstadoDeNFC(mNfcAdapter);
  51. }
  52.  
  53. private void verificarEstadoDeNFC(NfcAdapter mNfcAdapter2) {
  54. // TODO Auto-generated method stub
  55. if (mNfcAdapter2 != null && mNfcAdapter2.isEnabled())
  56. {
  57. Toast.makeText(this, "NFC disponible", Toast.LENGTH_SHORT).show();
  58. }
  59. else
  60. {
  61. Toast.makeText(this, "NFC no disponible, Active el servicio" +
  62. " e intente nuevamente", Toast.LENGTH_SHORT).show();
  63. //Terminar actividad
  64. finish();
  65. }
  66. }
  67.  
  68. @Override
  69. public boolean onCreateOptionsMenu(Menu menu) {
  70. // Inflate the menu; this adds items to the action bar if it is present.
  71. getMenuInflater().inflate(R.menu.main, menu);
  72. return true;
  73. }
  74.  
  75. @Override
  76. public boolean onOptionsItemSelected(MenuItem item) {
  77. // Handle action bar item clicks here. The action bar will
  78. // automatically handle clicks on the Home/Up button, so long
  79. // as you specify a parent activity in AndroidManifest.xml.
  80. int id = item.getItemId();
  81. if (id == R.id.action_settings) {
  82. return true;
  83. }
  84. return super.onOptionsItemSelected(item);
  85. }
  86.  
  87.  
  88. @Override
  89. public void onClick(View v) {
  90. // solo lanzar la actividad correspondiente o terminar
  91. if (v.getId() == btnBuscar.getId())
  92. {
  93. intentBuscar = new Intent(getApplicationContext(), SearchActivity.class);
  94. startActivity(intentBuscar);
  95. }
  96. else if (v.getId() == btnRegistrar.getId())
  97. {
  98. intentRegistrar = new Intent(getApplicationContext(), RegisterActivity.class);
  99. startActivity(intentRegistrar);
  100. }
  101. else if (v.getId() == btnTerminar.getId())
  102. {
  103. Toast.makeText(this, "¡Hasta luego!", Toast.LENGTH_SHORT).show();
  104. //Terminar
  105. finish();
  106. }
  107. }
  108. }
  109.  
  110. package com.example.prototiponfc.activities;
  111.  
  112. import java.io.ByteArrayOutputStream;
  113. import java.io.IOException;
  114. import java.io.UnsupportedEncodingException;
  115. import java.util.Locale;
  116.  
  117. import android.annotation.SuppressLint;
  118. import android.app.PendingIntent;
  119. import android.content.Intent;
  120. import android.content.IntentFilter;
  121. import android.database.Cursor;
  122. import android.graphics.Bitmap;
  123. import android.graphics.BitmapFactory;
  124. import android.net.Uri;
  125. import android.nfc.FormatException;
  126. import android.nfc.NdefMessage;
  127. import android.nfc.NdefRecord;
  128. import android.nfc.NfcAdapter;
  129. import android.nfc.Tag;
  130. import android.nfc.tech.Ndef;
  131. import android.nfc.tech.NdefFormatable;
  132. import android.os.Bundle;
  133. import android.os.Parcelable;
  134. import android.provider.MediaStore;
  135. import android.support.v7.app.ActionBarActivity;
  136. import android.util.Log;
  137. import android.view.Menu;
  138. import android.view.MenuItem;
  139. import android.view.View;
  140. import android.view.View.OnClickListener;
  141. import android.widget.Button;
  142. import android.widget.EditText;
  143. import android.widget.ImageView;
  144. import android.widget.Toast;
  145.  
  146. import com.android.volley.RequestQueue;
  147. import com.android.volley.toolbox.Volley;
  148. import com.example.prototiponfc.R;
  149. import com.example.prototiponfc.model.Persona;
  150. import com.parse.GetCallback;
  151. import com.parse.Parse;
  152. import com.parse.ParseException;
  153. import com.parse.ParseFile;
  154. import com.parse.ParseObject;
  155. import com.parse.ParseQuery;
  156. import com.parse.SaveCallback;
  157.  
  158. public class RegisterActivity extends ActionBarActivity implements OnClickListener{
  159.  
  160. /* codigo necesario para distinguir cuando se obtenga la fotografia */
  161. private static final int LOAD_IMAGE=1;
  162.  
  163. Button btnSelecFoto, btnRegresarAInicio, btnRegistrarUsuario;
  164. ImageView imageElement;
  165. EditText editNombre, editApellido, editCargo;
  166.  
  167. private boolean hayImagen = false;
  168.  
  169. private Intent intentNFC;
  170.  
  171. private Parcelable nfcTag;
  172.  
  173. private Bitmap myBitmap;
  174.  
  175. private RequestQueue requestQueue;
  176.  
  177. private NfcAdapter mNfcAdapter;
  178.  
  179. @Override
  180. protected void onCreate(Bundle savedInstanceState) {
  181. super.onCreate(savedInstanceState);
  182. setContentView(R.layout.activity_register);
  183.  
  184. btnSelecFoto = (Button)findViewById(R.id.btnSelecFoto);
  185. btnRegresarAInicio = (Button)findViewById(R.id.btnRegresarAInicio);
  186. btnRegistrarUsuario = (Button)findViewById(R.id.btnRegistrarUsuario);
  187.  
  188. editNombre = (EditText)findViewById(R.id.editNombre);
  189. editApellido = (EditText)findViewById(R.id.editApellido);
  190. editCargo = (EditText)findViewById(R.id.editCargo);
  191.  
  192. btnSelecFoto.setOnClickListener(this);
  193. btnRegresarAInicio.setOnClickListener(this);
  194. btnRegistrarUsuario.setOnClickListener(this);
  195.  
  196. //Conectar con backend de parse llave de app y de cliente
  197. Parse.initialize(getApplicationContext(),
  198. "0nCpqh1JNL4zpVDePY9bqW60qwsc5ro5vADHuzzD",
  199. "phifCGjvsbxWHSzgbdCDiuIRtJeGk6fbQHD7kupD");
  200.  
  201. //iniciar requestQueue
  202. requestQueue = Volley.newRequestQueue(this);
  203. //mNfcAdapter = MainActivity.
  204. mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
  205. //verificarEstadoDeNFC(mNfcAdapter);
  206.  
  207. }
  208.  
  209. @SuppressLint("NewApi") @Override
  210. protected void onNewIntent(Intent intent) {
  211. super.onNewIntent(intent);
  212.  
  213. //Reconocer la etiqueta
  214. nfcTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
  215. //Toast.makeText(this, ta.getTechList()[0], Toast.LENGTH_LONG).show();
  216. intentNFC = intent;
  217. disableForegroundDispatchSystem();
  218. // if (intentNFC.hasExtra(NfcAdapter.EXTRA_TAG))
  219. // {
  220. // Toast.makeText(this, "Etiqueta NFC detectada", Toast.LENGTH_LONG).show();
  221. //
  222. // Parcelable[] parcelables =intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
  223. // if (parcelables != null && parcelables.length > 0)
  224. // {
  225. // String mensajeNDEF = readTextFromNdefMessage((NdefMessage)parcelables[0]);
  226. //
  227. // Toast.makeText(this, mensajeNDEF, Toast.LENGTH_LONG).show();
  228. // }
  229. // else
  230. // {
  231. // Toast.makeText(this, "No se encontraron mensajes ndef", Toast.LENGTH_LONG).show();
  232. // }
  233. //
  234. // }
  235. }
  236. //Leer desde la etiqueta nfc
  237.  
  238. private String readTextFromNdefMessage(NdefMessage ndefMessage) {
  239. NdefRecord[] ndefRecords= ndefMessage.getRecords();
  240.  
  241. if (ndefRecords != null && ndefRecords.length > 0)
  242. {
  243. NdefRecord ndefRecord = ndefRecords[0];
  244. String tagContent = getTextFromNdefRecord(ndefRecord);
  245. //Asignar el contenido de la etiqueta en el textview destinado para eso
  246. //txtNfcContenido.setText(tagContent);
  247. return tagContent;
  248. }
  249. else
  250. {
  251. Toast.makeText(this, "No se encontraron records ndef", Toast.LENGTH_LONG).show();
  252. return null;
  253. }
  254. }
  255. public String getTextFromNdefRecord (NdefRecord ndefRecord)
  256. {
  257. String tagContent = null;
  258. try {
  259. byte[] payload = ndefRecord.getPayload();
  260. String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16" ;
  261. int languageSize = payload [0] & 0063 ;
  262. tagContent = new String(payload, languageSize + 1,
  263. payload.length - languageSize - 1, textEncoding);
  264. } catch (UnsupportedEncodingException e) {
  265. Log.e("getTextFromNdefRecord", e.getMessage());
  266. }
  267. return tagContent;
  268. }
  269.  
  270. @Override
  271. public boolean onCreateOptionsMenu(Menu menu) {
  272. // Inflate the menu; this adds items to the action bar if it is present.
  273. getMenuInflater().inflate(R.menu.register, menu);
  274. return true;
  275. }
  276.  
  277. @Override
  278. public boolean onOptionsItemSelected(MenuItem item) {
  279. // Handle action bar item clicks here. The action bar will
  280. // automatically handle clicks on the Home/Up button, so long
  281. // as you specify a parent activity in AndroidManifest.xml.
  282. int id = item.getItemId();
  283. if (id == R.id.action_settings) {
  284. return true;
  285. }
  286. return super.onOptionsItemSelected(item);
  287. }
  288.  
  289.  
  290.  
  291. /* (non-Javadoc)
  292. * @see android.support.v4.app.FragmentActivity#onPause()
  293. */
  294. @Override
  295. protected void onPause() {
  296. // TODO Auto-generated method stub
  297. super.onPause();
  298. disableForegroundDispatchSystem();
  299. }
  300.  
  301. private void disableForegroundDispatchSystem()
  302. {
  303. mNfcAdapter.disableForegroundDispatch(this);
  304. }
  305.  
  306. /* de NFC ACTIVAR y desactivar lectura de tajertas */
  307. private void enableForegroundDispatchSystem()
  308. {
  309. Intent intent = new Intent(this, MainActivity.class);
  310. intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
  311.  
  312. PendingIntent mpPendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
  313. IntentFilter[] intentFilters = new IntentFilter[]{};
  314.  
  315. mNfcAdapter.enableForegroundDispatch(this, mpPendingIntent, intentFilters, null);
  316. }
  317.  
  318. /* (non-Javadoc)
  319. * @see android.support.v4.app.FragmentActivity#onResume()
  320. */
  321. @Override
  322. protected void onResume() {
  323. // TODO Auto-generated method stub
  324. super.onResume();
  325. enableForegroundDispatchSystem();
  326. }
  327.  
  328. @Override
  329. public void onClick(View v) {
  330. // las opciones son cargarFoto, registrar usuario o volver al inicio
  331. Toast.makeText(this, "Recuerde acercar la etiqueta NFC aln" +
  332. " dispositivo para evitar errores", Toast.LENGTH_LONG);
  333. if (v.getId() == btnSelecFoto.getId())
  334. {
  335. cargarFotoDeGaleria();
  336. }
  337. else if (v.getId() == btnRegistrarUsuario.getId())
  338. {
  339. if (hayImagen == true) //si cargó imagen
  340. {
  341. if (editApellido.getText().length() > 0 &&
  342. editNombre.getText().length() > 0 &&
  343. editCargo.getText().length() > 0) //Si completó la informacionm
  344. {
  345. String nombre = editNombre.getText()+"";
  346. String apellido = editApellido.getText()+"";
  347. String cargo = editCargo.getText()+"";
  348. // if (nfcTag !=null) //Hay una etiqueta nfc disponible para escribir el código de registro en parse.com
  349. // {
  350. // registrarUsuario(nombre, apellido, cargo, myBitmap);
  351. // Toast.makeText(getApplicationContext(), "Acerque la etiqueta NFC para guardar" +
  352. // " el código asignado", Toast.LENGTH_LONG);
  353.  
  354. if (nfcTag !=null && intentNFC != null) //si la acercó, se puede escribir
  355. {
  356. Toast.makeText(getApplicationContext(), "Acerque la etiqueta NFC para guardar" +
  357. " el código asignado", Toast.LENGTH_LONG);
  358. registrarUsuario(nombre, apellido, cargo, myBitmap);
  359.  
  360. Persona ultimoElementoInsertado = obtenerUltimoRegistroDeParse();
  361. if(ultimoElementoInsertado!=null)
  362. {
  363. //Reconocer la etiqueta
  364. final Tag tag = intentNFC.getParcelableExtra(NfcAdapter.EXTRA_TAG);
  365. //Crear el mensaje para escribir en la etiqueta
  366. Log.e("idInsertado", ultimoElementoInsertado.getId());
  367. NdefMessage mnNdefMessage = createNdefMessage(ultimoElementoInsertado.getId());
  368. //EScribir el mensaje en la etiqueta
  369. writeNdefMessage(tag, mnNdefMessage);
  370. }
  371. else
  372. {
  373. Toast.makeText(getApplicationContext(), "PROBLEMAS", Toast.LENGTH_SHORT).show();
  374. }
  375. }
  376. else
  377. {
  378. Toast.makeText(this, "Debe acercar una etiqueta NFC para guardar" +
  379. " información del usuario", Toast.LENGTH_SHORT).show();
  380. }
  381. }
  382. else
  383. {
  384. Toast.makeText(this, "Debe llenar todos los campos", Toast.LENGTH_SHORT).show();
  385. }
  386.  
  387. }
  388. else
  389. {
  390. Toast.makeText(this, "No puede registrar un usuario si no selecciona una imagen", Toast.LENGTH_SHORT).show();
  391. }
  392. }
  393. else if (v.getId() == btnRegresarAInicio.getId())
  394. {
  395. Intent intent = new Intent(getApplicationContext(), MainActivity.class);
  396. startActivity(intent);
  397. //Terminar ESTA actividad
  398. this.finish();
  399. }
  400. }
  401.  
  402. private NdefRecord createTextRecord(String contenido)
  403. {
  404. try
  405. {
  406. byte[] language;
  407. language = Locale.getDefault().getLanguage().getBytes("UTF-8");
  408. final byte[] text = contenido.getBytes("UTF-8");
  409. final int languageSize =language.length;
  410. final int textLength = text.length;
  411. final ByteArrayOutputStream payload = new ByteArrayOutputStream(1 + languageSize + textLength);
  412.  
  413. payload.write((byte) ( languageSize & 0x1F));
  414. //El cero es el desplazamiento
  415. payload.write(language, 0, languageSize);
  416. payload.write(text, 0, textLength);
  417.  
  418. return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload.toByteArray());
  419. }
  420. catch(UnsupportedEncodingException ue)
  421. {
  422. Log.e("ERROR en createTextRecord", ue.getMessage());
  423. }
  424. return null;
  425. }
  426.  
  427. private NdefMessage createNdefMessage(String content)
  428. {
  429. NdefRecord ndefRecord = createTextRecord(content);
  430. NdefMessage ndefMessage = new NdefMessage(new NdefRecord[]{ndefRecord});
  431.  
  432. return ndefMessage;
  433. }
  434.  
  435. private void writeNdefMessage(Tag tag, NdefMessage ndefMessage)
  436. {
  437. Log.e("mensaje ndef", ndefMessage.toString());
  438. try
  439. {
  440. if (tag == null)
  441. {
  442. Toast.makeText(this, "Problemas al escribir en etiqueta n" +
  443. "(etiqueta no disponible o no reconocida)", Toast.LENGTH_LONG).show();
  444. }
  445.  
  446. Ndef ndef = Ndef.get(tag);
  447.  
  448. if (ndef == null) //si la tarjeta no tiene mensaje escrito(ndef)
  449. {
  450. //formatear la etiqueta con el formato ndef y escribir el mensaje
  451. formatNfcTag(tag, ndefMessage);
  452. }
  453. else
  454. {
  455. ndef.connect();
  456. if (!ndef.isWritable())
  457. {
  458. Toast.makeText(this, "No es posible escribir en la etiqueta", Toast.LENGTH_LONG).show();
  459. //si no se puede escribir, se cierra y se detiene
  460. ndef.close();
  461. return;
  462. }
  463. Toast.makeText(this, "Se pudo escribir en la etiqueta", Toast.LENGTH_LONG).show();
  464. ndef.writeNdefMessage(ndefMessage);
  465. ndef.close();
  466. }
  467.  
  468. }
  469. catch(IOException io)
  470. {
  471. Log.e("ERROR en write", io.getMessage() +"error");
  472. }
  473. catch(FormatException fe)
  474. {
  475. Log.e("ERROR en write", fe.getMessage());
  476. }
  477. }
  478.  
  479. private void formatNfcTag(Tag tag, NdefMessage ndefMessage)
  480. {
  481. try
  482. {
  483. NdefFormatable ndefFormatable = NdefFormatable.get(tag);
  484.  
  485. if (ndefFormatable == null) //la etiqueta no está enumerada en Tag.getTechList
  486. {
  487. Toast.makeText(this, "La etiqueta no está disponible" +
  488. " para formatear ()NdefFormteable", Toast.LENGTH_LONG).show();
  489. return; //para parar la aplicacion
  490. }
  491. ndefFormatable.connect();
  492. ndefFormatable.format(ndefMessage);
  493. ndefFormatable.close();
  494. Toast.makeText(this, "Se pudo escribir en la etiqueta", Toast.LENGTH_LONG).show();
  495. }
  496. catch(IOException e)
  497. {
  498. Log.e("ERROR", "eRROr de entrada salida (en formatNfcTag)");
  499.  
  500. }
  501. catch(FormatException fe)
  502. {
  503. Log.e("ERROR", "eRROr al formatear etiqueta (en formatNfcTag)");
  504. }
  505. }
  506.  
  507. private void escribirEnEtiqueta(String id) {
  508. //Toast.makeText(getApplicationContext(), "Nombre persona :" + id, Toast.LENGTH_LONG).show();
  509.  
  510. }
  511.  
  512. private Persona obtenerUltimoRegistroDeParse() {
  513. //obtener la tabla
  514. ParseQuery<ParseObject> query = ParseQuery.getQuery("Persona"); //Todos
  515. final Persona persona = new Persona();
  516. //ParseObject obj = query.get("MaIMQ7Y0V4");
  517. query.orderByDescending("createdAt"); //de mayor a menor
  518. query.getFirstInBackground(new GetCallback<ParseObject>() { //El primero de los mayores, o sea, el último
  519.  
  520. @Override
  521. public void done(ParseObject obj, ParseException arg1) {
  522. // TODO Auto-generated method stub
  523. String nombre = obj.getString("Nombre_persona");
  524. String apellido = obj.getString("Apellido_Persona");
  525. String id = obj.getObjectId();
  526.  
  527. Log.e("PUTO ID", id.toString());
  528. String cargo = obj.getString("Cargo");
  529. ParseFile foto = obj.getParseFile("Foto_persona");
  530. Log.e("DE IMAGEN", foto.getUrl().toString());
  531.  
  532. persona.setNombre(nombre);
  533. // Toast.makeText(getApplicationContext(), cargo, Toast.LENGTH_SHORT).show();
  534. persona.setApellido(apellido);
  535. persona.setFotoUrl(foto.getUrl());
  536. persona.setCargo(cargo);
  537. persona.setId(id);
  538. Toast.makeText(getApplicationContext(), persona.getId(), Toast.LENGTH_LONG).show();
  539. }
  540. });
  541. Toast.makeText(getApplicationContext(), persona.getId(), Toast.LENGTH_LONG).show();
  542. return persona;
  543. }
  544.  
  545. private void registrarUsuario(String nombre, String apellido, String cargo, Bitmap myBitmap2) {
  546. //ParseObject imagenParseObject = new pa
  547. ParseObject nuevoRegistro = new ParseObject("Persona");/*new ParseObject("PRUEBA");*/
  548.  
  549. nuevoRegistro.put("Nombre_persona", nombre);
  550. nuevoRegistro.put("Apellido_Persona", apellido);
  551. nuevoRegistro.put("Cargo", cargo);
  552. // nuevoRegistro.put("Foto_persona", myBitmap2);
  553.  
  554.  
  555.  
  556. //Intentar guardar imagen
  557. // Save image file
  558. // Drawable drawable = ...;
  559. // Bitmap bitmap = (Bitmap)((BitmapDrawable) drawable).getBitmap();
  560. ByteArrayOutputStream stream = new ByteArrayOutputStream();
  561. myBitmap2.compress(Bitmap.CompressFormat.JPEG, 100, stream);
  562. byte[] data = stream.toByteArray();
  563. //Ponerle nombre de la persona a la imagen
  564. String nombreImagen = nombre + "--image.jpg" ;
  565. ParseFile imageFile = new ParseFile(nombreImagen, data);
  566. // imageFile.saveInBackground();
  567. nuevoRegistro.put("Foto_persona", imageFile);
  568.  
  569. //ojo este si es el de guardar een parse
  570. nuevoRegistro.saveInBackground(new SaveCallback() {
  571.  
  572. @Override
  573. public void done(ParseException arg0) {
  574. // TODO Auto-generated method stub
  575. Toast.makeText(getApplicationContext(), "Registro exitoso", Toast.LENGTH_SHORT).show();
  576. Log.e("exito", "escritura en parse");
  577. limpiarPantalla();
  578. }
  579.  
  580.  
  581. }) ;
  582. // //Tratar de recuperar de una vez el objectId
  583. // ParseQuery<ParseObject> query = ParseQuery.getQuery("Persona");
  584. // ParseObject otro = query.get
  585. }
  586.  
  587. private void limpiarPantalla() {
  588. editApellido.setText("");
  589. editNombre.setText("");
  590. editCargo.setText("");
  591. imageElement.setImageResource(android.R.color.transparent);
  592. }
  593.  
  594. private void cargarFotoDeGaleria() {
  595. // TODO Auto-generated method stub
  596. // Este es el intent que manejará la seleccion de imagen de la galeria
  597. Intent intent = new Intent(Intent.ACTION_PICK,
  598. android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  599. int code = LOAD_IMAGE;
  600.  
  601. startActivityForResult(intent, code); // ---> Llama a onActivityResult
  602. }
  603.  
  604. /*Recibe un código de petición (arg0), un código de respuesta (arg1)y datos(arg2)
  605. este maldito método sobreescrito de Activity, no de la puta ActionBarActivity es
  606. el que implementará que se cargue la puta imagen seleccionada, dentro del ImagwVIew*/
  607. @Override
  608. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  609. super.onActivityResult(requestCode, resultCode, data);
  610.  
  611. //Para demoCamara verificar el codigo de peticion de la foto para saber como actuar qca en on activityResult
  612. switch (requestCode)
  613. {
  614. case LOAD_IMAGE:
  615. if (resultCode == RESULT_OK)
  616. {
  617. fromGallery(data);
  618. }
  619. break;
  620. //
  621. // case CAMERA:
  622. // if (resultCode == RESULT_OK)
  623. // {
  624. // fromCamera(/*data*/);
  625. // }
  626. // break;
  627. }
  628.  
  629. }
  630.  
  631. public void fromGallery(Intent data)
  632. {
  633. if ( data != null) //cambiado para demoCamara,
  634. //basada en la constante de esta clase y el codigo de respuesta fué una selección exitosa y hay datos
  635. {
  636. /* Declaro la uri de la imagen */
  637. Uri selectedImage = data.getData(); //datos tomados del intent quye se recibió
  638.  
  639. /* Definir un cursor que será el que ejecute una consulta
  640. * que finlmente mostrará la imagen, para crearlo se envia
  641. * un arreglo de Strings que es el que lleva la columna seleccionada */
  642. String[] filePathColumn = {MediaStore.Images.Media.DATA};
  643. /*Ahora si el cursor: Uri corresponde a la imagen seleccionada, que
  644. * en este caso corresponde al Uri que se definió previamente, se envia el
  645. * filePathColumn como elemento de la proyección, como se quiere todo o recibido,
  646. * entonces la seleccion será null y los argumentos de selección y ordenamiento
  647. * también serán null. NOTA::: Este tipo de seleccion de imagenes tambien es aplicable
  648. * para obtener otro tipo de archivos como canciones, videos, etc
  649. */
  650. Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
  651.  
  652. //Asumon que si se seleccionó una imagen, por lo tanto:
  653. if (cursor.moveToFirst())
  654. {
  655. //si hay al menos un primer resultado, entonces se obtiene la primera columna
  656. //obtengo el indice de la columna, correspondiente a la primera posicion del arreglo
  657. int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
  658. //ahora obtener la ruta como un String
  659. String picturePath=cursor.getString(columnIndex);
  660. //ahora se debe cerrar el cursor para liberar memoria
  661. cursor.close();
  662. //obtener el imageview para asignarle luego la imagen seleccionada
  663. // ImageView img = (ImageView)findViewById(R.id.image);
  664. imageElement = (ImageView)findViewById(R.id.imageElement);
  665. //Se asigna la imagendecodificando el archivo en base a la ruta de la imagen, declarada unosd pasos antes
  666. myBitmap = BitmapFactory.decodeFile(picturePath);
  667. // imageElement.setImageBitmap(BitmapFactory.decodeFile(picturePath));
  668. imageElement.setImageBitmap(myBitmap);
  669. hayImagen = true;
  670. }
  671. }
  672. }
  673. }
  674.  
  675. <?xml version="1.0" encoding="utf-8"?>
  676. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  677. package="com.example.prototiponfc"
  678. android:versionCode="1"
  679. android:versionName="1.0" >
  680.  
  681. <uses-sdk
  682. android:minSdkVersion="12"
  683. android:targetSdkVersion="21" />
  684.  
  685. <uses-permission android:name="android.permission.NFC" />
  686. <uses-permission android:name="android.permission.INTERNET" />
  687. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  688. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  689. <!--
  690. To retrieve OAuth 2.0 tokens or invalidate tokens to disconnect a user. This disconnect
  691. option is required to comply with the Google+ Sign-In developer policies
  692.  
  693. -->
  694. <uses-permission android:name="android.permission.USE_CREDENTIALS" />
  695. <!-- To access Google+ APIs: -->
  696. <uses-permission android:name="android.permission.INTERNET" />
  697.  
  698. <!-- To retrieve the account name (email) as part of sign-in: -->
  699. <uses-permission android:name="android.permission.GET_ACCOUNTS" />
  700.  
  701. <!-- To auto-complete the email text field in the login form with the user's emails -->
  702. <uses-permission android:name="android.permission.READ_PROFILE" />
  703. <uses-permission android:name="android.permission.READ_CONTACTS" />
  704.  
  705. <uses-feature
  706. android:name="android.hardware.nfc"
  707. android:required="false" />
  708.  
  709. <application
  710. android:allowBackup="true"
  711. android:icon="@drawable/ic_launcher"
  712. android:label="@string/app_name"
  713. android:theme="@style/AppTheme" >
  714. <activity
  715. android:name=".activities.MainActivity"
  716. android:label="@string/app_name" >
  717. <intent-filter>
  718. <action android:name="android.intent.action.MAIN" />
  719.  
  720. <category android:name="android.intent.category.LAUNCHER" />
  721. </intent-filter>
  722. </activity>
  723. <activity
  724. android:name=".activities.LoginActivity"
  725. android:label="@string/title_activity_login"
  726. android:windowSoftInputMode="adjustResize|stateHidden" >
  727. </activity>
  728. <activity
  729. android:name=".activities.RegisterActivity"
  730. android:label="@string/title_activity_register" >
  731. <intent-filter>
  732. <action android:name="android.intent.action.MAIN" />
  733.  
  734. <category android:name="android.intent.category.LAUNCHER" />
  735. </intent-filter>
  736. </activity>
  737. <activity
  738. android:name=".activities.SearchActivity"
  739. android:label="@string/title_activity_search" >
  740. </activity>
  741. <activity
  742. android:name="com.example.prototiponfc.activities.SearchResultsActivity"
  743. android:label="@string/title_activity_search_results" >
  744. </activity>
  745. </application>
  746.  
  747. </manifest>
Add Comment
Please, Sign In to add comment