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

时间:2015-02-05 06:50:40

标签: 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();
//}

?>

logcat的

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)

2 个答案:

答案 0 :(得分:0)

尝试在JsonParser的第56行使用它

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

再次检查清单中的互联网权限。

我是linux newby,所以不确定这是否是确定的答案,但是查看/ var / www / html的权限告诉我,只有用户root具有Read Write Execute权限。因为我只是作为标准用户使用浏览器而没有访问权限,所以我认为“其他”需要一些权限,所以我这样做了:

sudo chmod 755 html -R

现在我可以在浏览器中访问localhost。

我发现此视频“Linux中的用户,组和权限”非常有用:

http://youtu.be/zRw0SKaXSfI

答案 1 :(得分:0)

如果我正确解释堆栈跟踪,则会在此行的InputStreamReader构造函数中抛出异常:

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

唯一可信的解释是inputStreamnull

怎么样?之前的代码应该为您获取输入流!

但请考虑如果HTTP请求失败并抛出异常会发生什么。如果发生这种情况,您将无法访问将inputStream设置为内容流的语句,因此它仍然为空。

提示:这里真正的错误是你抓住了异常,打印了一个堆栈跟踪(某处)......然后继续好像一切都还好!