【问题标题】:Can't get my Android Application to connect to server无法让我的 Android 应用程序连接到服务器
【发布时间】:2013-01-29 14:18:07
【问题描述】:

我已经在我的应用程序上设置了一个登录屏幕(目前仅此而已)。它有一个用户名和密码字段以及一个登录按钮。 当用户输入他们的详细信息并按下登录时,它会检查用户是否存在于我的 MySQL 数据库中并且详细信息是否正确,然后显示一条 Toast 消息,如果是,则显示“成功”,如果不存在或存在则显示“无效...”是与服务器的错误连接,然后显示“连接错误”。

我不断收到连接错误消息,但我不知道为什么。 我已经在 php 文件中测试了数据库连接,它工作正常,对数据库的查询也是如此,所以我假设问题出在我的 android 代码中。

这是给你的整个代码块(隐藏我的域)

   package uk.co.mypackage.mypackagename;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{
    EditText etUser, etPass;
    Button bLogin;

//Create String variables that have input assigned to them
String username, password;

//Create an HTTPClient as form container
HttpClient httpClient;

//User HTTP Post method
HttpPost httppost;

//Create an array list for the input data to be sent
ArrayList<NameValuePair> nameValuePairs;

//Create an HTTP Response and HTTP Entity
HttpResponse response;
HttpEntity entity;



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

    initialise();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;

}

private void initialise() {
    etUser = (EditText) findViewById(R.id.etUser);
    etPass = (EditText) findViewById(R.id.etPass);
    bLogin = (Button) findViewById(R.id.bSubmit);
    //Now to set an OnClickListener
    bLogin.setOnClickListener(this);
}

@Override
public void onClick(View v) {

    //Create New default HTTPClient
    httpClient = new DefaultHttpClient();

    //Create new HTTP POST with URL to PHP file as parameter
    httppost = new HttpPost("http://www.mydomain.co.uk/android_api/index.php"); 

    //Assign input text to string
    username = etUser.getText().toString();
    password = etPass.getText().toString();

    try{
        //Create New Array List
        nameValuePairs = new ArrayList<NameValuePair>();

        //Place them in an array list
        nameValuePairs.add(new BasicNameValuePair("username", username));
        nameValuePairs.add(new BasicNameValuePair("password", password));

        //Add array list to HTTP POST
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        //assign executed form container to response
        response = httpClient.execute(httppost);

        //check status code, need to check status code 200
        if(response.getStatusLine().getStatusCode()== 200){

            //assign response entity to http entity
            entity = response.getEntity();

            //check if entity is not null
            if(entity != null){

                //Create new input stream with received data assigned
                InputStream instream = entity.getContent();

                //Create new JSON object. assign converted data as parameter
                JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));

                //assign JSON responses to local string
                String retUser = jsonResponse.getString("user");//MySQL table field
                String retPass = jsonResponse.getString("pass");//MySQL table field

                //Validate login
                if(username.equals(retUser)&& password.equals(retPass)){

                    //Create a new shared preference by getting the preference
                    SharedPreferences sp = getSharedPreferences("logindetails", 0);

                    //Edit the shared preferences
                    SharedPreferences.Editor spedit = sp.edit();

                    //Put the login details as string
                    spedit.putString("user", username);
                    spedit.putString("pass", password);//May not need to store password

                    //close the editor
                    spedit.commit();

                    //Display a Toast saying login was a success
                    Toast.makeText(getBaseContext(), "SUCCESS!", Toast.LENGTH_SHORT).show();


                } else {
                    //Display a Toast status saying it failed
                    Toast.makeText(getBaseContext(), "Invalid Login Details", Toast.LENGTH_SHORT).show();
                }

        }

    } 
    }   catch(Exception e){
        e.printStackTrace();
        //Display Toast when there is a connection error
        Toast.makeText(getBaseContext(), "Connection Error", Toast.LENGTH_SHORT).show();
    }


} //End OnClick()

 private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }//End ConvertStreamToString

}

【问题讨论】:

  • 你真的应该发布你得到的错误。
  • @StefandeBruijn 我没有。就是这样。我的错误日志是空的。
  • 您可以访问页面mydomain.co.uk/android_api/index.php 吗? php.ini 设置是否设置为显示所有消息?
  • 如果您的应用进入 catch(Exception e){} 打印 toast,那么也会出现错误。调试/打印并复制/粘贴异常 e 的值
  • 这段代码:catch(Exception e){ e.printStackTrace();打印错误发生了什么。它将在名为 Logcat 的视图中显示为红色文本:错误级别。这会说类似 java.lang.NullpointerException.... 很多文本,并有一个以 'Caused by' 结尾的分句,只需复制粘贴整个红色文本,从你有什么样的错误开始。

标签: android mysql database json mobile-application


【解决方案1】:

在发送带有用户名和密码的发布请求时,会发送一条警告消息未定义变量:num。包含非json元素的响应导致json对象解析出错,返回null对象。

【讨论】:

  • 非常感谢奥马尔。感谢您的宝贵时间。
猜你喜欢
  • 2021-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-21
  • 1970-01-01
  • 2016-08-09
  • 1970-01-01
相关资源
最近更新 更多