无法从数据库中检索用户登录详细信息到我的Android应用程序

时间:2014-02-17 12:03:16

标签: android mysql

我需要使用PhpMyAdmin将我的Android应用程序链接到MySQL数据库。

我已经开始使用“登录”页面,我的代码中没有错误但我不确定为什么我无法获得成功的登录消息,尽管我的数据库中有相同的登录详细信息。

我已经从其他网站引用了这组代码。有人可以帮帮我吗?提前致谢!以下是我的参考代码..

login.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/diagmonds"
    android:orientation="vertical" >

    <TableLayout
        android:id="@+id/tableLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="150dp"
        android:layout_marginLeft="20dp"        
        android:layout_marginRight="20dp"
        android:stretchColumns="1" >

        <!-- Row 1 -->
        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingBottom="20dp"
                android:gravity="right"
                android:text="Please Log In: "
                android:textColor="#FF9900"
                android:textStyle="bold"
                android:layout_gravity="center_vertical|center_horizontal" >
            </TextView>
        </TableRow>

        <!-- Row 2 -->
        <TableRow
            android:id="@+id/tableRow2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="right"
                android:text="User Type: "
                android:textColor="#FF9900" >
            </TextView>

            <EditText
                android:id="@+id/etUserName"
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:inputType="text"
                android:gravity="center"
                android:hint="staff / admin"
                android:textColor="#ffff00"
                android:textSize="18sp" >
            </EditText>
        </TableRow>

        <!-- Row 3 -->
        <TableRow
            android:id="@+id/tableRow3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/textView3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="right"
                android:text="Password: "
                android:textColor="#FF9900" >
            </TextView>

            <EditText
                android:id="@+id/etPassword"
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:inputType="numberPassword"
                android:gravity="center"
                android:hint="enter password"
                android:textColor="#ffff00"
                android:textSize="18sp" >
            </EditText>
        </TableRow>
    </TableLayout>

    <Button
        android:id="@+id/loginBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:layout_marginLeft="200dp"
        android:background="#000000"
        android:padding="13dp"
        android:text="Login"
        android:textColor="#FF9900"
        android:textStyle="bold" />

    <!-- <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_marginLeft="20dp"
        android:id="@+id/lbl_result"
        android:text="login result here"        
        android:textColor="#FF0040">
    </TextView> -->

</LinearLayout>

Login.java

public class Login extends Activity implements OnClickListener {

    //Declaration
    EditText etUserName;
    EditText etPassword;
    Button loginBtn;

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

    //Create a HTTPClient as the form container
    HttpClient httpclient;

    //Use HTTP Post method
    HttpPost httppost;

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

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

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

        initialise();
    }

    private void initialise() {
        // TODO Auto-generated method stub
        etUserName = (EditText) findViewById(R.id.etUserName);
        etPassword = (EditText) findViewById(R.id.etPassword);
        loginBtn = (Button) findViewById(R.id.loginBtn);

        //Set onClickListener for the button
        loginBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        //Create new default HTTPClient
        httpclient = new DefaultHttpClient();

        //Create new HTTP POST with URL to PHP file as parameter
        httppost = new HttpPost("http://127.0.0.1/android_connect/login.php");

        //Assign input text to strings
        username = etUserName.getText().toString();
        password = etPassword.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 strings
                    String retUser = jsonResponse.getString("LoginUser");
                    String retPass = jsonResponse.getString("Password");

                    //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 Preference
                        SharedPreferences.Editor spedit = sp.edit();

                        //Put the login details as Strings
                        spedit.putString("user", username);
                        spedit.putString("password", password);

                        //Close the editor
                        spedit.commit();

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

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


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

        }

    }//End of 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 of convertStreamtoString()
}

1 个答案:

答案 0 :(得分:1)

您正在执行 network I/O on the main thread ,这可能导致程序崩溃。尝试使用AsyncTask进行网络操作。

  

AsyncTask可以正确,轻松地使用UI线程。这个班   允许执行后台操作并在UI上发布结果   线程,而不必操纵线程和/或处理程序。