I am trying to test an Android application and add data to a database hosted on localhost. I opened a tunnel using ngrok to access a database stored on my local computer. Here is my code:
public class MainActivity extends FragmentActivity{
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private static String email;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
private static final int RESULT_SETTINGS = 1;
private static String IP_ADDRESS="http://682dc364.ngrok.com/";
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Account[] accounts = AccountManager.get(getBaseContext()).getAccounts();
if(accounts.length > 0)
email = accounts[0].name;
Toast.makeText(this, email, Toast.LENGTH_SHORT).show();
mTitle = mDrawerTitle = getTitle();
addUser();
}
private static void addUser()
{
HashMap<String, String> nameValuePairs = new HashMap<String, String>();
nameValuePairs.put("email",email);
String id="addUser";
AsyncHttpPost asyncHttpPost = new AsyncHttpPost(nameValuePairs);
asyncHttpPost.execute(id,"http://"+IP_ADDRESS+"/MakeMyDay/add_user.php");
}
AsyncHttpPost
public class AsyncHttpPost extends AsyncTask<String, String, String>
{
private HashMap<String,String> mData=null;
public AsyncHttpPost(HashMap<String,String> data)
{
mData=data;
}
@Override
protected String doInBackground(String... params)
{
HttpURLConnection connection;
OutputStreamWriter request = null;
ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
Iterator<String> it = mData.keySet().iterator();
String parameters="";
while (it.hasNext()) {
String key = it.next();
String value=mData.get(key);
parameters=parameters+key+"="+value+"&";
Log.d("key",key);
Log.d("value",mData.get(key));
Log.d("string value",value);
nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
}
parameters=parameters.substring(0, parameters.length()-1);
Log.d("parameters",parameters);
URL url = null;
String response = null;
String id="";
try
{
id=params[0];
url = new URL(params[1]);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
response = sb.toString();
String s=regExExtractor(response);
Log.d("server message","Message from Server: \n"+ response);
Log.d("progress","here3");
isr.close();
reader.close();
}
catch (ClientProtocolException cpe) {
System.out.println("First Exception caz of HttpResponese :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Second Exception caz of HttpResponse :" + ioe);
ioe.printStackTrace();
}
return response;
}
public String regExExtractor(String response)
{
String jsonResponse="";
Pattern p=Pattern.compile("(\\Q[\\E.*?\\Q]\\E)");
Matcher m=p.matcher(response);
while(m.find())
{
jsonResponse=m.group(1);
}
return jsonResponse;
}
@Override
protected void onPostExecute(String result) {
}
}
add_user.php
<?php
$DBServer = 'localhost';
$DBUser = 'xxxx';
$DBPass = 'xxxx';
$DBName = 'xxxx';
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
$sql="SELECT email FROM user WHERE email='$email'";
$rs=$conn->query($sql);
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$rows_returned = $rs->num_rows;
if($rows_returned==0)
{
$sql="INSERT INTO user (email) VALUES ($email)";
if($conn->query($sql) === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$last_inserted_id = $conn->insert_id;
$affected_rows = $conn->affected_rows;
}
}
}
$conn->close();
?>
The server message is as follows:
Message from Server:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><head><meta http-equiv="refresh" content="0;url=http://search.maxonline.com.sg/main?InterceptSource=0&ClientLocation=sg&ParticipantID=zflj3p94j2yfy45e433eet7iejjmxgif&FailureMode=1&SearchQuery=&FailedURI=http%3A%2F%2Fhttp%2F%2F682dc364.ngrok.com%2F%2FMakeMyDay%2Fadd_user.php&AddInType=4&Version=2.1.8-1.90base&Referer=&Implementation=0"/><script type="text/javascript">url="http://search.maxonline.com.sg/main?InterceptSource=0&ClientLocation=sg&ParticipantID=zflj3p94j2yfy45e433eet7iejjmxgif&FailureMode=1&SearchQuery=&FailedURI=http%3A%2F%2Fhttp%2F%2F682dc364.ngrok.com%2F%2FMakeMyDay%2Fadd_user.php&AddInType=4&Version=2.1.8-1.90base&Referer=&Implementation=0";if(top.location!=location){var w=window,d=document,e=d.documentElement,b=d.body,x=w.innerWidth||e.clientWidth||b.clientWidth,y=w.innerHeight||e.clientHeight||b.clientHeight;url+="&w="+x+"&h="+y;}window.location.replace(url);</script></head><body></body></html>
Does anyone know why this is not working