Android无法连接到远程数据库

时间:2014-07-15 06:47:37

标签: android json

我正在观看关于Android与远程数据库的连接的教程,但不知何故它崩溃了,我不明白为什么。我包括代码请看看,告诉我是否可以解决它。

package com.example.mysqltest;

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

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

import android.app.Activity;
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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Login extends Activity implements OnClickListener {

    private EditText user, pass;
    private Button mSubmit, mRegister;
    TextView tv;

    // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();

    // php login script location:

    // localhost :
    // testing on your device
    // put your local ip instead, on windows, run CMD > ipconfig
    // or in mac's terminal type ifconfig and look for the ip under en0 or en1
    // private static final String LOGIN_URL =
    // "http://xxx.xxx.x.x:1234/webservice/login.php";

    // testing on Emulator:
    private static final String LOGIN_URL = "http://localhost:8080/webservice/login.php";

    // testing from a real server:
    // private static final String LOGIN_URL =
    // "http://www.mybringback.com/webservice/login.php";

    // JSON element ids from repsonse of php script:
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        tv = (TextView) findViewById(R.id.textView2);

        // setup input fields
        user = (EditText) findViewById(R.id.username);
        pass = (EditText) findViewById(R.id.password);

        // setup buttons
        mSubmit = (Button) findViewById(R.id.login);
        mRegister = (Button) findViewById(R.id.register);

        // register listeners
        mSubmit.setOnClickListener(this);
        mRegister.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.login:
            new AttemptLogin().execute();
            break;
        case R.id.register:
            Intent i = new Intent(this, Register.class);
            startActivity(i);
            break;

        default:
            break;
        }
    }

    class AttemptLogin extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Login.this);
            pDialog.setMessage("Attempting login...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
            // Check for success tag
            int success;
            String username = user.getText().toString();
            String password = pass.getText().toString();
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", username));
                params.add(new BasicNameValuePair("password", password));

                Log.d("request!", "starting");
                // getting product details by making HTTP request
                JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
                        params);

                // check your log for json response
                Log.d("Login attempt", json.toString());

                // json success tag
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    tv.setText("Success");

//                  Log.d("Login Successful!", json.toString());
//                  // save user data
//                  SharedPreferences sp = PreferenceManager
//                          .getDefaultSharedPreferences(Login.this);
//                  Editor edit = sp.edit();
//                  edit.putString("username", username);
//                  edit.commit();
//                  
//                  Intent i = new Intent(Login.this, ReadComments.class);
//                  finish();
//                  startActivity(i);
//                  return json.getString(TAG_MESSAGE);
                } else {
//                  Log.d("Login Failure!", json.getString(TAG_MESSAGE));
//                  return json.getString(TAG_MESSAGE);
                    tv.setText("Failed");

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;

        }

        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();
            if (file_url != null) {
                Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
            }

        }

    }

}

如果您需要查看LogCat,日志信息就在这里

