First of all, I am new to Android, and I want to clarify that I have already investigated and searched for tutorials, what I intend to do is, solely and exclusively, that information can be saved in an Android application through a form which contains: EditText
and Spinners
. It should be clarified that I have already done this on a web page, but now I want to create the application that performs the same function, that is, save.
I also want to clarify that I have already done this before in java, but I have been searching the Internet for days and days and I can't find any similar example. Also, from the little I have found, I have tried to adapt it to what I need and nothing. Is what I want to do very complicated or is it more difficult to do this kind of thing in Android?
Well, I don't want them to do the project for me, but could someone guide me on what I need to do?
After researching your advice I decided to try doing it natively and so far I have the following but I am having trouble saving the date formats and I have no idea how to save thespinners
I attach the image of my form (the button that saves says next because I still intend to make some changes)
The xml of the image above is as follows:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.server.guardar_a.MainActivity">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/scrollView">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Spinner
android:layout_width="140dp"
android:layout_height="wrap_content"
android:id="@+id/sp_tiempodeuso"
android:focusable="true"
android:layout_below="@+id/txtv_tiempouso"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="140dp"
android:layout_height="30dp"
android:text="Tiempo de uso:"
android:textColor="#000000"
android:textSize="20sp"
android:id="@+id/txtv_tiempouso"
android:layout_alignTop="@+id/txtv_docente" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="time"
android:ems="10"
android:hint="Hora de Inicio"
android:textColorHint="#424242"
android:id="@+id/txt_horainicio"
android:imeOptions="actionNext"
android:layout_below="@+id/txt_fechadeuso"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="18dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="none"
android:descendantFocusability="blocksDescendants"
android:ems="10"
android:hint="Fecha de uso"
android:textColorHint="#424242"
android:nextFocusDown="@+id/txt_horainicio"
android:id="@+id/txt_fechadeuso"
android:imeOptions="actionNext"
android:layout_below="@+id/txt_practica"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="16dp"
android:onClick="mostrarCalendario" />
<Spinner
android:layout_width="140dp"
android:layout_height="wrap_content"
android:id="@+id/sp_docente"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_alignBaseline="@+id/sp_tiempodeuso"
android:layout_alignBottom="@+id/sp_tiempodeuso"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="130dp"
android:layout_height="30dp"
android:text="Docente:"
android:textColor="#000000"
android:id="@+id/txtv_docente"
android:textSize="20sp"
android:layout_marginTop="31dp"
android:layout_below="@+id/txt_horainicio"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/txt_practica"
android:hint="Practica"
android:textColorHint="#424242"
android:layout_marginTop="9dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:text="Siguiente"
android:textSize="20sp"
android:id="@+id/btn_form1"
android:layout_below="@+id/sp_tiempodeuso"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="41dp"/>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
My JSONParser class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser(){
}
public JSONObject getJSONFromUrl(final String url){
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}catch (ClientProtocolException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null){
sb.append(line+"\n");
}
is.close();
json = sb.toString();
}catch (Exception e){
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
public JSONObject makeHttpRequest(String url, String method,
List params){
try{
if(method == "POST"){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params,"utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}catch (ClientProtocolException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
is.close();
json = sb.toString();
}catch (Exception e){
Log.e("Buffer Error","Error converting result"+e.toString());
}
try{
jObj = new JSONObject(json);
}catch (JSONException e){
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
And my MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private EditText practica, fechauso, horainicio;
private Button botonform1;
Spinner n_docentes, t_uso;
private int anio, dia, mes, hora, minuto;
private static final int TIPO_DIALOGO=0;
private static DatePickerDialog.OnDateSetListener oyenteSelectorFecha;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String REGISTER_URL = "http://wservervv.esy.es/laboratorio/guardar_solicitud.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
practica = (EditText)findViewById(R.id.txt_practica);
fechauso = (EditText)findViewById(R.id.txt_fechadeuso);
horainicio = (EditText)findViewById(R.id.txt_horainicio);
// t_uso = (Spinner)findViewById(R.id.sp_tiempodeuso);
// n_docentes = (Spinner)findViewById(R.id.sp_docente);
botonform1 = (Button)findViewById(R.id.btn_form1);
botonform1.setOnClickListener(this);
fechauso.setInputType(InputType.TYPE_NULL);
ArrayAdapter adapter_d = ArrayAdapter.createFromResource(this, R.array.Nombres_Docentes, R.layout.spiner_item_lab);
n_docentes.setAdapter(adapter_d);
ArrayAdapter adapter_t = ArrayAdapter.createFromResource(this, R.array.Tiempo_Uso, R.layout.spiner_item_lab);
t_uso.setAdapter(adapter_t);
Calendar calendario = Calendar.getInstance();
anio = calendario.get(Calendar.YEAR);mes = calendario.get(Calendar.MONTH);dia = calendario.get(Calendar.DAY_OF_MONTH);
oyenteSelectorFecha = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
anio = year;mes = monthOfYear;dia = dayOfMonth;mostrarFecha();
/* try {
Thread.sleep (5000);
} catch (Exception e) {
// Mensaje en caso de que falle
} */
horainicio.requestFocus();
}
};
fechauso.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
//Si tiene el Foco esconde el teclado y muestra el datePicker
if(hasFocus){
closeSoftKeyBoard();mostrarCalendario(fechauso);
}
}
});
horainicio.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
//Si tiene el Foco Esconde el teclado y muestra el timePicker
if(hasFocus){
closeSoftKeyBoard();
mostrarTime();
}
}
});
}
@Override
public void onClick(View args0) {
if(args0 == horainicio){
closeSoftKeyBoard();
mostrarTime();
}
if(args0 == botonform1) {
String practicaa = practica.getText().toString();
String fechausoo = fechauso.getText().toString();
String horainicioo = horainicio.getText().toString();
// String t_usoo = t_uso.getText().toString();
// String n_docentess = n_docentes.getText().toString();
new CreateUser().execute(practicaa, fechausoo, horainicioo);
}
}
class CreateUser extends AsyncTask<String, String, String> {
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Guardando.....");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// Todo Auto-generated method stub
// Check for success tag
int success;
String practicaa = args[0];
String fechausoo = args[1];
String horainicioo = args[2];
// String t_usoo = args[3];
// String n_docentess = args[4];
try{
List params = new ArrayList();
params.add(new BasicNameValuePair("practica", practicaa));
params.add(new BasicNameValuePair("fecha_prestamo", fechausoo));
params.add(new BasicNameValuePair("hora_prestamo", horainicioo));
// params.add(new BasicNameValuePair("horas_uso", t_usoo));
// params.add(new BasicNameValuePair("idusuario", n_docentess));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(
REGISTER_URL, "POST", params);
Log.d("Registering attempt", json.toString());
success = json.getInt(TAG_SUCCESS);
if(success == 1){
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Registering Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
}catch (JSONException e){
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),"Usuario guardado con exito... ",Toast.LENGTH_LONG).show();
return null;
}
protected void onPostExecute(String file_url){
pDialog.dismiss();
if (file_url != null){
Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
public void mostrarTime(){
// Get Current Time
final Calendar c = Calendar.getInstance();
hora = c.get(Calendar.HOUR);
minuto = c.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
horainicio.setText(hourOfDay + ":" + minute+":00");
// t_uso.requestFocus();
}
}, hora, minuto, false);
timePickerDialog.show();
}
public void closeSoftKeyBoard() {
InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id){
case 0:
return new DatePickerDialog(this, oyenteSelectorFecha, anio, mes, dia);
}
return null;
}
public void mostrarCalendario(View control){
showDialog(TIPO_DIALOGO);
}
public void mostrarFecha(){
fechauso.setText(anio+"-"+(mes+1)+"-"+dia);
}
}
The strings.xml
<resources>
<string name="app_name">Guardar_A</string>
<!-- Spinner docentes -->
<string-array name="Nombres_Docentes">
<item>Seleccione</item>
<item>Juan</item>
<item>Pedro</item>
<item>Jose</item>
</string-array>
<!-- Spinner tiempo de uso -->
<string-array name="Tiempo_Uso">
<item>Seleccione</item>
<item>1 Hora</item>
<item>2 Horas</item>
<item>3 Horas</item>
</string-array>
</resources>
my php files:
db_config.php
<?php
define('DB_USER',"u557976579_swgvv");
define('DB_PASSWORD',"guardar_a");
define('DB_DATABASE',"u557976579_bdser");
define('DB_SERVER',"mysql.hostinger.mx");
?>
db_connect.php
<?php
class DB_CONNECT {
function __construct(){
$this->connect();
}
function __destruct(){
$this->close();
}
function connect(){
require_once __DIR__ . '/db_config.php';
$con = @mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
$db = @mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
return $con;
}
function close(){
mysql_close();
}
}
?>
save_request.php
guardar_solicitud.php
<?php
$response = array();
//if (isset($_POST['idusario']) && isset($_POST['fecha_prestamo']) && isset($_POST['hora_prestamo']) && isset($_POST['horas_uso']) && isset($_POST['practica']) && isset($_POST['idusuariosolicitud'])){
if (isset($_POST['fecha_prestamo']) && isset($_POST['hora_prestamo']) && isset($_POST['practica'])){
$nombredocente = 4;
$fechauso = $_POST['fechauso'];
$horainicio = $_POST['horainicio'];
$timeuso = 1;
$practica = $_POST['practica'];
$usuariosolicitud=1;
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("INSERT INTO prestamo(idusuario,fecha_prestamo,hora_prestamo,horas_uso,practica,idusuariosolicitud) VALUES('$nombredocente', '$fechauso', '$horainicio', '$timeuso','$practica', '$usuarioquesolicita')");
if ($result){
$response["success"] = 1;
$response["message"] = "Product successfully created.";
echo json_encode($response);
}else{
$response["success"] = 0;
$response["message"] = "Oops! An error ocurred.";
echo json_encode($response);
}
}else{
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
echo json_encode($response);
}
?>
That's what I have so far
Si tienes ya tu codigo en HTML que realiza esa acción simplemente puedes cargar tu página en un
WebView
dentro de tu app, dejando el HTML en un archivo local de la aplicación, ahora si lo que quieres es pasarlo a un formulario nativo de Android como mencionas con EditText y Spinners necesitaras primero realizar un webservice para la comunicación de la app con tu base de datos (crear registros, extraer catalogos de información para los spinners, etc...).Good, actually if you already have the page working in the browser it is actually very easy since with apache cordova you can pass your code to a project with this framework, which is used to create hybrid applications for the different operating systems ios, android etc. , there are tools that help us to do it faster like ionic, jquery mobile, onsen UI etc.
apache cordova: click to go to the page!
ionic framework: click to go to the page!