java - 无法从远程数据库获取数据

标签 java android mysql

我正在开发一个简单的应用程序,我需要从本地主机sql数据库获取数据,当我在浏览器上测试时我能够获取JSON,但是我在检查android时遇到空指针异常,我已经交叉检查了IP地址,甚至尝试了异步任务,甚至在manifest.xml中声明了互联网权限,我调试了应用程序,但仍然无法找出错误的原因。

MainActivity.java

package library.danaraddi.com.myapplication;


import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

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


public class MainActivity extends ActionBarActivity {
    // views import
    Button PostButton, GetButton;
    TextView UsernameTextView, PasswordTextView;
    EditText UsernameEditText, PasswordEditText;
   // 192.168.1.210

    // static fields
    private static String URL = "http://192.168.1.210/cpsscripts/total_items.php";
    private static String GET_TOTAL = "gettotal";


    // objetcs
    JSONParser jsonParser ;
    List<NameValuePair> params;

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

        // Views Import
        PostButton = (Button) findViewById(R.id.post_button);
        GetButton = (Button) findViewById(R.id.get_button);
        UsernameEditText = (EditText) findViewById(R.id.username_edittext);
        PasswordEditText = (EditText) findViewById(R.id.password_edittext);
        UsernameTextView = (TextView) findViewById(R.id.username_textView);
        PasswordTextView = (TextView) findViewById(R.id.password_textView);


        // Objects
        jsonParser = new JSONParser();
        params = new ArrayList<NameValuePair>();


        params.add(new BasicNameValuePair("", ""));


        PostButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    JSONObject json = jsonParser.getJSONFromURL(URL, params);
                    String res = json.getString("gettotal");
                    UsernameTextView.setText(res);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });



    }


}

JSONParser.java

package library.danaraddi.com.myapplication;

import android.util.Log;

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.HttpPost;
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;

/**
 * Created by VINAY on 2/4/2015.
 */
public class JSONParser {
   InputStream inputStream = null;
     JSONObject jsonObject = null;
     String output = "";

    public JSONParser() {

    }

    public JSONObject getJSONFromURL(String URL, List<NameValuePair> valuePairs) {

        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(URL);
            httpPost.setEntity(new UrlEncodedFormEntity(valuePairs));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            inputStream = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"),8);

            StringBuilder stringBuilder = new StringBuilder();
            String line = null;
            while ((line = bufferedReader.readLine())!= null){
                stringBuilder.append(line + "\n");
            }

            inputStream.close();
            output = stringBuilder.toString();

            Log.i("VINAY",output);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            jsonObject = new JSONObject(output);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return jsonObject;
    }
}

total_items.php

<?php

    $response = array();

    // import db connection variables
    require_once __DIR__ . '/db_config.php';
    // connect DB
    $db= new mysqli(DB_SERVER, DB_USER, DB_PASSWORD,DB_DATABASE);

    //if(!empty($_POST['total'])){
    // Query
    $totalquery ="SELECT * FROM `questions` ORDER BY `id` DESC LIMIT 1";

    // connecting to mysql
    if ($db->query($totalquery) == TRUE) {
        $rows = $db->query($totalquery);
        // get array
        $totalrows = $rows->fetch_assoc();
        // repond the total amount
        $response["gettotal"] = $totalrows["id"];
        // show response
        print(json_encode($response));
    } else {
        echo "Error: " . $insertQuery . "<br>" . $db->error;
    }
    $db->close();
//}

?>

日志猫

02-05 06:01:24.248      400-400/library.danaraddi.com.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at java.io.Reader.<init>(Reader.java:65)
            at java.io.InputStreamReader.<init>(InputStreamReader.java:79)
            at library.danaraddi.com.myapplication.JSONParser.getJSONFromURL(JSONParser.java:56)
            at library.danaraddi.com.myapplication.MainActivity$1.onClick(MainActivity.java:64)
            at android.view.View.performClick(View.java:2485)
            at android.view.View$PerformClick.run(View.java:9080)
            at android.os.Handler.handleCallback(Handler.java:587)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:130)
            at android.app.ActivityThread.main(ActivityThread.java:3683)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:507)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
            at dalvik.system.NativeStart.main(Native Method)

最佳答案

尝试在 JsonParser 的第 56 行使用它

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));

并再次检查 list 中的互联网权限。

我是 Linux 新手,所以不确定这是否是明确的答案,但是查看/var/www/html 的权限表明只有用户 root 具有读写执行权限。由于我只是作为标准用户使用浏览器并且没有访问权限,因此我认为“其他”需要一些权限,所以我这样做了:

sudo chmod 755 html -R

现在我可以在浏览器中访问本地主机了。

我发现这个有关“Linux 中的用户、组和权限”的视频非常有帮助:

http://youtu.be/zRw0SKaXSfI

关于java - 无法从远程数据库获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28337815/

相关文章:

java - TreeSet 或 TreeMap 自动排序,当底层对象的字段值改变时

java - Eclipse 从文件中读取标准输入(System.in)

java - 解析数据 org.json.JSONException 类型 java.lang.String 的值 <html> 时出错

javascript - 网站上的Python连接手机连接电脑

android - 如何使用 NetworkStatusManager 或 TrafficStat 在 Android 中获取网络共享和移动热点数据使用情况

java - 如何打印中心数字金字塔?

android - 不幸的是应用程序已在 Android 模拟器上停止

mysql - Laravel 多态关系中的 FK

mysql查询以获取特定日期之间的记录

php - 根据下拉选择显示特定的 MySQL 行