简体   繁体   English

Android-如何使用PHP从MySQL数据库获取响应?

[英]Android - How to get response from a MySQL Database using PHP?

So hello all, 大家好

I have a problem getting a response from my php file I created. 我从我创建的php文件获取响应时遇到问题。 I'm using AsyncTask to send a request with a SELECT statement which then get's passed throught to MySQL Database localy. 我正在使用AsyncTask发送带有SELECT语句的请求,然后将其传递到MySQL数据库本地。 I wanted to get the response back to Android as a JSON-String but What I get in Android is just an empty string. 我想以JSON-String的形式将响应返回给Android,但是我在Android中得到的只是一个空字符串。 If I try the PHP file in browser I'm getting a correct output. 如果我在浏览器中尝试使用PHP文件,则会得到正确的输出。

Here are my code Samples: 这是我的代码示例:

My AsyncTask class: 我的AsyncTask类:

public class DBHelperAsyncTask extends AsyncTask<String, Void, String> {
    private static final String SHARED_PREFERENCE = SharedPreferencesEnum.SHARED_PREFERENCE.getText();
    SharedPreferences prefs;
    final protected Activity currentActivity;
    final protected URL link;
    final protected String fileName;
    private ProgressDialog dialog;

    public DBHelperAsyncTask(Activity currentActivity, URL link, String fileName) throws MalformedURLException
    {
        this.currentActivity = currentActivity;
        this.fileName = fileName;
        this.link = new URL(String.format("http://{0}/{1}", link, fileName));
    }

    public DBHelperAsyncTask(Activity currentActivity, URL link) throws MalformedURLException
    {
        this.currentActivity = currentActivity;
        this.fileName = "uebergabe.php";
        this.link = new URL(String.format("http://{0}/{1}", link, fileName));
    }

    public DBHelperAsyncTask(Activity currentActivity) throws MalformedURLException
    {
        prefs = PreferenceManager.getDefaultSharedPreferences(currentActivity);
        this.currentActivity = currentActivity;
        this.fileName = "uebergabe.php";
        this.link = new URL(String.format("http://%s/%s", prefs.getString(SharedPreferencesEnum.HOST.getText(), "127.0.0.1"), prefs.getString(SharedPreferencesEnum.PFAD.getText(), fileName)));
        AlertDialog.Builder builder = new AlertDialog.Builder(currentActivity);
        builder.setTitle(link.toString());
        Dialog dialog = builder.create();
        dialog.show();


    }

    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(currentActivity);
        dialog.setIndeterminate(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.show();
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        try {
            HttpURLConnection connection = (HttpURLConnection) link.openConnection();
            connection.setDoOutput(true);

            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());

            if (params.length > 1) return null;
            else
            {
                String data = URLEncoder.encode("Url", "UTF-8") + "=" + URLEncoder.encode(params[0], "UTF-8");
                writer.write(data);
                writer.flush();
                writer.close();
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder builder = new StringBuilder();
                String line = null;
                while((line = reader.readLine()) != null)
                {
                    builder.append(line);
                    break;
                }
                reader.close();
                return builder.toString().trim();
            }

            //Aufruf bei Verbindungsunterbrechung
        } catch (Exception e) {
            AlertDialog.Builder builder = new AlertDialog.Builder(currentActivity);
            builder.setTitle("Verbindungsfehler");
            builder.setMessage("Die Verbindung mit dem Server hat fehlergeschlagen");
            builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.dismiss();
                }
            });


            Dialog dialog = builder.create();
            dialog.show();
            return null;
        }
    }

    @Override
    protected void onPostExecute(String result) {
        if(dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    //Konventiert ein json String zum ContentValues
    public ContentValues jsonToContentValues(String jsonString) {
        ContentValues output = new ContentValues();
        JSONObject parser = new JSONObject();
        try {
            if (jsonString == null) throw new JSONException(null);
            parser = new JSONObject(jsonString);
            Iterator<String> iterator = parser.keys();
            JSONArray array = parser.names();
            while (iterator.hasNext()) output.put(iterator.next(), array.getString(output.size()));
        } catch (JSONException e) {
            AlertDialog.Builder builder = new AlertDialog.Builder(currentActivity);
            builder.setTitle("Daten-Konvertierungsfehler");
            builder.setMessage("Die Daten konnten nicht richtig gelesen werden\n" + jsonString);
            builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.dismiss();
                }
            });


            Dialog dialog = builder.create();
            dialog.show();
            return null;
        } finally {
            return output;
        }
    }

}

My MainActivity: 我的主要活动:

