douzhuolong9886 2014-12-22 17:16
浏览 148

通过PHP将信息从MySQL传递到Android - 转换结果时出错java.lang.NullPointerException:lock == null

I am new to Android and I am trying to make am simple APP the access a server and read a table in a database. I used this example http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/ and tried to make some adaptations.

There has been many errors that I was able to solve searching here, but on this case I haven´t been luck so far.

As suggest, I did some debbuging and the app stops working when to line 108

    try{
        //Verificando a TAG Sucesso
        int sucess = json.getInt(TAG_SUCESSO);

For the varibles, just befor that, json appears as null.

As it seens I am having trouble to get the response from my PHP code (it shows the right array and executed) to the app.

Here is the Logcat error

12-22 11:50:35.609    1273-1293/br.com.agenciaeisberg.qm E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null
12-22 11:50:35.859    1273-1293/br.com.agenciaeisberg.qm E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
12-22 11:50:35.859    1273-1293/br.com.agenciaeisberg.qm W/dalvikvm﹕ threadid=12: thread exiting with uncaught exception (group=0xb2a24ba8)
12-22 11:50:36.799    1273-1293/br.com.agenciaeisberg.qm E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
    Process: br.com.agenciaeisberg.qm, PID: 1273
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
     Caused by: java.lang.NullPointerException
            at br.com.agenciaeisberg.qm.ListagemHospitaisActivity$LoadListagemHospitais.doInBackground(ListagemHospitaisActivity.java:104)
            at br.com.agenciaeisberg.qm.ListagemHospitaisActivity$LoadListagemHospitais.doInBackground(ListagemHospitaisActivity.java:76)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
12-22 11:50:38.039    1273-1273/br.com.agenciaeisberg.qm W/EGL_emulation﹕ eglSurfaceAttrib not implemented
12-22 11:50:39.259    1273-1273/br.com.agenciaeisberg.qm E/WindowManager﹕ android.view.WindowLeaked: Activity br.com.agenciaeisberg.qm.ListagemHospitaisActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b2ce6d30 V.E..... R......D 0,0-320,96} that was originally added here
            at android.view.ViewRootImpl.<init>(ViewRootImpl.java:348)
            at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
            at android.app.Dialog.show(Dialog.java:286)
            at br.com.agenciaeisberg.qm.ListagemHospitaisActivity$LoadListagemHospitais.onPreExecute(ListagemHospitaisActivity.java:88)
            at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
            at android.os.AsyncTask.execute(AsyncTask.java:535)
            at br.com.agenciaeisberg.qm.ListagemHospitaisActivity.onCreate(ListagemHospitaisActivity.java:59)
            at android.app.Activity.performCreate(Activity.java:5231)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)

Here is the Activity

package br.com.agenciaeisberg.qm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class ListagemHospitaisActivity extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> ListaHospitais;

    //url para lista hospitais
    private static String url_lista_hospitais = "http://127.0.0.1/QM/lista_hospitais.php";

    //JSON Node names
    private static final String TAG_HOSPITAIS = "hospitais";
    private static final String TAG_PID = "pid";
    private static final String TAG_NOME = "nome";
    private static final String TAG_SUCESSO = "sucesso";
    //private static final String TAG_LOTACAO = "lotacao";
    //private static final String TAG_DATA_LOTACAO = "data_lotacao";

    //hospitais JSONARRAY
    JSONArray hospitais = null;

    @Override
    public void onCreate (Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lista_hospitais);

        //Hashmap for ListView
        ListaHospitais = new ArrayList<HashMap<String,String>>();

        // Carregando hospitais no backgroung
        new LoadListagemHospitais().execute();

        // Get ListView
        //ListView lv = getListView();

        //Selecionando um Hospital
        //Executa atividade Hospital
        //Criar código depois -> pesquisar linhas abaixo
        // on seleting single product
        // launching Edit Product Screen

    }

    /**
     * Background Async Task para carregar todos os hospitais através de um HTTP Request
     */

    class LoadListagemHospitais extends AsyncTask <String, String, String>{
        /**
         * Before starting background thread Show Progress Dialog
         * */

         @Override
        protected void onPreExecute(){
            super.onPreExecute();
            pDialog = new ProgressDialog(ListagemHospitaisActivity.this);
            pDialog.setMessage("Aguarde, carregando Hospitais");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * Buscando os hospitais do URL
         * */

        protected String doInBackground (String... args) {
            //Criação dos parâmetros
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            // Buscando o string JSON do URL
            JSONObject json = jParser.makeHttpRequest(url_lista_hospitais,"GET", params);

            // Check your log cat for JSON reponse

            Log.d("Listagem Hospitais: ", json.toString());

            try{
                //Verificando a TAG Sucesso
                int sucess = json.getInt(TAG_SUCESSO);

                if (sucess == 1){
                    //existe hospital cadastrado

                    // Buscando Array dos hospitais
                    hospitais = json.getJSONArray(TAG_HOSPITAIS);

                    //loop por todos os Hospitais

                    for (int i = 0; i < hospitais.length(); i++) {
                        JSONObject c = hospitais.getJSONObject(i);

                        // Armazenando as variáveis
                        String id = c.getString(TAG_PID);
                        String nome = c.getString(TAG_NOME);

                        // creando novo HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adicionando cada child node ao HashMap . key => value
                        map.put(TAG_PID, id);
                        map.put(TAG_NOME, nome);

                        // adicionando HashList à ArrayList
                        ListaHospitais.add(map);
                    }

                }else{

                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(),
                            MainActivity.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            }catch (JSONException e) {
                e.printStackTrace();
            }
             return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/

        protected void onPostExecute(String file_url) {
            // Dismiss a caixa de dialogo depois de buscar todos os items
            pDialog.dismiss();

            // atualizando UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            ListagemHospitaisActivity.this, ListaHospitais,
                            R.layout.lista_hospitais, new String[] { TAG_PID,
                            TAG_NOME},
                            new int[] { R.id.pid, R.id.nome });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }


    }

}

Here is the JSONParser Class

package br.com.agenciaeisberg.qm;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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 android.util.Log;


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<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "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 == "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 = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "
");
            }
            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;

    }
}

Here is the php Code

<?php

/*
 * O código a seguir lista todos os hospitais
 */


//array para Resposta JSON
$response = array();

require_once 'geral.inc.php';

// connecting to db

$con = mysqli_connect($hostname, $username, $senha, $banco);

// Listar todos os Hospitais
$result = mysqli_query($con, 'SELECT * FROM hospitais');

$response['hospitais'] = array();

while ($row = mysqli_fetch_array($result)){
    //array temporário
    $hospital = array ();
    $hospital['pid'] = $row['PID'];
    $hospital['nome'] = $row['NomeHospital'];
    $hospital['lotacao'] = $row['ultima_lotacao'];
    $hospital['data_lotacao'] = $row['d_h_ultima_lotacao'];

    // Exibe o resultado um a um da array
    array_push($response["hospitais"], $hospital);
}

$response["successo"] = 1;

// echoing JSON response
    echo json_encode($response);

?>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 电脑桌面设定一个区域禁止鼠标操作
    • ¥15 求NPF226060磁芯的详细资料
    • ¥15 使用R语言marginaleffects包进行边际效应图绘制
    • ¥20 usb设备兼容性问题
    • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
    • ¥15 安装svn网络有问题怎么办
    • ¥15 Python爬取指定微博话题下的内容,保存为txt
    • ¥15 vue2登录调用后端接口如何实现
    • ¥65 永磁型步进电机PID算法
    • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?