Hello folks of stackoverflow!
I have a problem that I've been trying to fix for days now, but nobody in our group can fix it. Here's the issue:
The task is "simple": Set up a connection between an Android device (run as an emulator in Eclipse) and a locally set-up MySQL Database. The goal was to be able to run queries (saved in PHP-scripts which are stored on a local webserver (using XAMPP)), so that the Android device was able to withdraw content of said database and display it in a TextView. To do this, the following tutorial was used as help: http://www.youtube.com/watch?v=38HDyEUEpCw
Unfortunately, my setup didn't work properly. Before I continue describing my issue, here's my code (don't worry if my explanation doesn't make any sense yet, I put a summary of my issue at the end):
My set-up in Eclipse was the following: The MainActivity class, where an instance of the AsyncTask TestAusfuehren is created and where the TextView field with the id "Frage" from the Android layout (activity_main.xml) is set. Here's the code:
package com.example.androidtestdatabase;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
static TextView resultView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultView = (TextView) findViewById(R.id.Frage);
new TestAusfuehren().execute();
// StrictMode.enableDefaults(); STRICT MODE ENABLED
}
}
Then there's the AsyncTask, which contains the tricky part: The connection to the webserver and the execution of the php-scripts containing the MySQL-queries. The issue here, is that no text is returned to the MainActivity class, where it should actually return the result of the queries (for example the answer to a question or a simple id, like "5").
package com.example.androidtestdatabase;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;
public class TestAusfuehren extends AsyncTask<String, Void, String> {
String result = "";
String sResult = "";
protected String doInBackground(String... params) {
InputStream isr = null;
try {
HttpClient httpclient = new DefaultHttpClient();
MainActivity.resultView.setText("Verbindung wird hergestellt...");
HttpPost httppost = new HttpPost("http://10.0.2.2:8080/php/AndroidTest.php"); // MY PHP SCRIPT ADDRESS
MainActivity.resultView.setText("Verbindung hergestellt!");
MainActivity.resultView.setText("Antwort speichern...");
HttpResponse response = httpclient.execute(httppost);
MainActivity.resultView.setText("Antwort gespeichert!");
HttpEntity entity = response.getEntity();
MainActivity.resultView.setText("Antwort wird verarbeitet...");
isr = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
isr, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
MainActivity.resultView.setText("Antwort verarbeitet!");
JSONObject resultstring = new JSONObject(result);
sResult = resultstring.getString("question");
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data " + e.toString());
}finally{
try{
if(isr != null){
isr.close();}
}catch(Exception e2){
Log.e("log_tag", "Error Parsing Data " + e2.toString());
}
}
return sResult;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
MainActivity.resultView.setText("Ergebnis: "+ sResult);
}
}
For some reason, the variable sResult, which is supposed to be containing the line of text from the database, is empty and the TextView of my Android-Layout simply displays "Ergebnis: " without anything following.
To get a better idea of what my layout xml-file looks like (even though I'm quite sure that the error isn't caused by the layout file):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true" >
<RadioButton
android:id="@+id/radioButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="26dp"
android:layout_marginTop="18dp"
android:text="RadioButton" />
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton" />
<RadioButton
android:id="@+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton" />
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="RadioButton" />
</RadioGroup>
<TextView
android:id="@+id/Frage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/radioGroup1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="72dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/Kategorie"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/Frage"
android:text="TextView" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="55dp"
android:layout_marginLeft="50dp"
android:layout_toRightOf="@+id/radioGroup1"
android:text="Weiter" />
<Chronometer
android:id="@+id/chronometer1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/Frage"
android:layout_alignRight="@+id/button1"
android:text="Chronometer" />
<TextView
android:id="@+id/Unterkategorie"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/Kategorie"
android:layout_alignBottom="@+id/Kategorie"
android:layout_centerHorizontal="true"
android:text="TextView" />
</RelativeLayout>
Last but not least, my php-script (which I have tested successfully in a browser, so I can ensure you that it works):
<?php
$con = mysql_connect("localhost","root","mcf");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mcf", $con);
$result = mysql_query("SELECT question FROM Fragensatz1");
while($row = mysql_fetch_assoc($result))
{
$output[]=$row;
}
print(json_encode($output));
mysql_close($con);
?>
To sum it up really quickly:
Goal: Android-emulator executes php script, which contains MySQL queries, and is found on local webserver and saves the result of the queries in a variable, before finally displaying them in a TextView from the Android layout XML-file.
Issue: No result is saved in variable sResult, even though connection to webserver and execution of scripts both work, and therefore no text is displayed in the TextView field of the Android App.
I have tried pretty much everything, but I'm out of ideas, which is why I would be sooo thankful and grateful if someone could point out my flaw in logic or coding mistake!
Thanks foreward!
Yann G.
PS: If there are any questions regarding my explanation e.g. if I haven't gone into detail enough or left something unexplained please feel free to let me know! Thanks again!
PPS: There are no errors printed out in by the Android LogCat, but my guess is that the issue has to do with a Time-Out, since the App will run for 3-4 minutes and be stuck displaying "Antwort speichern..." and then suddenly switching to "Ergebnis: "
Here's a link to what the app is supposed to look like: http://i44.tinypic.com/2dt80og.png
The textView with the String "QUESTION" doesn't change after running the AsyncTask...