public class MainActivity extends ActionBarActivity {
    private static final String SHARED_PREFERENCE = SharedPreferencesEnum.SHARED_PREFERENCE.getText();
    ContentValues result = null;
    private EditText benutzerEditText;
    private EditText passwortEditText;
    private TextView anmeldenTextView;
    DBHelperAsyncTask asyncTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences prefs = getSharedPreferences(SHARED_PREFERENCE, MODE_PRIVATE);

        String benutzer = prefs.getString(SharedPreferencesEnum.BENUTZER.getText(), null);
        if(benutzer == null) {
            setContentView(R.layout.login_maske);
            benutzerEditText = (EditText) findViewById(R.id.benutzerNameEditText);
            passwortEditText = (EditText) findViewById(R.id.benutzerPasswortEditText);
        }
        else
            setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = null;
        switch(item.getItemId()) {
            case R.id.settings_scan:
                intent = new Intent(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                intent.setClassName(this, PreferencesActivity.class.getName());
                break;
            case R.id.settings:
                intent = new Intent(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                intent.setClassName(this, SettingsActivity.class.getName());
                break;
        }
        startActivity(intent);
        return super.onOptionsItemSelected(item);
    }
    public void onAnmeldenClick(View view) throws MalformedURLException, InterruptedException, ExecutionException
    {
        asyncTask = new DBHelperAsyncTask(this);
        String sql = String.format("SELECT IDBenutzer, Passwort FROM benutzer where Benutzername = '{0}'", benutzerEditText.getText().toString());
        result = asyncTask.jsonToContentValues(asyncTask.execute(sql).get());

        anmeldenTextView = (TextView) findViewById(R.id.anmeldenTextView);
        anmeldenTextView.setText(result.toString());
        /*
        String passwort = result.getAsString("Passwort");
        if(passwortEditText.getText().toString() == passwort)
        {
            SharedPreferences prefs = getSharedPreferences(SHARED_PREFERENCE, MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putInt(SharedPreferencesEnum.BENUTZER_ID.getText(), result.getAsInteger("IDBenutzer"));
            editor.putString(SharedPreferencesEnum.BENUTZER.getText(), result.getAsString("Benutzer"));
        }*/
    }


    public void onPruefenClick(View view) {
        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
        startActivityForResult(intent, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0) {
            if (resultCode == RESULT_OK) {

                String contents = data.getStringExtra("SCAN_RESULT");
                AlertDialog dialog = new AlertDialog.Builder(MainActivity.this).create();
                dialog.setTitle("Barcode");
                dialog.setMessage(contents);
                dialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                        new DialogInterface.OnClickListener(){
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                dialog.show();
                // Handle successful scan

            }
        }
    }


    public void onAbmeldenClick(View view)
    {
        SharedPreferences prefs = getSharedPreferences(SHARED_PREFERENCE, MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.remove(SharedPreferencesEnum.BENUTZER.getText());
        editor.remove(SharedPreferencesEnum.BENUTZER_ID.getText());
        editor.commit();
        restartActivity(this);
    }

    private void restartActivity(Activity restartActivity)
    {
        Intent intent = new Intent();
        intent.setClass(restartActivity, restartActivity.getClass());
        restartActivity.startActivity(intent);
        restartActivity.finish();
    }
}

And the PHP file: 和PHP文件:

    <?php

    $link = "localhost";
    $user = "root";
    $password = "";
    $dbname = "ProjektZ";

    $conn = mysqli_connect($link,$user,$password,$dbname);

    if ($conn->connect_error) {
                #Script verlassen
                die("Connection failed");
            } 
            $sql = $_POST['Url']; #sql-anfrage erstellen
            $myArray = array();
            if ($result = $conn->query($sql)) #sql-anfrage ausführen und in Variable speichern
            if(is_object($result))
            {
                while($row = $result->fetch_array(MYSQL_ASSOC)) $myArray[] = $row;
                header('Content-type: application/json');
                echo json_encode($myArray);     
            }
            mysqli_close($conn);
?>

Everywhere I read it states that echo json_encode($myArray) should be correct way to pass response back to the app. 我到处阅读的内容都表明echo json_encode($ myArray)应该是将响应传递回应用程序的正确方法。

I think you should consider using a REST approach for getting data from your database. 我认为您应该考虑使用REST方法从数据库中获取数据。 It'll be much more easier to the Android application and much more safe (SQL injections are a risk in your code). 这将使Android应用程序变得更加轻松,也更加安全(SQL注入会危害您的代码)。 You can use a CMS like Symfony (or any ohter CMS that you like) to help you build that server side. 您可以使用Symfony之类的CMS(或您喜欢的任何其他CMS)来帮助您构建服务器端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM