1. Insertar un LinearLayout (horizontal)
2. Agregar dos botones
3. A un boton, ponerle layout:width: 0 y layout:weight: .80
4. Al otro ponerle layout:width: 0 y layout:weight: .20
Cambiar el estilo de la aplicacion en Android Studio
Editar el archivo \src\main\res\values\styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Light">
<!-- Customize your theme here. -->
</style>
</resources>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Light">
<!-- Customize your theme here. -->
</style>
</resources>
Barcode scanner con ZBarScanner en Android Studio
[El codigo fuente esta en Google Drive, en la carpeta Android Studio]
https://github.com/dm77/ZBarScanner
https://github.com/dm77/ZBarScanner
Ejemplo de lista clickeable con Android Studio
package com.example.crusso_pc.app1;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
ListView lv = (ListView) findViewById(R.id.lista1);
String[] values = new String[] { "Android List View",
"Adapter implementation",
"Simple List View In Android",
"Create List View Android",
"Android Example",
"List View Source Code",
"List View Array Adapter",
"Android Example List View"
};
/* Tambien se puede hacer con arrraylists!
ArrayList<String> values =
new ArrayList<String>();
values.add(matricula);
values.add("matricula1");
values.add("matricula2");
values.add("matricula3");
values.add("matricula4");
*/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
long id) {
// We know the View is a TextView so we can cast it
TextView clickedView = (TextView) view;
Toast.makeText(MyActivity.this, "Item with id [" + id + "] - Position [" + position + "] - Planet [" + clickedView.getText() + "]", Toast.LENGTH_SHORT).show();
}
});
}
}
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
ListView lv = (ListView) findViewById(R.id.lista1);
String[] values = new String[] { "Android List View",
"Adapter implementation",
"Simple List View In Android",
"Create List View Android",
"Android Example",
"List View Source Code",
"List View Array Adapter",
"Android Example List View"
};
/* Tambien se puede hacer con arrraylists!
ArrayList<String> values =
new ArrayList<String>();
values.add(matricula);
values.add("matricula1");
values.add("matricula2");
values.add("matricula3");
values.add("matricula4");
*/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
long id) {
// We know the View is a TextView so we can cast it
TextView clickedView = (TextView) view;
Toast.makeText(MyActivity.this, "Item with id [" + id + "] - Position [" + position + "] - Planet [" + clickedView.getText() + "]", Toast.LENGTH_SHORT).show();
}
});
}
}
Android Studio 0.8.1 - step by step
1. Ir al SDK manager, ejecutando c:\android-studio\sdk\tools\android.bat (invocar el SDK manager asi
evita el error "sdk manager a folder failed to be moved")
2. Instalar Android 4.1.2 (api 16) y las android sdk tools, sdk platform-tools y sdk build-tools
3. Crear un nuevo AVD (Android virtual device) con estos settings
Device: Nexus 4
Target: Android 4.1.2 - API Level 16
CPU/ABI: ARM (armeabi-v7a)
Skin: Skin with dynamic hardware controls
5. Abrir el android studio, crear un nuevo proyecto con la version de SDK 16.
6. El apk lo genera automaticamente en esta ruta
C:\Users\CRUSSO_PC\AndroidStudioProjects\App1\app\build\outputs\apk\app-debug.apk
(se puede pasar al cel e instalarla)
(Si un componente (ej, calendarView) no se puede usar por un problema con la version de SDK:
Ir al archivo AndroidManifest.xml (en la raiz del proyecto), y hacer click en "uses sdk",
y cambiar la "min sdk version" a 11 por ej.
evita el error "sdk manager a folder failed to be moved")
2. Instalar Android 4.1.2 (api 16) y las android sdk tools, sdk platform-tools y sdk build-tools
3. Crear un nuevo AVD (Android virtual device) con estos settings
Device: Nexus 4
Target: Android 4.1.2 - API Level 16
CPU/ABI: ARM (armeabi-v7a)
Skin: Skin with dynamic hardware controls
5. Abrir el android studio, crear un nuevo proyecto con la version de SDK 16.
6. El apk lo genera automaticamente en esta ruta
C:\Users\CRUSSO_PC\AndroidStudioProjects\App1\app\build\outputs\apk\app-debug.apk
(se puede pasar al cel e instalarla)
(Si un componente (ej, calendarView) no se puede usar por un problema con la version de SDK:
Ir al archivo AndroidManifest.xml (en la raiz del proyecto), y hacer click en "uses sdk",
y cambiar la "min sdk version" a 11 por ej.
Obtener cotizaciones de Mercado Libre con gson
package PaqueteAplicacion;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.google.gson.Gson;
public class Aplicacion {
public static void main(String[] args) throws MalformedURLException, IOException {
String uri = "https://api.mercadolibre.com/currency_conversions/search?from=USD&to=UYU";
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
if (connection.getResponseCode() != 200) {
throw new RuntimeException("Error : HTTP error code : "
+ connection.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(connection.getInputStream())));
String output = br.readLine();
Gson gson = new Gson();
Cotizacion person = gson.fromJson(output, Cotizacion.class);
System.out.println(person.getRatio());
connection.disconnect();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.google.gson.Gson;
public class Aplicacion {
public static void main(String[] args) throws MalformedURLException, IOException {
String uri = "https://api.mercadolibre.com/currency_conversions/search?from=USD&to=UYU";
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
if (connection.getResponseCode() != 200) {
throw new RuntimeException("Error : HTTP error code : "
+ connection.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(connection.getInputStream())));
String output = br.readLine();
Gson gson = new Gson();
Cotizacion person = gson.fromJson(output, Cotizacion.class);
System.out.println(person.getRatio());
connection.disconnect();
}
}
package PaqueteAplicacion;
import java.math.BigDecimal;
public class Cotizacion {
private BigDecimal ratio;
private String mercado_pago_ratio;
public BigDecimal getRatio() {
return ratio;
}
public void setRatio(BigDecimal ratio) {
this.ratio = ratio;
}
public String getMercado_pago_ratio() {
return mercado_pago_ratio;
}
public void setMercado_pago_ratio(String mercado_pago_ratio) {
this.mercado_pago_ratio = mercado_pago_ratio;
}
}
Ejemplos de archivos de configuracion correctos en Java EE
C:\_KARINA\Fuentes\Obligatorio\AppAchilles\AppAchilles-ejb\setup\glassfish-resources.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
<jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="pool-achilles" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
<property name="serverName" value="localhost"/>
<property name="portNumber" value="3306"/>
<property name="databaseName" value="achilles"/>
<property name="User" value="root"/>
<property name="Password" value="root"/>
<property name="URL" value="jdbc:mysql://localhost:3306/achilles?zeroDateTimeBehavior=convertToNull"/>
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
</jdbc-connection-pool>
<jdbc-resource enabled="true" jndi-name="jdbc/achilles" object-type="user" pool-name="pool-achilles"/>
</resources>
C:\_KARINA\Fuentes\Obligatorio\AppAchilles\AppAchilles-ejb\src\conf\persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="AppAchillesPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/achilles</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>
RESTful web services con NetBeans 7.4
1. Crear un Enterprise Application (File / New Project / Java Web / Web Application)
2. Crear una Web Application (File / New Project / Java EE / Enterprise Application) [elegir como Enterprise Application la creada en el paso 1)
3. Sobre el Web Application, click derecho y New / RESTful Web Services from Patterns...
4. Simple Root Resource
5. Como nombre de package, uy.com.prueba.servicios
6. Ingresar el Path (ej /servicio1)
7. Ingresar el nombre de la clase (ej, PruebaResource)
8. Elegir el mime type (ej, text/plain)
9. En el metodo que esta debajo del @GET, agregar el codigo
return "hola";
10. Boton derecho en el web application, y deploy.
11. Ir a un browser y poner
http://localhost:8080/WebApplication2/webresources/servicio1
2. Crear una Web Application (File / New Project / Java EE / Enterprise Application) [elegir como Enterprise Application la creada en el paso 1)
3. Sobre el Web Application, click derecho y New / RESTful Web Services from Patterns...
4. Simple Root Resource
5. Como nombre de package, uy.com.prueba.servicios
6. Ingresar el Path (ej /servicio1)
7. Ingresar el nombre de la clase (ej, PruebaResource)
8. Elegir el mime type (ej, text/plain)
9. En el metodo que esta debajo del @GET, agregar el codigo
return "hola";
10. Boton derecho en el web application, y deploy.
11. Ir a un browser y poner
http://localhost:8080/WebApplication2/webresources/servicio1
Ejemplos de JPA - Guia #2 [COMPLETA]
0. Crear la base de datos achilles (ir a Inicio / Programas / MySql / MySql Server 5.6 / MySql 5.6 Command Line Client
Poner el password (root)
Poner Show Databases; (enter)
Si ya no existe achilles,
Create Database achilles;
exit
1. Creo el AppAchilles y dejo marcado que cree el modulo EJB
2. Creo el dominio (desmarco que cree la main class)
3. Creo la clase Categoria, y le pongo como package: uy.com.achilles.dominio
4. En la ficha Services, crear una nueva coneccion a la base achilles (poner root root en el usr y pwd)
5. Sobre el EJB crear un persistence unit (OJO!! A LA CONEXION NOMBRARLA ASI: java:app/achilles (SINO, FALLA EL DEPLOY)
6. Sobre el EJB, new / entity class (nombre CategoriaEntity, y package uy.com.achilles.entidades)
7. Agregar los atributos en la entidad creada (para eso ver los que estan en el dominio y copiarlos)
8. Agregar los decoradores que falten para los nombres de las tablas, campos, etc (@Table(name="CATEGORIA"), @OneToOne, etc)
9. Hacer Clean and Build de AppAchilles
10. Hacer Deploy de AppAchilles
Va a dar un error: SEVERE: Exception while deploying the app [AppAchilles] : Application [AppAchilles] contains no valid components
[ESTO ES PORQUE EL EJB NO TIENE NINGUN SESSION BEAN!!!]
11. Crear un session bean dentro del EJB
12. Hacer clean and build del EJB
13. Hacer deploy del EJB
[SI NO CREA LAS TABLAS ES PORQUE ES NECESARIO IMPLEMENTAR EL SESSION BEAN!!! AHI ES DONDE SE ESPECIFICA EL PERSISTENCE CONTEXT]
14. Crear el Session Bean (stateless, local)
15. Crear un Web Service dentrod de EJB (elegir la opcion de crearlo a partir de un SB existente)
16. Crear una nueva java app. llamada ClientePrueba
17. Dentro de ella, crear un webservice client, que apunte al WSDL del servicio creado en el paso 15.
18. Agregar el codigo:
CategoriaWS port = new CategoriaWS_Service().getCategoriaWSPort();
Categoria cat = new Categoria();
cat.setId(new Long(1));
cat.setNombre("categoria1");
cat.setDimensiones("10x10x10");
cat.setNotas("Notas cat 1");
port.alta(cat);
Poner el password (root)
Poner Show Databases; (enter)
Si ya no existe achilles,
Create Database achilles;
exit
1. Creo el AppAchilles y dejo marcado que cree el modulo EJB
2. Creo el dominio (desmarco que cree la main class)
3. Creo la clase Categoria, y le pongo como package: uy.com.achilles.dominio
4. En la ficha Services, crear una nueva coneccion a la base achilles (poner root root en el usr y pwd)
5. Sobre el EJB crear un persistence unit (OJO!! A LA CONEXION NOMBRARLA ASI: java:app/achilles (SINO, FALLA EL DEPLOY)
6. Sobre el EJB, new / entity class (nombre CategoriaEntity, y package uy.com.achilles.entidades)
7. Agregar los atributos en la entidad creada (para eso ver los que estan en el dominio y copiarlos)
8. Agregar los decoradores que falten para los nombres de las tablas, campos, etc (@Table(name="CATEGORIA"), @OneToOne, etc)
9. Hacer Clean and Build de AppAchilles
10. Hacer Deploy de AppAchilles
Va a dar un error: SEVERE: Exception while deploying the app [AppAchilles] : Application [AppAchilles] contains no valid components
[ESTO ES PORQUE EL EJB NO TIENE NINGUN SESSION BEAN!!!]
11. Crear un session bean dentro del EJB
12. Hacer clean and build del EJB
13. Hacer deploy del EJB
[SI NO CREA LAS TABLAS ES PORQUE ES NECESARIO IMPLEMENTAR EL SESSION BEAN!!! AHI ES DONDE SE ESPECIFICA EL PERSISTENCE CONTEXT]
14. Crear el Session Bean (stateless, local)
15. Crear un Web Service dentrod de EJB (elegir la opcion de crearlo a partir de un SB existente)
16. Crear una nueva java app. llamada ClientePrueba
17. Dentro de ella, crear un webservice client, que apunte al WSDL del servicio creado en el paso 15.
18. Agregar el codigo:
CategoriaWS port = new CategoriaWS_Service().getCategoriaWSPort();
Categoria cat = new Categoria();
cat.setId(new Long(1));
cat.setNombre("categoria1");
cat.setDimensiones("10x10x10");
cat.setNotas("Notas cat 1");
port.alta(cat);
Suscribirse a:
Comentarios (Atom)