dqteh7347 2016-11-10 19:17 采纳率: 100%
浏览 51

从php脚本解析Json以在android应用程序中显示它时出错

My goal is to get the data of mssql database, this part is already done and working, and then grab that json and display it in a android application.

The data gets to the app because its displayed on the logcat and in one Toast message, however it does not complete the process.

The json is very long, and when i try to see the error on logcat, i cant because it doesnt show all the info, here is what i meant:

begin logcat end logcat

There is a lot more data but i guess it doesnt all fit on the console..

The json im working with: http://ploran.gear.host/scriptobras6.php

PHP:

<?php
error_reporting(1);
ini_set('mssql.charset', 'UTF-8');

$serverName = "--";

/* Get UID and PWD from application-specific files.  */
$connectionInfo = array( "Database"=>"programaplo", "UID"=>"--", "PWD"=>"--","CharacterSet"=>"UTF-8");
$conn = sqlsrv_connect($serverName, $connectionInfo);

// if( $conn ) {
//      echo "Connection established.<br />";
// }else{
//      echo "Connection could not be established.<br />";
//      die( print_r( sqlsrv_errors(), true));
// }

$tsql = "SELECT * FROM Obras";
$stmt = sqlsrv_query($conn, $tsql);

// if( $stmt === false ) {
//      echo "Error in executing query.</br>";
//      die( print_r( sqlsrv_errors(), true));
// }

// echo "Query: sucesso 
";

$json = array();

while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
        $json[] = $row;
     }

header('Content-type: application/json; Charset=UTF-8');
echo json_encode($json);

sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnectiokn first

exit();
?>

MainActivity.java

  public class MainActivity extends Activity {

    private String TAG = MainActivity.class.getSimpleName();
    private ProgressDialog pDialog;
    private ListView list;

    private static String url = "http://ploran.gear.host/scriptobras6.php";

    ArrayList<HashMap<String, String>> obrasList;

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

        obrasList = new ArrayList<>();

        list = (ListView)findViewById(R.id.list1);

        new GetObras().execute();
    }

    private class GetObras extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray obras = jsonObj.getJSONArray("obras");

                    // looping through All 
                    for (int i = 0; i < obras.length(); i++) {
                        JSONObject c = obras.getJSONObject(i);

                        String id = c.getString("Id");
                        String nomeObra = c.getString("NomeObra");
                        String idCliente = c.getString("idCliente");
                        String DataLevantamento = c.getString("DataPLevantamento");
                        String DataRealizacao = c.getString("DataRLevantamento");
                        String Estado = c.getString("Estado");
                        String DataMateriais = c.getString("DataRMateriais");
                        String DataInicioObra = c.getString("DataInicioObra");
                        String DataConclusao = c.getString("DataConclusao");
                        String DataVestoria = c.getString("DataVestoria");
                        String Obs = c.getString("Obs");
                        String Prompor = c.getString("Prompor");
                        String Levantpor = c.getString("Levantpor");
                        String executpor = c.getString("executpor");

                        // tmp hash map for single contact
                        HashMap<String, String> obra = new HashMap<>();

                        // adding each child node to HashMap key => value
                        obra.put("Id", id);
                        obra.put("nomeObra", nomeObra);
                        obra.put("idCliente", idCliente);
                        obra.put("DataLevantamento", DataLevantamento);
                        obra.put("DataRealizacao", DataRealizacao);
                        obra.put("Estado", Estado);
                        obra.put("DataMateriais", DataMateriais);
                        obra.put("DataIncioObra", DataInicioObra);
                        obra.put("DataConclusao", DataConclusao);
                        obra.put("DataVestoria", DataVestoria);
                        obra.put("Obs", Obs);
                        obra.put("Prompor", Prompor);
                        obra.put("Levantpor", Levantpor);
                        obra.put("executpor", executpor);

                        // adding contact to contact list
                        obrasList.add(obra);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    Logger.debugEntire("teste", e);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();

                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, obrasList,
                    R.layout.list_item, new String[]{"nomeObra", "idCliente",
                    "Estado"}, new int[]{R.id.name,
                    R.id.email, R.id.mobile});

            list.setAdapter(adapter);
        }

    }
}

HttpHandler.java

public class HttpHandler {

private static final String TAG = HttpHandler.class.getSimpleName();

public HttpHandler() {
}

public String makeServiceCall(String reqUrl) {
    String response = null;
    try {
        URL url = new URL(reqUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        // read the response
        InputStream in = new BufferedInputStream(conn.getInputStream());
        response = convertStreamToString(in);
    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(TAG, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
    return response;
}

private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('
');
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}
}

I am a bit lost here, please take a look at the php "while" from the solutions i saw on web its a bit different but it was the only way i found to get the json, that can be the issue, or not..

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 基于卷积神经网络的声纹识别
    • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
    • ¥100 为什么这个恒流源电路不能恒流?
    • ¥15 有偿求跨组件数据流路径图
    • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
    • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
    • ¥15 CSAPPattacklab
    • ¥15 一直显示正在等待HID—ISP
    • ¥15 Python turtle 画图
    • ¥15 stm32开发clion时遇到的编译问题