07-16 05:05:48.274: E/Buffer Error(313): Error converting result java.lang.NullPointerException
07-16 05:05:48.274: E/JSON Parser(313): Error parsing data org.json.JSONException: End of input at character 0 of 
07-16 05:05:48.274: W/dalvikvm(313): threadid=9: thread exiting with uncaught exception (group=0x40015560)
07-16 05:05:48.284: E/AndroidRuntime(313): FATAL EXCEPTION: AsyncTask #1
07-16 05:05:48.284: E/AndroidRuntime(313): java.lang.RuntimeException: An error occured while executing doInBackground()
07-16 05:05:48.284: E/AndroidRuntime(313):  at android.os.AsyncTask$3.done(AsyncTask.java:200)
07-16 05:05:48.284: E/AndroidRuntime(313):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
07-16 05:05:48.284: E/AndroidRuntime(313):  at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
07-16 05:05:48.284: E/AndroidRuntime(313):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
07-16 05:05:48.284: E/AndroidRuntime(313):  at java.util.concurrent.FutureTask.run(FutureTask.java:138)
07-16 05:05:48.284: E/AndroidRuntime(313):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
07-16 05:05:48.284: E/AndroidRuntime(313):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
07-16 05:05:48.284: E/AndroidRuntime(313):  at java.lang.Thread.run(Thread.java:1019)
07-16 05:05:48.284: E/AndroidRuntime(313): Caused by: java.lang.NullPointerException
07-16 05:05:48.284: E/AndroidRuntime(313):  at com.example.mysqltest.Login$AttemptLogin.doInBackground(Login.java:125)
07-16 05:05:48.284: E/AndroidRuntime(313):  at com.example.mysqltest.Login$AttemptLogin.doInBackground(Login.java:1)
07-16 05:05:48.284: E/AndroidRuntime(313):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
07-16 05:05:48.284: E/AndroidRuntime(313):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
07-16 05:05:48.284: E/AndroidRuntime(313):  ... 4 more
07-16 05:05:48.294: W/ActivityManager(61):   Force finishing activity com.example.mysqltest/.Login
07-16 05:05:48.434: W/IInputConnectionWrapper(313): showStatusIcon on inactive InputConnection
07-16 05:05:48.964: E/WindowManager(313): Activity com.example.mysqltest.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40564ea8 that was originally added here
07-16 05:05:48.964: E/WindowManager(313): android.view.WindowLeaked: Activity com.example.mysqltest.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40564ea8 that was originally added here
07-16 05:05:48.964: E/WindowManager(313):   at android.view.ViewRoot.<init>(ViewRoot.java:258)
07-16 05:05:48.964: E/WindowManager(313):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
07-16 05:05:48.964: E/WindowManager(313):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
07-16 05:05:48.964: E/WindowManager(313):   at android.view.Window$LocalWindowManager.addView(Window.java:424)
07-16 05:05:48.964: E/WindowManager(313):   at android.app.Dialog.show(Dialog.java:241)
07-16 05:05:48.964: E/WindowManager(313):   at com.example.mysqltest.Login$AttemptLogin.onPreExecute(Login.java:103)
07-16 05:05:48.964: E/WindowManager(313):   at android.os.AsyncTask.execute(AsyncTask.java:391)
07-16 05:05:48.964: E/WindowManager(313):   at com.example.mysqltest.Login.onClick(Login.java:82)
07-16 05:05:48.964: E/WindowManager(313):   at android.view.View.performClick(View.java:2485)
07-16 05:05:48.964: E/WindowManager(313):   at android.view.View$PerformClick.run(View.java:9080)
07-16 05:05:48.964: E/WindowManager(313):   at android.os.Handler.handleCallback(Handler.java:587)
07-16 05:05:48.964: E/WindowManager(313):   at android.os.Handler.dispatchMessage(Handler.java:92)
07-16 05:05:48.964: E/WindowManager(313):   at android.os.Looper.loop(Looper.java:123)
07-16 05:05:48.964: E/WindowManager(313):   at android.app.ActivityThread.main(ActivityThread.java:3683)
07-16 05:05:48.964: E/WindowManager(313):   at java.lang.reflect.Method.invokeNative(Native Method)
07-16 05:05:48.964: E/WindowManager(313):   at java.lang.reflect.Method.invoke(Method.java:507)
07-16 05:05:48.964: E/WindowManager(313):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-16 05:05:48.964: E/WindowManager(313):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-16 05:05:48.964: E/WindowManager(313):   at dalvik.system.NativeStart.main(Native Method)
07-16 05:05:54.016: D/dalvikvm(313): GC_EXPLICIT freed 118K, 53% free 2662K/5639K, external 551K/961K, paused 105ms
07-16 05:05:54.376: D/SntpClient(61): request time failed: java.net.SocketException: Address family not supported by protocol
07-16 05:05:56.704: I/Process(313): Sending signal. PID: 313 SIG: 9
07-16 05:05:56.754: W/InputManagerService(61): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@407536a8
07-16 05:05:56.854: I/ActivityManager(61): Process com.example.mysqltest (pid 313) has died.
07-16 05:08:00.014: I/dalvikvm(61): Jit: resizing JitTable from 1024 to 2048
07-16 05:10:00.135: D/dalvikvm(129): GC_CONCURRENT freed 223K, 51% free 2813K/5703K, external 544K/1021K, paused 9ms+4ms
07-16 05:10:54.386: D/SntpClient(61): request time failed: java.net.SocketException: Address family not supported by protocol
07-16 05:11:00.125: D/dalvikvm(61): GC_CONCURRENT freed 673K, 44% free 4282K/7623K, external 1226K/2327K, paused 5ms+6ms
07-16 05:15:54.396: D/SntpClient(61): request time failed: java.net.SocketException: Address family not supported by protocol
07-16 05:20:54.404: D/SntpClient(61): request time failed: java.net.SocketException: Address family not supported by protocol.

根据LogCat的主要问题在于doInBackground方法。

以下是完整源代码的下载链接。 http://dchabmztumu0g.cloudfront.net/wp-content/uploads/2013/05/remote-sql-android-6.zip 感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

我认为logcat告诉你这是什么问题

Error converting result java.lang.NullPointerException

以及

Error parsing data org.json.JSONException: End of input at character 0 of

你正在从后台线程操纵UI,所以它引发了一个错误,另一个是你从doinbackground返回null然后使用该null作为file_url

并且JSONException告诉您字符串结果为空

答案 1 :(得分:0)

通过执行以下检查确保您的json不为空 -

@Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        // Check for success tag
        int success;
        String username = user.getText().toString();
        String password = pass.getText().toString();
        try {
            // Building Parameters
            List<NameValuePair> params = new 
            ArrayList<NameValuePair>();
            params.add(new 
            BasicNameValuePair("username", username));
            params.add(new 
            BasicNameValuePair("password", password));

            Log.d("request!", "starting");
            // getting product details by making HTTP request
            JSONObject json = jsonParser.
            makeHttpRequest(LOGIN_URL, "POST",
            params);

            if(json != null && !json.isNull(TAG_SUCCESS)){

    // check your log for json response
    Log.d("Login attempt", json.toString());

    // json success tag
    success = json.getInt(TAG_SUCCESS);
    }
    else
    {
      Log.d("Login attempt", "Null Json");

      success = 0;
    }
      return success + "";
    }


protected void onPostExecute(String success) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();

        if(success.equals("1"))
          tv.setText("Success");
        else
          tv.setText("Failed");
    }

}

另请注意,您无法从后台线程更新UI的内容。您可以将结果传递给可以更新UI的onPostExecute,如上面的代码中所述。