java - Android 应用程序在访问本地主机时崩溃

标签 java php android post authentication

抱歉我的英语不好..这是我的第一篇文章:D 但是我在 Android/Java 编程方面遇到了一个大问题,而且我在 Android 编程方面真的很新......

我尝试将数据发送到外部 PHP 服务器(在同一网络中)并使用 SharedPreferences 保存。但是,如果我按下“登录”按钮,应用程序总是会崩溃。

这是我的代码: 登录类

public class Login extends ActionBarActivity {
    final Context context = this;
        @Override
        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);

            final Button btn_login = (Button) findViewById(R.id.btn_login);
            final EditText username = (EditText) findViewById(R.id.login_username);
            final EditText password = (EditText) findViewById(R.id.login_password);
            final EditText password2 = (EditText) findViewById(R.id.login_password2);
            final EditText ip = (EditText) findViewById(R.id.login_ip);

            btn_login.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

                        // Create a new HttpClient and Post Header
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost(ip.getText().toString()+"/app/android/login.php");
                        JSONObject json = new JSONObject();

                        try {
                            // JSON data:
                            json.put("username", username.getText().toString());
                            json.put("password", password.getText().toString());

                            JSONArray postjson=new JSONArray();
                            postjson.put(json);

                            // Post the data:
                            httppost.setHeader("json",json.toString());
                            httppost.getParams().setParameter("jsonpost",postjson);

                            // Execute HTTP Post Request
                            System.out.print(json);
                            @SuppressWarnings("deprecation")
                            HttpResponse response = httpclient.execute(httppost);

                            // for JSON:
                            if(response != null){
                                InputStream is = response.getEntity().getContent();

                                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) {
                                    Toast.makeText(getApplicationContext(), "Error!"+e, Toast.LENGTH_LONG).show();
                                } finally {
                                    try {
                                        is.close();
                                    } catch (IOException e) {
                                        Toast.makeText(getApplicationContext(), "Error!"+e, Toast.LENGTH_LONG).show();
                                    }
                                }
                                String text = sb.toString();

                                if(text == "true"){
                                    //save Username in Preferences
                                     savePreferences("username", username.getText().toString());
                                    //save password in Preferences 
                                     savePreferences("password", password.getText().toString());
                                    //save password in Preferences 
                                     savePreferences("ip", ip.getText().toString());


                                    Intent i = new Intent(Login.this, Start.class);

                                    startActivity(i);
                                }
                                else if(text == "405"){
                                    Toast.makeText(getApplicationContext(), "Error while saving data", Toast.LENGTH_LONG).show();
                                }
                                else if(text == "406"){
                                    Toast.makeText(getApplicationContext(), "Passwords aren't the same!", Toast.LENGTH_LONG).show();
                                }
                                else if(text == "true408"){
                                    //save Username in Preferences
                                     savePreferences("username", username.getText().toString());
                                    //save password in Preferences 
                                     savePreferences("password", password.getText().toString());
                                    //save password in Preferences 
                                     savePreferences("ip", ip.getText().toString());

                                    Toast.makeText(getApplicationContext(), "Wieder eingeloggt!", Toast.LENGTH_LONG).show();
                                    Intent i = new Intent(Login.this, Start.class);

                                    startActivity(i);
                                }
                                else if(text == "407"){
                                    Toast.makeText(getApplicationContext(), "Passwort falsch!", Toast.LENGTH_LONG).show();
                                }
                                else if(text == "404"){
                                    Toast.makeText(getApplicationContext(), "Fehler beim abgleich!", Toast.LENGTH_LONG).show();
                                }
                            }


                        }catch (IOException e) {
                            Toast.makeText(getApplicationContext(), "Fehler beim Login!"+e, Toast.LENGTH_LONG).show();
                        } catch (JSONException e1) {
                            Toast.makeText(getApplicationContext(), "Fehler beim Login!"+e1, Toast.LENGTH_LONG).show();
                        }

                }

            });
        } 

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

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
            if (id == R.id.menu_login_help) {
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

                    // set title
                    alertDialogBuilder.setTitle("Hilfe");

                    // set dialog message
                    alertDialogBuilder
                        .setMessage("This is the Tutorial of the App")
                        .setCancelable(true)
                        ;

                        // create alert dialog
                        AlertDialog alertDialog = alertDialogBuilder.create();

                        // show it
                        alertDialog.show();
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
        private void savePreferences(String key, String value) {
              SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
              Editor editor = sharedPreferences.edit();
              editor.putString(key, value);
              editor.commit();
        }

   }

