I am new to android development. As part of a bigger project I want to insert data from an android device to a web-server. So I did some research and articles like The article from androidhive and this article from codeproject were really helpful in trying to develop a test-app which inserts in to a mysql db, which is residing at a remote web-server.
Here is my android code
ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxxxxxxx.in/installment.php");
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", editTextCustomer.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("amount", editTextAmount.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
Log.i("postData", response.getStatusLine().toString());
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
}
else {
Toast.makeText(PayBillActivity.this, "Internet Access, Denied!!", Toast.LENGTH_LONG).show();
}
Here is the php code
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['amount'])) {
$name = $_POST['name'];
$amount = $_POST['amount'];
$con=mysqli_connect("localhost","db_user","passwd","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO installment (name, amount) VALUES ('$_POST[name]','$_POST[amount]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
// check if row inserted or not
if ($sql) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Installment made successfully";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
echo $result;
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
//$amount = 1000;
//echo $amount;
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
when I run the app, I am getting this "NetworkOnMainThreadException" exception and as a result no rows are being added. But its working perfect with HTML POST.
Can anyone tell me where the problem is in my code?
Thanks in advance!:)
I think if you spent the time you did on posting this question into google you may have got some good answers... Just to complete this question
There are two options available with you, either you can add a line of code and allow network operation on main thread, but its very very bad for your app and also as a coding style.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
The longer option is to redesign the code to have the network operations performed in a separate thread. This is both good for the app and you will learn how to work on a multi-threaded program.
I think you should not use that strict or take it manually out of main..
Just use a smart premade lib and it is making all for you !
Download : http://loopj.com/android-async-http/
Note: And this lib is even using gzip to compress requests :)
Related
I have been searching everywhere this question and the only answer i've seen is JSON! I feel there is also other ways to do this.
My problem is i can post data from android to php script to insert data to my server. But what i want to do is get some data from my php to android. (without using JSON).
Please, i'm still in the basics. Make this as simple as possible!
Here's my php script:
<?php
$con=mysqli_connect("HOST", "USER", "PASSWORD", "DB_NAME");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$tablenamep = $_POST["tablenamep"];
$stringp = $_POST["stringp"];
$val = mysqli_query($con, "DESCRIBE `$tablenamep`");
if($val == TRUE) {
echo "Table exists";
$stringp = "This ID already exists. Try again!";
} else {
echo "Table does not exist";
mysqli_query($con, "CREATE TABLE ".$tablenamep." ( name VARCHAR(30), number INT, email VARCHAR(30))");
$stringp = "Your ID is available";
}
mysqli_close($con);
?>
This is how i used my java class to post data to php script.
public void CONNECT_SERVER(){
String msg = etID.getText().toString();
if (msg.length()>0){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myfile.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("tablenamep", msg));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
} else {
Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show(); }
}
The php script and android app is working FINE, no errors! Now i can add the data from my android app to the php script. NO PROBLEMS TILL NOW!
BUT WHAT I WANT, is to get the $stringp variable from the php script above to my android app after executing the script. In other words i want my app to know whether the ID exists or not.
I have already checked many forums regarding this question. SOLVE THIS PROBLEM WITHOUT JSON.
You must use json or other parsing method to retrieve data from server
try this
contact.php
<?php
mysql_connect ("localhost","root","");
mysql_select_db("meetapp");
$output=array();
$q=mysql_query("SELECT `app_id` FROM `registration`");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print (json_encode($output));
mysql_close();
?>
in your java code
try {
HttpClient httpclient2 = new DefaultHttpClient();
HttpPost httppost2 = new HttpPost("http://10.0.2.2:80/contact.php");
HttpResponse response2 = httpclient2.execute(httppost2);
HttpEntity entity2 = response2.getEntity();
is2 = entity2.getContent();
Log.e("log_tag", "connection success ");
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
try
{
BufferedReader reader2 = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb2 = new StringBuilder();
String line = null;
while ((line = reader2.readLine()) != null)
{
sb2.append(line + "\n");
}
is.close();
result3=sb2.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
try
{
JSONArray jArray2 = new JSONArray(result3);
String s11;
Log.w("Lengh",""+jArray2.length());
for(int i=0;i<jArray2.length();i++){
JSONObject json_data2 = jArray2.getJSONObject(i);
s11=json_data2.getString("app_id");
}
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
}
I havnt been able to find a guide on how to submit data to a database from android through php.
say for instance i have the following site:
function insert($var1) {
// mysql inserting a new row
$result = mysql_query("INSERT INTO report (name) VALUES ('$var1')");
// check if row inserted or not
if ($result) {
// successfully inserted into database;
$msg = "Message received.";
} else {
$msg = "Not received.";
}
return ($msg);
}
if (isset($_POST['name'])) {
$name = $_POST['name']);
insert($name);
} else {
echo "No input.";
}
How would i call this from my Android project?
You can refer to this tutorial but you do need a web-server for it.
Request mechanism Android App ----> webserver ------> database (mysql)
Respond mechanism Android App <---- webserver <------ database (mysql)
Android App will use JSON or other to get the data and display it
PHP Code
<?php
$con=mysql_connect("host","username");
if(!$con)
{
die("Could Not Connect".mysql_error());
}
$db="CREATE DATABASE login";
mysql_query($db,$con);
mysql_select_db("login",$con);
$tab="CREATE TABLE info(FirstName varchar(20),LastName varchar(20))";
mysql_query($tab,$con);
$user_fname=$_POST['fn'];
$user_lname=$_POST['ln'];
$row= mysql_query("INSERT INTO info (FirstName,LastName) VALUES('$user_fname', '$user_lname')");
if ($row) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
echo $row;
}
mysql_close($con);
?>
Sending the Data (Android)
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://127.0.0.1:4001/file.php");
List<NameValuePair> pair=new ArrayList<NameValuePair>(2);
pair.add(new BasicNameValuePair("fn",fname));
pair.add(new BasicNameValuePair("ln",lname));
httppost.setEntity(new UrlEncodedFormEntity(pair));
HttpResponse response = httpclient.execute(httppost);
I have created a webservice called "login.php" where I send the id and password information from android. The webservice successfully catches the id and password. I need to compare that id and password to the ones already present in the database and check whether they exist or not. If they do, I need to send back an "okay message" back to android so I can start a new intent. If the id and password do not exist, I want to display an error.
Below is my code.
Login.java
HttpPost httppost = new HttpPost("http://abc.com/webservice/Login.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("userid", et1.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("pass", et2.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
client.execute(httppost);
Log.d("valueeeeeeeeeeee", et6.getText().toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
Log.d("exppppppp", "msg");
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("exppppppp", "msg");
}
Login.php:
<?php
$host = "localhost";
$user = "user";
$pass = "pass";
$connection = mysql_connect($host,$user,$pass) or die (mysql_errno().": ".mysql_error()."<BR>");
$userid = $_POST['userid'];
$pass = $_POST['pass'];
$db_select=mysql_select_db("my_db");
if(!$db_select){
die(mysql_error());
echo "error";
}
What query should I run here to check the database against the specific id and password it recieved and send back an "okay message" to the android app. Thanks
You can try something like this:
Java:
HttpPost httppost = new HttpPost("http://abc.com/webservice/Login.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("userid", et1.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("pass", et2.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//This piece of code should do the trick
HttpResponse response = client.execute(httppost);
HttpEntity respEntity = response.getEntity();
if (respEntity != null) {
// EntityUtils to get the reponse content
String content = EntityUtils.toString(respEntity);
}
Log.d("valueeeeeeeeeeee", et6.getText().toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
Log.d("exppppppp", "msg");
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("exppppppp", "msg");
}
PHP:
<?php
$host = "localhost";
$user = "user";
$pass = "pass";
$connection = mysql_connect($host,$user,$pass) or die (mysql_errno().": ".mysql_error()."<BR>");
$userid = mysql_real_escape_string($_POST['userid']);
$pass = mysql_real_escape_string($_POST['pass']);
$db_select=mysql_select_db("my_db");
if(!$db_select){
die(mysql_error());
echo "error";
}
$query = "select count(1) as count_users from user_table where user_field = '".$userid."' and pass_field ='".$pass."'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row['count_users']>0)
{
echo "Okey";
}
else
{
echo "Not found";
}
?>
PS: Please dont use the mysql_extension, go for mysqli or PDO instead.
I would recommend doing as you are. Initiate a HTTP post/get request to a PHP page which connects to the MySQL database using mysqli (mysql_query is deprecated). You can then form the result into a JSON response to be passed back and can be easily parsed in android to extract any wanted information. I would recommend these tutorials:
Connect android with PHP and MySql, JSON in android and PHP and MySQLi
I used these tutorials and managed to get what you are trying to do working without too much difficulty.
You can access the passed get variables sent from android using
$_GET['userid'] and $_GET['pass']
and a valid SQL query would be
$query = 'SELECT * FROM '%table_name%' WHERE uname ="'.$_GET['uname'].'" AND pass ="'.$_GET['pass'].'"';
You need to beware though as using unchecked input directly in SQL statements leaves you susceptible to SQL injection attacks and should be avoided if at all possible. For the purposes of investigating and experimenting on a private server you should be okay though. Be aware that that there is are a lot of security issues to consider before distributing software with server connectivity
I am sending some values through HTTP Post to my server from my Android emulator but the values are not being stored. My logcat is showing response code 200 and displaying the codes of the php script as a http response. My database is fine as i am able to insert data in it. Any idea what might be the matter?
main.java
public void sendRegistrationIdToServer(String deviceId,
String registrationId) {
System.out.println(registrationId);
System.out.println(deviceId);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://10.21.78.11/storePost.php?");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
// Get the deviceID
nameValuePairs.add(new BasicNameValuePair("devid", deviceId));
nameValuePairs.add(new BasicNameValuePair("regid",
registrationId));
//HttpProtocolParams.setUseExpectContinue(client.getParams(), false);
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
post.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
System.out.println("HTTP Status = "+status);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
Log.e("HttpResponse", line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
storePost.php
<?php
mysql_connect("localhost", "root", "") or die (mysql_error());
mysql_select_db("DeviceID");
$regid = mysql_real_escape_string($_POST["regid"]);
$devid = mysql_real_escape_string($_POST["devid"]);
mysql_query("INSERT INTO Android(regID, devID) VALUES ('$regid', '$devid')") or die(mysql_error());
mysql_close();
?>
Make sure your web server is configured to run php codes. If you go to storePost.php with your desktop browser and you still see the codes displayed in the browser, then it's a configuration issue with your webserver. Until you fix that, the Android code will still be returning php codes as a response.
If you're on a windows platform, you might want to check this out http://www.simplehelp.net/2008/08/25/how-to-install-and-setup-apache-mysql-and-php-in-windows/
or linux https://help.ubuntu.com/community/ApacheMySQLPHP
Even easier, check xampp out www.apachefriends.org/en/xampp.html
I could really need some help to my project.
I have an android app, that scans for wireless networks. I want to upload this data to a mysql database.
Android have database class:
public class Database {
public static void putServerData(String building, String floor, String room, String address, String signal){
String db_url = "http://**(IP ADDRESS)**/setdata.php";
#SuppressWarnings("unused")
InputStream is = null;
ArrayList<NameValuePair> request = new ArrayList<NameValuePair>();
request.add(new BasicNameValuePair("building",building));
request.add(new BasicNameValuePair("floor",floor));
request.add(new BasicNameValuePair("room",room));
request.add(new BasicNameValuePair("address",address));
request.add(new BasicNameValuePair("signal",signal));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(db_url);
httppost.setEntity(new UrlEncodedFormEntity(request));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
}
}
This is called by:
try {
Database.putServerData(building,floor, room, array1.get(1).toString(), array2.get(2).toString());
} catch (Exception e) {
Log.e("test", "test");
}
The server is a Win7 machine, with apache php and mysql
The setdata.php file:
<?php
$con = mysql_connect("localhost","root","pass");
if(!$con)
{
echo 'Not connected';
echo ' - ';
}else
{
echo 'Connection Established';
echo ' - ';
}
$db = mysql_select_db("android");
if(!$db)
{
echo 'No database selected';
}else
{
echo 'Database selected';
}
$building = $_POST['building'];
$floor = $_POST['floor'];
$room = $_POST['room'];
$ap_mac1 = $_POST['ap_mac1'];
$ap_strength1 = $_POST['ap_strength1'];
$ap_mac2 = $_POST['ap_mac2'];
$ap_strength2 = $_POST['ap_strength2'];
$ap_mac3 = $_POST['ap_mac3'];
$ap_strength3 = $_POST['ap_strength3'];
$ap_mac4 = $_POST['ap_mac4'];
$ap_strength4 = $_POST['ap_strength4'];
$ap_mac5 = $_POST['ap_mac5'];
$ap_strength5 = $_POST['ap_strength5'];
echo ($_POST['building']);
mysql_query("INSERT INTO wifiscan VALUES($nextid, '$building','$floor','$room','$ap_mac1','$ap_strength1','$ap_mac2','$ap_strength2', '$ap_mac3', '$ap_strength3', '$ap_mac4', '$ap_strength4', '$ap_mac5', '$ap_strength5')");
mysql_close(); ?>
This is not working. Im not sure i select the database in the correct way, could that be the problem?
Maybe this isnt so clear and ill will explain it further if you want.
Use some Log and maybe sprintfs to figure out what is exactly going on.
I#d start with the PHP. Try to open the URL from your browser and put some outputs in the PHP to see if everything works fine here. Post your results and you will probably get further help.