首先,我是Android新手,我想澄清一下,我已经调查并搜索了教程,我打算做的是,唯一且唯一的是,可以通过包含以下内容的表单将信息保存在Android应用程序中:EditText
和Spinners
。需要说明的是,我已经在一个网页上做了这个,但是现在我想创建执行相同功能的应用程序,即保存。
我也想澄清一下,我之前已经在java中做过这个,但是我已经在互联网上搜索了几天和几天,我找不到任何类似的例子。此外,从我发现的那一点点开始,我试图让它适应我需要的东西,什么都没有。我想做的事情是非常复杂还是在Android中做这种事情更难?
好吧,我不希望他们为我做这个项目,但是有人可以指导我做什么吗?
在研究了您的建议后,我决定尝试在本地进行,到目前为止,我有以下内容,但我无法保存日期格式,我不知道如何保存spinners
我附上了我的表格的图像(保存的按钮接下来说,因为我仍然打算进行一些更改)
上图的xml如下:
<?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>
我的JSONParser类
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;
}
}
还有我的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);
}
}
字符串.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>
我的 php 文件:
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);
}
?>
这就是我到目前为止所拥有的
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...).很好,实际上如果您已经在浏览器中运行了该页面,这实际上非常容易,因为使用apache cordova您可以将代码传递给具有此框架的项目,该框架用于为不同的操作系统 ios、android 等创建混合应用程序. ,有一些工具可以帮助我们更快地完成它,比如ionic、jquery mobile、onsen UI等。
阿帕奇科尔多瓦:点击进入页面!
离子框架:点击进入页面!