我的 list .xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="de.mbpictures.fastorder"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity android:name=".Main">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>  
        </activity>
        <activity android:name=".Start" android:label="@string/app_name" ></activity>

        <activity android:name=".Login"></activity>

    </application>
    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />

</manifest>

最后我的 login.php 在 XAMPP 中运行:

<?php
require("../v0.6/inc/connect.php");
if(isset($_SERVER["HTTP_JSON"])){
    $json = $_SERVER['HTTP_JSON'];
    $data = json_decode($json);

    $username = $data->username;
    $password = $data->password;

    mysql_select_db("forder_info");
    $sql = mysql_query("SELECT * FROM bedienungen WHERE bedienung = '".$username."'");
    if(mysql_num_rows($sql) == 0){
        if($_POST["pw1"] == $_POST["pw2"]){
            $sql_i = "INSERT INTO bedienungen (bedienung, password) VALUES ('".$username."', '".$password."')";
            $sql_createTable = "CREATE TABLE IF NOT EXISTS `".$username."` (
            `id` int(32) NOT NULL, `essen` text NOT NULL, `tisch` text NOT NULL, `kommentar` text NOT NULL, `bedienung` text NOT NULL, `art` text NOT NULL, `preis` text NOT NULL, `place` text NOT NULL, `time` text NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;";
            if(mysql_query($sql_i)){

                 mysql_select_db("forder_todruck");

                if(mysql_query($sql_createTable)){
                    echo "true";
                }

            }
            else{
                ?>
                405
                <?php   
            }
        }
        else{
            ?>
            406
            <?php   
        }
    }
    else{
        $sql_c = mysql_query("SELECT * FROM bedienungen WHERE bedienung='".$username."'");
        $out_c = mysql_fetch_assoc($sql_c);
        if($out_c["password"] == $password){

                ?>
                true408
                <?

        }
        else{
            ?>
            407
            <?php   
        }
    }
}
else{
    ?>404<?php
}

?>

编辑: 现在我将代码编辑为:

public class Login extends ActionBarActivity {
    public static final String PREFS_NAME = "Fastorder_Settings";
    final Context context = this;

    EditText username;
    EditText password;
    EditText password2;
    EditText ip;

    ProgressDialog dialog = null;

    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    List<NameValuePair> nameValuePairs;

