como guardar en una variable un dato extraido desde una base de datos en mysql y android studio

Hola amigos hoy veremos un tutorial a base de las dudas que surgieron de algunos usuarios, preguntaban como se podía extraer un dato x de una base de datos y luego guardarlo o trabajar con dicha variable en android, les comento que una cosa es la web services y otra muy distinta la app. Una vez que tu obtienes un dato de tu ws , esos datos lo trabajas de forma normal como hemos hecho con variables normales, sin mas rodeos veamos el tutorial:
 
como guardar en una variable un dato extraído desde una base de datos en mysql y android studio
Para este ejercicio quiero aclarar que no importa en que este hecho la base de datos de la webservices sea mysql, postgresql, sql, etc. La parte de la app siempre sera la misma y no cambiara. Para este ejemplo extraeremos dos datos de nuestra base de datos un String y un int y luego trabajaremos con ellos.
Obtendremos una cadena y le agregaremos otra cadena formando dos palabras también obtendremos un entero y le sumaremos otro entero, como se muestra en la siguiente imagen:
PASO 1: Creamos nuestra base de datos, yo le llamare variable.

CREATE TABLE `obtener` (
  `id` int(11) NOT NULL,
  `nombre` varchar(100) NOT NULL,
  `edad` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `obtener` (`id`, `nombre`, `edad`) VALUES
(1, ‘ANDROFAST’, 20);
PASO 2: Creamos nuestra webservices
Creamos un archivo que nos servirá para conectarnos a nuestra BD llamado DatabaseConfig.php

<?php
$HostName = "localhost";
$HostUser = “root”;

$HostPass = “12345”;

$DatabaseName = “variable”;

?>

Creamos un segundo archivo llamado listar.php

<?php
include 'DatabaseConfig.php';
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);

if ($conn->connect_error) {

die(“Connection failed: “ . $conn->connect_error);
}

$sql = “SELECT * FROM obtener”;

$result = $conn->query($sql);

if ($result->num_rows >0) {

while($row[] = $result->fetch_assoc()) {

$tem = $row;

$json = json_encode($tem);
}

} else {
echo “No Results Found.”;
}
echo $json;
$conn->close();
?>

PASO 3: Creamos nuestra app empezamos por el modo gráfico, debe quedar como la siguiente imagen:

 

Les dejo en activity_main.xml en modo texto

<?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:padding="5dp"
    tools:context="com.androfast.pc.appguardarvariablebd.MainActivity">
<Button
android:id=“@+id/button”
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:text=“Cargar datos a los TextView del servidor “
android:layout_marginTop=“23dp”
android:layout_below=“@+id/txtJuntoInt”
android:layout_alignParentLeft=“true”
android:layout_alignParentStart=“true” />

<TextView
android:id=“@+id/txtNombre”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“TextView”
android:textSize=“25dp”
android:textColor=“#000”
android:gravity=“center”
android:layout_marginTop=“26dp”
android:layout_alignParentTop=“true”
android:layout_alignParentLeft=“true”
android:layout_alignParentStart=“true” />

<TextView
android:id=“@+id/txtEdad”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:layout_marginTop=“27dp”
android:text=“TextView”
android:textSize=“24sp”
android:textStyle=“bold”
android:layout_below=“@+id/txtNombre”
android:layout_alignParentLeft=“true”
android:layout_alignParentStart=“true” />

<TextView
android:id=“@+id/txtJuntoString”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“TextView”
android:layout_above=“@+id/txtJuntoInt”
android:layout_alignParentLeft=“true”
android:layout_alignParentStart=“true”
android:layout_marginBottom=“37dp” />

<TextView
android:id=“@+id/txtJuntoInt”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“TextView”
android:layout_centerVertical=“true”
android:layout_alignLeft=“@+id/txtJuntoString”
android:layout_alignStart=“@+id/txtJuntoString” />

<ProgressBar
android:id=“@+id/progressBar”
style=“?android:attr/progressBarStyle”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_below=“@+id/txtNombre”
android:layout_centerHorizontal=“true”
android:layout_marginTop=“22dp”
android:visibility=“gone”/>

</RelativeLayout>

Ahora debemos ir a nuestro AndroidManifest y agreguemos el siguiente permiso:

<uses-permission 
   android:name="android.permission.INTERNET"/>

