AlertDialog, MySQL соединение и Android - PullRequest
0 голосов
/ 20 июля 2011

У меня вопрос по AlertDialog в Android и MySQL соединении.

В соединении mysql, основанном на последнем вопросе. Я хочу поставить AlertDialog, когда база данных пуста, или результат запроса пуст, указывая информацию. Это возможно?

Вот мой код (сейчас работает):

package net.medinfo.movil.prot2;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class Busqueda2 extends Activity
{

    AutoCompleteTextView texto;
    Button boton;
    TextView resultado;
    String total;
    InputStream is = null;
    public void onCreate(Bundle SavedInstanceState)
    {
        super.onCreate(SavedInstanceState);
        setContentView(R.layout.main);
        texto = (AutoCompleteTextView) findViewById(R.id.cajaTexto);
        String[] meds = getResources().getStringArray(R.array.arreglo_medicamentos);
        ArrayAdapter <String> adapter = new ArrayAdapter <String> (this, R.layout.lista_med, meds);
        texto.setAdapter(adapter);
        boton = (Button) findViewById(R.id.botonBuscar);
        resultado = (TextView) findViewById(R.id.resultado);
        boton.setOnClickListener (new OnClickListener()
        {   
            @Override
            public void onClick(View v) 
            {
                //Se llama el metodo para ejecutar el recibo de datos
                resultado.setText(Medicamentos(total));

            }
        });
    }



    protected String Medicamentos (String returnString)
    {


        String txt = texto.getText().toString();
        if(!txt.equals(""))
        {
        String result ="";

        //Se envian datos de consulta;
        ArrayList<NameValuePair> parametros = new ArrayList<NameValuePair>();
        parametros.add(new BasicNameValuePair("name" , txt));       

        //Conectando a la base de datos
        try
        {
            HttpClient cliente = new DefaultHttpClient();
            HttpPost direccion = new HttpPost("http://10.0.2.2/medinfo/conexion.php");
            direccion.setEntity(new UrlEncodedFormEntity(parametros));
            HttpResponse respuesta = cliente.execute(direccion);
            HttpEntity entity = respuesta.getEntity();
            is = entity.getContent();
        }
        catch(Exception e)
        {
            Log.e("log_tag", "Error en la conexion a la base de datos"+e.toString());
            Toast.makeText(this, "Error al conectar a la base de datos", Toast.LENGTH_LONG).show();
        }

            //Transformar respuesta de la conexion en string
        try
        {

            BufferedReader reader = new BufferedReader (new InputStreamReader(is, "iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String linea = null;
            if ((linea = reader.readLine()) != null)
            {
                sb.append(linea + "\n");
            }
            is.close();
            result = sb.toString();
        }
        catch(Exception e)
        {
            Log.e("log_tag", "Error al transformar datos. "+e.toString());
            Toast.makeText(this, "Error al transformar datos", Toast.LENGTH_LONG).show();
        }

        //Recibir datos en formato JSON
        try
        {
            JSONArray jArreglo = new JSONArray(result);
            for(int i=0; i<jArreglo.length(); i++)
            {
                JSONObject json_datos = jArreglo.getJSONObject(i);
                Log.i("log_tag", "nombre: "+json_datos.getString("Nombre")+
                        ", cantidad: "+json_datos.getInt("Stock"));
                    returnString += "\n\t" + jArreglo.getJSONObject(i);
            }   
        }
        catch (JSONException e)
        {
                Log.e("log_tag", "Error al recibir datos"+e.toString());
                Toast.makeText(this, "Error al mostrar datos", Toast.LENGTH_LONG).show();
        }
        }
        else Toast.makeText(this, "Escriba un medicamento", Toast.LENGTH_LONG).show();
        texto.setText("");
        return returnString;
    }
}

Я ценю всю помощь.

ОБНОВЛЕНО: Ну, теперь я тестирую код, и я решил поместить алердиалог в JSONexception, до сих пор он работает, но у меня есть некоторые проблемы с кнопкой. кнопка «Ampliar Busqueda» должна вызывать метод с именем «Alternativos», когда выполняется то же самое, что и Medicamentos, но с другим запросом результат должен появиться в текстовом представлении «resultado», теперь у меня есть исключение java.lang.NullException. я не знаю почему

Это код

package net.medinfo.movil.prot2;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class Busqueda2 extends Activity
{

    AutoCompleteTextView texto;
    Button boton;
    TextView resultado;
    String total;
    String comp;
    InputStream is = null;
    public void onCreate(Bundle SavedInstanceState)
    {
        super.onCreate(SavedInstanceState);
        setContentView(R.layout.main);
        texto = (AutoCompleteTextView) findViewById(R.id.cajaTexto);
        String[] meds = getResources().getStringArray(R.array.arreglo_medicamentos);
        ArrayAdapter <String> adapter = new ArrayAdapter <String> (this, R.layout.lista_med, meds);
        texto.setAdapter(adapter);
        boton = (Button) findViewById(R.id.botonBuscar);
        resultado = (TextView) findViewById(R.id.resultado);
        final AlertDialog.Builder mensaje = new AlertDialog.Builder(this);
        mensaje.setTitle("Oops...");

        boton.setOnClickListener (new OnClickListener()
        {   
            @Override
            public void onClick(View v) 
            {
                //Se llama el metodo para ejecutar el recibo de datos
                resultado.setText(Medicamentos(total));
                while (resultado.equals(""))
                {

                    resultado.setText(total);
                }

            }
        });
    }

    protected String Medicamentos (String returnString)
    {


        String txt = texto.getText().toString();
        if(!txt.equals(""))
        {
        String result ="";

        //Se envian datos de consulta;
        ArrayList<NameValuePair> parametros = new ArrayList<NameValuePair>();
        parametros.add(new BasicNameValuePair("name" , txt));       

        //Conectando a la base de datos
        try
        {
            HttpClient cliente = new DefaultHttpClient();
            HttpPost direccion = new HttpPost("http://10.0.2.2/medinfo/conexion.php");
            direccion.setEntity(new UrlEncodedFormEntity(parametros));
            HttpResponse respuesta = cliente.execute(direccion);
            HttpEntity entity = respuesta.getEntity();
            is = entity.getContent();
        }
        catch(Exception e)
        {
            Log.e("log_tag", "Error en la conexion a la base de datos"+e.toString());
            Toast.makeText(this, "Error al conectar a la base de datos", Toast.LENGTH_LONG).show();
        }

            //Transformar respuesta de la conexion en string
        try
        {

            BufferedReader reader = new BufferedReader (new InputStreamReader(is, "iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String linea = null;
            if ((linea = reader.readLine()) != null)
            {
                sb.append(linea + "\n");
            }
            is.close();
            result = sb.toString();
        }
        catch(Exception e)
        {
            Log.e("log_tag", "Error al transformar datos. "+e.toString());
            Toast.makeText(this, "Error al transformar datos", Toast.LENGTH_LONG).show();
        }

        //Recibir datos en formato JSON

        try
        {
            JSONArray jArreglo = new JSONArray(result);
            for(int i=0; i<jArreglo.length(); i++)
            {
                JSONObject json_datos = jArreglo.getJSONObject(i);
                Log.i("log_tag", "nombre: "+json_datos.getString("Nombre")+
                        ", cantidad: "+json_datos.getInt("Stock"));
                    returnString += "\n\t" + jArreglo.getJSONObject(i); 
                    comp = json_datos.getString("componentes");
            }   
        }
        catch (JSONException e)
        {

                Log.e("log_tag", "Error al recibir datos"+e.toString());
                Toast.makeText(this, "Error al mostrar datos", Toast.LENGTH_LONG).show();
                AlertDialog.Builder mensaje = new AlertDialog.Builder(this);
                mensaje.setTitle("Oops...");
                mensaje.setMessage("El medicamento se encuentra sin stock");
                mensaje.setPositiveButton("Ampliar Busqueda", new DialogInterface.OnClickListener() 
                {

                    @Override
                    public void onClick(DialogInterface dialog, int which) 
                    {
                        resultado.setText(Alternativos(total));
                    }
                });
                mensaje.setNegativeButton("Reintentar", new DialogInterface.OnClickListener()
                {

                    @Override
                    public void onClick(DialogInterface dialog, int which) 
                    {
                        dialog.cancel();
                    }
                });
                mensaje.show();
        }
        }
        else Toast.makeText(this, "Escriba un medicamento", Toast.LENGTH_LONG).show();
        return returnString;
    }


    protected String Alternativos (String returnString)
    {

            String result = "";
                    //Se envian datos de consulta;
            ArrayList<NameValuePair> parametros = new ArrayList<NameValuePair>();
            parametros.add(new BasicNameValuePair("componente" , comp.trim()));     

            //Conectando a la base de datos
            try
            {
                HttpClient cliente = new DefaultHttpClient();
                HttpPost direccion = new HttpPost("http://10.0.2.2/medinfo/conexionalt.php");
                direccion.setEntity(new UrlEncodedFormEntity(parametros));
                HttpResponse respuesta = cliente.execute(direccion);
                HttpEntity entity = respuesta.getEntity();
                is = entity.getContent();
            }
            catch(Exception e)
            {
                Log.e("log_tag", "Error en la conexion a la base de datos"+e.toString());
                Toast.makeText(this, "Error al conectar a la base de datos", Toast.LENGTH_LONG).show();
            }

                //Transformar respuesta de la conexion en string
            try
            {

                BufferedReader reader = new BufferedReader (new InputStreamReader(is, "iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String linea = null;
                if ((linea = reader.readLine()) != null)
                {
                    sb.append(linea + "\n");
                }
                is.close();
                result = sb.toString();
            }
            catch(Exception e)
            {
                Log.e("log_tag", "Error al transformar datos. "+e.toString());
                Toast.makeText(this, "Error al transformar datos", Toast.LENGTH_LONG).show();
            }

            //Recibir datos en formato JSON

            try
            {
                JSONArray jArreglo = new JSONArray(result);
                for(int i=0; i<jArreglo.length(); i++)
                {
                    JSONObject json_datos = jArreglo.getJSONObject(i);
                    Log.i("log_tag", "nombre: "+json_datos.getString("Nombre")+
                            ", cantidad: "+json_datos.getInt("Stock"));
                        returnString += "\n\t" + jArreglo.getJSONObject(i); 
                }
            }
            catch (JSONException e)
            {
                Log.e("log_tag", "Error al recibir datos"+e.toString());
                Toast.makeText(this, "Error al mostrar datos", Toast.LENGTH_LONG).show();
            }
            return returnString;
    }
}

Спасибо за вашу помощь.

ОБНОВЛЕНИЕ 2: php код:

<?php

      mysql_connect("localhost","root","123456");
      mysql_select_db("medinfo_movil");
      $query=mysql_query("SELECT Nombre, Componentes, Stock FROM medicamento WHERE componentes like 
      '".$_REQUEST['componente']."%' and Stock > 0");

      while($row=mysql_fetch_assoc($query))

              $output[]=$row;

           print(json_encode($output));

           mysql_close();
?>

1 Ответ

0 голосов
/ 20 июля 2011

Я могу придумать способы проверить: Если JSONObject является пустым / пустым, тогда запрос возвратил 0 строк из вашей базы данных. Прежде всего попробуйте вывести результат с нулевой строкой из вашего запроса в коде php. Написать тест на основе этих результатов PHP. Также вы можете проверить в respuesta, содержит ли ответ результат вашего запроса.

http://publib.boulder.ibm.com/infocenter/dmndhelp/v6r1mx/index.jsp?topic=/com.ibm.wbit.610.help.config.doc/topics/rjsonnullunsempprops.html

Здесь больше информации о пустых и нулевых объектах JSON.

Edit:

[{"_id":"23","imenaobjekt":"Fire Fighting Depot","lat_":"48511471","long_":"28951451","category":"0",},{"_id":"22","imenaobjekt":"Police Station????????? ???????","lat_":"4882837","long_":"285576","category":"0",}]

Сочетание ключа и значения.

...