        @Override
        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);

            final Button btn_login = (Button) findViewById(R.id.btn_login);
            username = (EditText) findViewById(R.id.login_username);
            password = (EditText) findViewById(R.id.login_password);
            password2 = (EditText) findViewById(R.id.login_password2);
            ip = (EditText) findViewById(R.id.login_ip);

            btn_login.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

                    dialog = ProgressDialog.show(Login.this, "", 
                            "Bitte warten...", true);
                     new Thread(new Runnable() {
                            public void run() {
                                login();                          
                            }
                          }).start();                   
                }

            });
        } 


        void login(){
            try{
                httpclient = new DefaultHttpClient();
                httppost = new HttpPost(ip.getText().toString()+"/fastorder/android/login.php"); // make sure the url is correct.
                //add your data
                nameValuePairs = new ArrayList<NameValuePair>(2);
                // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar, 
                nameValuePairs.add(new BasicNameValuePair("username", username.getText().toString().trim()));  // $Edittext_value = $_POST['Edittext_value'];
                nameValuePairs.add(new BasicNameValuePair("password",password.getText().toString().trim())); 
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                //Execute HTTP Post Request
                response=httpclient.execute(httppost);
                // edited by James from coderzheaven.. from here....
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                final String response = httpclient.execute(httppost, responseHandler);
                System.out.println("Response : " + response); 

                if(response.equalsIgnoreCase("true")){
                    //save Username in Preferences
                     savePreferences("username", username.getText().toString());
                    //save password in Preferences 
                     savePreferences("password", password.getText().toString());
                    //save password in Preferences 
                     savePreferences("ip", ip.getText().toString());


                    Intent i = new Intent(Login.this, Start.class);

                    startActivity(i);
                }
                else if(response.equalsIgnoreCase("405")){
                    Toast.makeText(getApplicationContext(), "Fehler beim Speichern", Toast.LENGTH_LONG).show();
                }
                else if(response.equalsIgnoreCase("406")){
                    Toast.makeText(getApplicationContext(), "Passwoerte nicht gleich!", Toast.LENGTH_LONG).show();
                }
                else if(response.equalsIgnoreCase("true408")){
                    //save Username in Preferences
                     savePreferences("username", username.getText().toString());
                    //save password in Preferences 
                     savePreferences("password", password.getText().toString());
                    //save password in Preferences 
                     savePreferences("ip", ip.getText().toString());

                    Toast.makeText(getApplicationContext(), "Wieder eingeloggt!", Toast.LENGTH_LONG).show();
                    Intent i = new Intent(Login.this, Start.class);

                    startActivity(i);
                }
                else if(response.equalsIgnoreCase("407")){
                    Toast.makeText(getApplicationContext(), "Passwort falsch!", Toast.LENGTH_LONG).show();
                }
                else if(response.equalsIgnoreCase("404")){
                    Toast.makeText(getApplicationContext(), "Fehler beim abgleich!", Toast.LENGTH_LONG).show();
                }
                dialog.dismiss();

            }catch(Exception e){
                dialog.dismiss();
                Toast.makeText(getApplicationContext(), "Fehler beim Login!"+e.getMessage(), Toast.LENGTH_LONG).show();
                System.out.println("Exception : " + e.getMessage());
            }
        }

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

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
            if (id == R.id.menu_login_help) {
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

                    // set title
                    alertDialogBuilder.setTitle("Hilfe");

                    // set dialog message
                    alertDialogBuilder
                        .setMessage("Tragen Sie ihre Bedienungsid und Ihr Passwort ein! \n"
                                + "Sollten Sie bereits registriert sein, werden sie eingeloggt\n"
                                + "andernfalls werden Sie registriert\n \n"
                                + "Die Server-IP wird Ihnen vom Admin mitgeteilt.")
                        .setCancelable(true)
                        ;

                        // create alert dialog
                        AlertDialog alertDialog = alertDialogBuilder.create();

                        // show it
                        alertDialog.show();
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
        private void savePreferences(String key, String value) {
              SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
              Editor editor = sharedPreferences.edit();
              editor.putString(key, value);
              editor.commit();
        }
}

如果我运行 ProgressDialog 会打开一小段时间,然后应用程序再次崩溃......有什么想法......? 现在我得到这个错误: 目标主机不能为空,也不能在参数中设置。 scheme=null, host=null, path=192.168.178.XX/fastorder/android/login.php

最佳答案

您正在应用程序的主线程上运行与网络相关的代码。解决这个问题的一种方法是启动 AsyncTask然后稍后处理结果,再次回到主线程。

还有其他选择,例如 Handler的,但我相信 AsyncTasks 使与 UI 的交互变得更加简单,我认为这正是您所需要的。

在链接中我passed有一个用于简单文件下载 AsyncTask 的代码 fragment ,其中包含解决此问题所需的一切,请看一下。

关于java - Android 应用程序在访问本地主机时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31625474/

相关文章:

php - 提交表单后,在 PHP 中对来自 MySQL 的数据进行粘性选择不会粘住所有数据

php - 使用 PDO 调用带有 Out 参数的存储过程

java - Thread.sleep() 和 FileWriter()

java - 为数组索引赋值和为java中的变量赋值之间的性能差异

php - 为什么即使我设置了 alpha 混合设置,GIF 图像也会失去 imagegif() 的透明度?

android - 将 Android Eclipse 项目移动到工作区

android - 为什么HtmlCompat.fromHtml()没有设置文本样式?

javascript - 我可以清除移动设备上触摸的 div 的焦点吗?

Java join 2 不包含在一个表达式中

java - 带 Trident 动画的 JScrollPane 出现 bug?