大家好,
我从我创建的php文件中获取响应时遇到问题。我正在使用AsyncTask发送带有SELECT语句的请求,然后将其传递给MySQL数据库localy。我希望将响应作为JSON-String返回给Android,但我在Android中获得的只是一个空字符串。如果我在浏览器中尝试PHP文件,我会得到正确的输出。
以下是我的代码示例:
我的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;
}
}
}
我的主要活动:
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();
}
}
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);
?>
我读到的每个地方都声明,echo json_encode($ myArray)应该是将响应传递回应用程序的正确方法。