Ahora nos vamos a nuestro build.gradle y debemos agregar lo siguiente como esta en rojo, dentro de los corchetes de android:

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"
    defaultConfig {
        applicationId "com.androfast.pc.appguardarvariablebd"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        useLibrary 'org.apache.http.legacy'
    }

Ahora por fin podemos trabajar con nuestro MainActivity

import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {

HttpResponse httpResponse;
Button button;
TextView textView,edad, juntoString,juntoInt;
JSONObject jsonObject = null ;
String StringHolder = “” ;
ProgressBar progressBar;
// Adding HTTP Server URL to string variable.
String HttpURL = “http://192.168.8.133/enviardato/listar.php”;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Assigning ID’s to button, textView and progressbar.
button = (Button)findViewById(R.id.button);
textView = (TextView)findViewById(R.id.txtNombre);
edad = (TextView)findViewById(R.id.txtEdad);
juntoString = (TextView)findViewById(R.id.txtJuntoString);
juntoInt = (TextView)findViewById(R.id.txtJuntoInt);
progressBar = (ProgressBar)findViewById(R.id.progressBar);

// Adding click lister to button.
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

// Showing progress bar on button click.
progressBar.setVisibility(View.VISIBLE);

//Calling GetDataFromServerIntoTextView method to Set JSon MySQL data into TextView.
new GetDataFromServerIntoTextView(MainActivity.this).execute();
// edad=textView;

}
});
}

// Declaring GetDataFromServerIntoTextView method with AsyncTask.
public class GetDataFromServerIntoTextView extends AsyncTask<Void, Void, Void>
{
// Declaring CONTEXT.
public Context context;

public GetDataFromServerIntoTextView(Context context)
{
this.context = context;
}

@Override
protected void onPreExecute()
{
super.onPreExecute();
}

@Override
protected Void doInBackground(Void… arg0)
{

HttpClient httpClient = new DefaultHttpClient();

// Adding HttpURL to my HttpPost oject.
HttpPost httpPost = new HttpPost(HttpURL);

try {
httpResponse = httpClient.execute(httpPost);

StringHolder = EntityUtils.toString(httpResponse.getEntity(), “UTF-8”);

} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try{
// Passing string holder variable to JSONArray.
JSONArray jsonArray = new JSONArray(StringHolder);
jsonObject = jsonArray.getJSONObject(0);

} catch ( JSONException e) {
e.printStackTrace();
}

catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {

// Mostramos el dato tipo cadena extraido de la BD.
textView.setText(jsonObject.getString(“nombre”));
//Almacenamos el dato extraido en la variable extnombre
String extnombre= textView.getText().toString();
//declaramos la variable unido y la sumamos a nuestro dato extraido
String unido1=“LA MEJOR WEB: “+extnombre;
//Mostramos en un nuevo texview la varible unido
juntoString.setText(unido1);

// Mostramos el dato tipo entero extraido de la BD.
edad.setText(Integer.toString(jsonObject.getInt(“edad”)));
//Almacenamos el dato extraido en la variable extnombre
int extedad = Integer.parseInt(edad.getText().toString());

//declaramos la variable unido y la sumamos a nuestro dato extraido
int unido2=2+extedad;
//Mostramos en un nuevo texview la varible unido
juntoInt.setText(“20+2= “+unido2);

} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//Hiding progress bar after done loading TextView.
progressBar.setVisibility(View.GONE);

}
}

}

PASO 4: Analizamos el código:

Primero obtenemos el dato tipo cadena “nombre” de la siguiente forma:

textView.setText(jsonObject.getString("nombre"));

Ahora lo almacenamos en la variable extnombre

 String extnombre=  textView.getText().toString();

Ahora obtenemos el dato tipo entero “edad” de la siguiente forma:

edad.setText(Integer.toString(jsonObject.getInt("edad")));

Ahora lo almacenamos en la variable extedad

int extedad =  Integer.parseInt(edad.getText().toString());

 

Con eso hemos terminado dejo el proyecto para que descargues si eres lo suficiente mente vago como para ir de frente a la descarga, al menos mira el paso 4 por un momento:
descargar: como guardar en una variable un dato extraído desde una base de datos, android

Deja una respuesta

Tu dirección de correo electrónico no será publicada.

WhatsApp chat