JSON PhP ANDROID NPE

时间:2015-11-08 12:09:37

标签: php android json

我在下一段代码上获得了NPE。 你能解释一下为什么它会在周期中得到和NPE:

for (int i = 0; i < jsonMainNode.length(); i++)?我正在尝试所有图书馆等,它没有帮助...

我看过这段视频并试图改编它https://www.youtube.com/watch?v=YfAqv0pIBBA似乎没问题,但NPE ......

    11-08 13:03:31.249 3361-3361/com.example.arnold.itsosgadda W/System.err: java.lang.NullPointerException
11-08 13:03:31.249 3361-3361/com.example.arnold.itsosgadda W/System.err:     at com.example.arnold.itsosgadda.CommunicationsActivity.ListDrwaer(CommunicationsActivity.java:99)
11-08 13:03:31.249 3361-3361/com.example.arnold.itsosgadda W/System.err:     at com.example.arnold.itsosgadda.CommunicationsActivity.access$100(CommunicationsActivity.java:30)
11-08 13:03:31.249 3361-3361/com.example.arnold.itsosgadda W/System.err:     at com.example.arnold.itsosgadda.CommunicationsActivity$JsonReadTask.onPostExecute(CommunicationsActivity.java:86)
11-08 13:03:31.249 3361-3361/com.example.arnold.itsosgadda W/System.err:     at com.example.arnold.itsosgadda.CommunicationsActivity$JsonReadTask.onPostExecute(CommunicationsActivity.java:54)
11-08 13:03:31.249 3361-3361/com.example.arnold.itsosgadda W/System.err:     at android.os.AsyncTask.finish(AsyncTask.java:632)
11-08 13:03:31.249 3361-3361/com.example.arnold.itsosgadda W/System.err:     at android.os.AsyncTask.access$600(AsyncTask.java:177)
11-08 13:03:31.249 3361-3361/com.example.arnold.itsosgadda W/System.err:     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
11-08 13:03:31.249 3361-3361/com.example.arnold.itsosgadda W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
11-08 13:03:31.249 3361-3361/com.example.arnold.itsosgadda W/System.err:     at android.os.Looper.loop(Looper.java:149)
11-08 13:03:31.249 3361-3361/com.example.arnold.itsosgadda W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5061)
11-08 13:03:31.249 3361-3361/com.example.arnold.itsosgadda W/System.err:     at java.lang.reflect.Method.invokeNative(Native Method)
11-08 13:03:31.249 3361-3361/com.example.arnold.itsosgadda W/System.err:     at java.lang.reflect.Method.invoke(Method.java:515)
11-08 13:03:31.249 3361-3361/com.example.arnold.itsosgadda W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
11-08 13:03:31.249 3361-3361/com.example.arnold.itsosgadda W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:603)
11-08 13:03:31.249 3361-3361/com.example.arnold.itsosgadda W/System.err:     at dalvik.system.NativeStart.main(Native Method)

Php Code

<?php
/**
 * Created by PhpStorm.
 * User: Arnol'd
 * Date: 07.11.2015
 * Time: 15:27
 */
$username = 'app';
$password = '4826159g';
$hostname = 'xxx.xxx.xxx.xxx:xxxx';
$database = 'app_db';

//$conn = new mysqli($hostname, $username, $password, $database);
$conn = @mysql_connect($hostname, $username, $password);
/*if ($conn->connect_error) {
    die("Connection failed:" . $conn->connect_error);
}*/
$sql = "select * from push";
@mysql_select_db($database);
/*$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo $data = $row['push_name'] . '  <a href="'.$row['link'].'">' . 'Download' . "<br>";

    }
}
else{
    echo "0 results";
}
$conn->close();*/
$r = @mysql_query($sql, $conn);
while ($row = @mysql_fetch_array($r)) {
    $flag[] = $row;
    if (empty($flag)) {
        die(json_encode($flag));
    }
}
print(json_encode($flag));
@mysql_close($conn);

的Android

package com.example.arnold.itsosgadda;

import android.app.ActionBar;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("deprecation")
public class CommunicationsActivity extends Activity {
    private String jsonResult;
    //private String url = "https://drive.google.com/open?id=0By57NyAMoNAhWDl2ckJvMy1qLUU";
    private String url = "http://xxx.xxx.xxx.xxx:xxxx/config.php";
    private ListView listView;
    List<Map<String, String>> communications = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.communications_news_layout);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        //connect();

        ActionBar actionBar = getActionBar();
        assert actionBar != null;
        actionBar.setIcon(R.mipmap.ic_launcher);
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ffeb3b")));

        accessWebService();
    }

    private class JsonReadTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(params[0]);
            try {
                HttpResponse response = httpClient.execute(httpPost);
                jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return null;
        }

        private StringBuilder inputStreamToString(InputStream inputStream) {
            String rLine = "";
            StringBuilder answer = new StringBuilder();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            try {
                while ((rLine = bufferedReader.readLine()) != null) {
                    answer.append(rLine);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                Toast.makeText(getApplicationContext(),
                        "Error..." + ex.toString(), Toast.LENGTH_LONG).show();
            }
            return answer;
        }

        @Override
        protected void onPostExecute(String s) {
            ListDrwaer();
        }


    }

    private void ListDrwaer() {
        try {
            JSONObject jsonResponse = new JSONObject(jsonResult.substring(jsonResult.indexOf("{"),
                    jsonResult.lastIndexOf("}")+1));
            JSONArray jsonMainNode = jsonResponse.optJSONArray("app_db");
            final ArrayList<HashMap<String, String>> hashMapArrayList = new ArrayList<>();
            HashMap<String,String> map;
            for (int i = 0; i < jsonMainNode.length(); i++) {
                JSONObject jsonObject = jsonMainNode.getJSONObject(i);
                map = new HashMap<>();
                map.put("ID", jsonObject.getString("ID"));
                map.put("push_name", jsonObject.getString("push_name"));
                map.put("link", jsonObject.getString("link"));
                hashMapArrayList.add(map);
                SimpleAdapter adapter = new SimpleAdapter(CommunicationsActivity.this,
                        hashMapArrayList,
                        R.layout.communications_news_layout,
                        new String[]{"ID","push_name","link"},
                        new int[]{R.id.newsID,R.id.newsName,R.id.nameLink});
                listView = (ListView) findViewById(R.id.listView);
                listView.setAdapter(adapter);

            }
        } catch (Exception ex) {
            ex.printStackTrace();
            Toast.makeText(getApplicationContext(),
                    "Error..." + ex.toString(), Toast.LENGTH_LONG).show();
        }
    }

    public void accessWebService() {
        JsonReadTask task = new JsonReadTask();
        task.execute(new String[]{url});
    }
}

0 个答案:

没有答案