djriber
Usuario (España)
Como hacerun array de productos con JSON y PHP para poder realizar otro tutorial con datos php JSON y andorid link: https://www.youtube.com/watch?v=dKfJiV9iQNk
Funciones con un retorno array de tres valores. En el próximo tutorial con valores mysql. link: https://www.youtube.com/watch?v=ojW9ocDXmpA
Tutorial paginación php y Zebra 2.1.1 link: https://www.youtube.com/watch?v=Q0v3tOQHMgk
Un simple código php para sacar o extraer solo los números de una determinada cadena. Utilizamos ereg_replace y una simple expresión regular [^0-9] para extraer solo los números enteros de la cadena:
Introducción: ¿Hola que tal? vamos a ver como, generar una consulta Mysql a un servidor Hostinger, recibir la respuesta en Json, decodificarla en Android y Generar un ListView, para poder implementar lo dicho. MySQL Database. Estructura proyecto. Permisos INTERNET en AndroidManifest.xml Archivos PHP e conexión. Implementar JSONParser y MainActivity. Implementar XML. Finalmente compilar. 1. MySQL database. CREATE TABLE IF NOT EXISTS `producto` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nombre` varchar(150) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; 2.Estructura proyecto AndroidManifest.xml JSONParser MainActivity activity_main.xml single_post.xml 3.Permisos INTERNET. En el archivo principal AndroidManifest.xml , pondremos este codigo. <uses-permission android:name="android.permission.INTERNET" android:maxSdkVersion="18"/> 4.Archivos PHP Archivos necesarios para tu servidor web aqui db_config.php Productos.php 5.Implementar JSONParser y MainActivity JSONParser import android.util.Log; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.List; public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } // function get json from url // by making HTTP POST or GET mehtod public JSONObject makeHttpRequest(String url, String method, List params) { // Making HTTP request try { // check for request method if (method.equals("POST") { // request method is POST // defaultHttpClient 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.equals("GET") { // request method is 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; 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 parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } } ---------------------------- MainActivity import android.app.ProgressDialog;import android.os.AsyncTask;import android.support.v7.app.ActionBar;import android.support.v7.app.ActionBarActivity;import android.os.Bundle;import android.util.Log;import android.view.MenuItem;import android.widget.ListAdapter;import android.widget.ListView;import android.widget.SimpleAdapter;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import java.util.ArrayList;import java.util.HashMap;import java.util.List; public class MainActivity extends ActionBarActivity { // Progress Dialog private ProgressDialog pDialog; // Creating JSON Parser object JSONParser jParser = new JSONParser(); ArrayList<HashMap<String, String>> productesList; // JSON Node names private static final String TAG_SUCCESS = "success"; private static final String TAG_PRODUCTS = "productos"; private static final String TAG_NAME = "nombre"; // products JSONArray JSONArray products = null; ListView lista; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Hashmap para el ListView productesList = new ArrayList<>(); // Cargar los productos en el Background Thread new LoadAllProducts().execute(); lista = (ListView) findViewById(R.id.listAllProducts); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); }//fin onCreate @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to the action bar's Up/Home button case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } class LoadAllProducts extends AsyncTask<String, String, String> { /** * Antes de empezar el background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("Cargando..."; pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } /** * obteniendo todos los productos * */ protected String doInBackground(String... args) { // Building Parameters List params = new ArrayList(); // getting JSON string from URL String url_all_empresas = "http://pruevasandroid.esy.es/Productos.php"; JSONObject json = jParser.makeHttpRequest(url_all_empresas, "GET", params); // Check your log cat for JSON reponse Log.d("All Products: ", json.toString()); try { // Checking for SUCCESS TAG int success = json.getInt(TAG_SUCCESS); if (success == 1) { // products found // Getting Array of Products products = json.getJSONArray(TAG_PRODUCTS); // looping through All Products //Log.i("ramiro", "produtos.length" + products.length()); for (int i = 0; i < products.length(); i++) { JSONObject c = products.getJSONObject(i); // Storing each json item in variable String prod = c.getString(TAG_NAME); // creating new HashMap HashMap<String, String> map = new HashMap<>(); // adding each child node to HashMap key => value map.put(TAG_NAME, prod); productesList.add(map); } } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog after getting all products pDialog.dismiss(); // updating UI from Background Thread runOnUiThread(new Runnable() { public void run() { /** * Updating parsed JSON data into ListView * */ ListAdapter adapter = new SimpleAdapter( MainActivity.this, productesList, R.layout.single_post, new String[] { TAG_NAME, }, new int[] { R.id.nombre, }); // updating listview //setListAdapter(adapter); lista.setAdapter(adapter); } }); } }} 6.Implementar XML Activity_main.xml <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:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:id="@+id/main" android:clickable="false"> <ListView android:id="@+id/listAllProducts" android:layout_width="fill_parent" android:layout_height="wrap_content" android:dividerHeight="3dp" android:background="#fff"/></RelativeLayout> ---------------------------------- single_post.xml <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="match_parent" android:background="#f0f0f0" android:orientation="vertical" > <TextView android:text="nombre" android:id="@+id/nombre" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom" android:paddingBottom="2dip" android:padding="10dp" android:textColor="#333" android:textSize="12dp" android:textStyle="bold" android:layout_column="0" android:background="#ffff9000" /> </LinearLayout> 7.Compilar El resultado al compilar. Espero que les ayude, gracias y hasta la próxima.