无法让我的Android应用程序连接到服务器

时间:2013-01-29 14:18:08

标签: android mysql database json mobile-application

好的,首先,Android开发对我来说很新,所以请光临我。

我想做什么:

我已经在我的应用程序上设置了一个登录屏幕(现在就是这样)。它有一个用户名和密码字段以及一个登录按钮。 当用户输入他们的详细信息并按下登录时,它会检查用户是否存在于我的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

}

对不起,如果这超出了你的需要,但正如我所说,这对我来说是新的,所以我不知道你需要看到什么。

非常感谢任何帮助。如果您需要其他页面中的代码,请告诉我,在任何人询问之前,是的,互联网权限已添加到清单中。

提前致谢。

1 个答案:

答案 0 :(得分:1)

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