I got this code. But I got errors because I think some of them are deprecated. All I want to happen is when the button "send" is clicked it will send the location of the user to mysql.
This is the android side.
public void onCreate(Bundle savedInstanceState) {
Button insert=(Button) findViewById(R.id.button1);
insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(gps.canGetLocation()){
lat = (float) gps.getLatitude();
lng = (float) gps.getLatitude();
lat2= Float.toString(lat);
lng2= Float.toString(lng);
insert();
Toast.makeText(getApplicationContext(), "Success insert - \nLat: " + lat2 + "\nLong: " + lng2, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}});
}
public void insert() {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("lat2", lat2));
nameValuePairs.add(new BasicNameValuePair("lng2", lng2));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://monds.com/example.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
try {
JSONObject json_data = new JSONObject(result);
code = (json_data.getInt("code"));
if (code == 1) {
Toast.makeText(getBaseContext(), "Inserted Successfully",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Sorry, Try Again",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e("Fail 3", e.toString());
}
}
}
And this is the php file where I send the lat and lng to my database.
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$lat2=(isset($_REQUEST['lat']) ? $_REQUEST['lat'] : '');
$lng2=(isset($_REQUEST['lng']) ? $_REQUEST['lng'] : '');
//$lat2=$_REQUEST['lat'];
//$lng2=$_REQUEST['lng'];
var_dump($lat2);
$flag['code']=0;
if($r=mysql_query("insert into markers_awal values('','$lat2','$lng2') ",$con))
{
$flag['code']=1;
echo"hi";
}
print(json_encode($flag));
mysql_close($con);
?>
Related
Data is not inserting in MySql from android there is no error in the code, i have defined them using AsyncThread - doInBackground and onPostExecute..Its showing the toast what i have defined in Json Object Try Catch Method 'Sorry Try Again' in else condition if data is not inserted.
InputStream is = null;
String res = null;
String line = null;
int code;
onClick Code
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
question = addque.getText().toString();
choice1 = addc1.getText().toString();
choice2 = addc2.getText().toString();
choice3 = addc3.getText().toString();
answer = addanswer.getText().toString();
Explanation = addexplan.getText().toString();
AsyncTaskRunner Class
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
ArrayList<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("question", question));
nameValuePairs.add(new BasicNameValuePair("choice1", choice1));
nameValuePairs.add(new BasicNameValuePair("choice2", choice2));
nameValuePairs.add(new BasicNameValuePair("choice3", choice3));
nameValuePairs.add(new BasicNameValuePair("answer", answer));
nameValuePairs.add(new BasicNameValuePair("Explanation",
Explanation));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://192.168.43.4/insert/insert.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
}
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
res = sb.toString();
Log.e("pass 2", "connection success ");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try
{
JSONObject json_data;
json_data = new JSONObject(res);
code = json_data.getInt("code");
if(code==1)
{
Toast.makeText(getActivity(), "Inserted Successfully",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getActivity(), "Sorry, Try Again",
Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
}
PHP Code
<?php
$host='localhost';
$uname='root';
$pwd='';
$db="quizDB";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$question=$_REQUEST['question'];
$choice1=$_REQUEST['choice1'];
$choice2=$_REQUEST['choice2'];
$choice3=$_REQUEST['choice3'];
$answer=$_REQUEST['answer'];
$Explanation=$_REQUEST['Explanation'];
$flag['code']=0;
if($r=mysql_query("insert into quizquestion values('$question','$choice1',
$choice2, '$choice3', '$answer', '$Explanation') ",$con))
{
$flag['code']=1;
echo"hi";
}
print(json_encode($flag));
mysql_close($con);
?>
Correct me if i am wrong.
first get all string you want to insert and then call AsyncTask. may be this solve .
question = addque.getText().toString();
choice1 = addc1.getText().toString();
choice2 = addc2.getText().toString();
choice3 = addc3.getText().toString();
answer = addanswer.getText().toString();
Explanation = addexplan.getText().toString();
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
and also change this 2 line . pass UTF-8 to UrlEncodeFormEntity
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
httppost.setEntity(formEntity);
Edited
I think you forget to add concatination onto $choice2 , and change query like this. pass first fieldName and then Values.
$sql = "INSERT INTO MyGuests (fieldName1, fieldName2, fieldName3,fieldName4,fieldName5,fieldName6)
VALUES ('$question','$choice1','$choice2', '$choice3', '$answer', '$Explanation')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
$flag['code']=1;
echo"hi";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
I´m having a problem with this string: "Não Vou". It means "I don´t go". I´m trying to insert it into database with php/json file.
When I remove blank space and ~ accent it works fine.
What I have tried:
changed iso-8859-1 to utf-8;
changed eclipse encoding to utf-8;
changed print(json_encode($flag)) to print(json_encode('utf8_encode', $flag));
Have read similar posts but any of them helped me.
public class insertNo extends AsyncTask<String, Boolean, Boolean>{
#Override
protected Boolean doInBackground(String... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("e_id", subString));
nameValuePairs.add(new BasicNameValuePair("Não Vou", no));
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://mywebsite.com/includes/insert_counter.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
inputStream = entity.getContent();
Log.e("pass 1", "connection success");
}catch(Exception e){
Log.e("Fail 1", e.toString());
Log.e("Invalid IP", e.toString());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
inputStream.close();
result = stringBuilder.toString();
Log.e("pass 2", "connection success");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
try {
JSONObject json_data = new JSONObject(result);
code = (json_data.getInt("code"));
if (code==1) {
Log.d("Insert success", result);
} else {
Log.d("Sorry son", result);
}
} catch (Exception e) {
Log.e("Fail 3", e.toString());
}
return null;
}
}
php file
include_once("db_connect.php");
$e_id = $_REQUEST["e_id"];
$yes = $_REQUEST["Vou"];
$no = $_REQUEST["Não Vou"];
$maybe = $_REQUEST["Talvez"];
$flag['code']=0;
if(isset($yes)){
$r = mysqli_query($mysqli, "UPDATE table1 SET yes = yes + 1 WHERE id='$e_id'");
$flag['code']=1;
}else if(isset($no)){
$r = mysqli_query($mysqli, "UPDATE table1 SET no = no + 1 WHERE id='$e_id'");
$flag['code']=1;
}else if(isset($maybe)){
$r = mysqli_query($mysqli, "UPDATE table1 SET maybe = maybe + 1 WHERE id='$e_id'");
$flag['code']=1;
}
print(json_encode($flag));
mysqli_close($mysqli);
From the documentation, PHP variables should not contain special characters, or spaces, or anything out of
a letter is a-z, A-Z, and the bytes from 127 through 255 (0x7f-0xff).
A simple android application. This application can get coordinate of user location and sending lat and long to mysql. This is my android code :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
Button insert=(Button) findViewById(R.id.btnShowLocation);
insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
// TODO Auto-generated method stub
if(gps.canGetLocation()){
lat = (float) gps.getLatitude();
lng = (float) gps.getLongitude();
lat2= Float.toString(lat);
lng2= Float.toString(lng);
insert();
Toast.makeText(getApplicationContext(), "Success insert - \nLat: " + lat2 + "\nLong: " + lng2, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
}
public void insert() {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("lat2", lat2));
nameValuePairs.add(new BasicNameValuePair("lng2", lng2));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.56.1/rute2/insert_android.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
try {
JSONObject json_data = new JSONObject(result);
code = (json_data.getInt("code"));
if (code == 1) {
Toast.makeText(getBaseContext(), "Inserted Successfully",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Sorry, Try Again",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e("Fail 3", e.toString());
}
}
and this is table marker_awal
this is my php file
<?php
$host='localhost';
$uname='root';
$pwd='';
$db="test";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$lat2=(isset($_REQUEST['lat2']) ? $_REQUEST['lat2'] : '');
$lng2=(isset($_REQUEST['lng2']) ? $_REQUEST['lng2'] : '');
//$lat2=$_REQUEST['lat'];
//$lng2=$_REQUEST['lng'];
var_dump($lat2);
$flag['code']=0;
if($r=mysql_query("insert into markers_awal values('','$lat2','$lng2','') ",$con))
{
$flag['code']=1;
echo"hi";
}
print(json_encode($flag));
mysql_close($con);
?>
I got no error in my application but it can`t insert to database.
xxxI am trying to insert data in mysql database from my Android app using php file. I don´t know what I am doing wrong, here is my android code:
public void insert()
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("nick",nick));
nameValuePairs.add(new BasicNameValuePair("minuto",minuto));
nameValuePairs.add(new BasicNameValuePair("id_pelicula",String.valueOf(id_pelicula)));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxxx.xxxxx.com/xxxx/insertar.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
if(code==1)
{
Toast.makeText(getBaseContext(), "Opinión enviada correctamente",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Disculpe, inténtelo de nuevo",
Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
and here is my php file code:
<?php
// Connection data
$host = 'xxx.xxx.com';;
$uname = 'uxxxx';
$pwd = 'xxxxx';
$db = 'xxxxx';
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$nick=$_REQUEST['nick'];
$minuto=$_REQUEST['minuto'];
$id_pelicula=$_REQUEST['id_pelicula'];
$flag['code']=0;
if($r=mysql_query("insert into opiniones values('$nick','$minuto','$id_pelicula') ",$con))
{
$flag['code']=1;
echo"hi";
}
print(json_encode($flag));
mysql_close($con);
?>
Perhaps is because in my mysql database the "minuto" variable is integer and I use like String from android? Please somebody can help me? Thank you so much
I have solved, I had an error in the php file in this sentence:
if($r=mysql_query("insert into opiniones (nick, minuto, id_pelicula) values('$nick','$minuto','$id_pelicula') ",$con))
im trying to find a way to post username and password using json rather than normal http post that im currently using. i have being going through most of the tutorials and examples to undestand but yet i was unable to get an idea. i have json phasers available to get the data from my sql but not the post json.
thank you for the help
following is the currently used json post
EditText uname = (EditText) findViewById(R.id.log_Eu_name);
String username = uname.getText().toString();
EditText pword = (EditText) findViewById(R.id.log_Epass);
String password = pword.getText().toString();
String result = new String();
result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs
.add(new BasicNameValuePair("username", username));
nameValuePairs
.add(new BasicNameValuePair("password", password));
InputStream is = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.loshwickphotography.com/log.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.w("SENCIDE", "Execute HTTP Post Request");
String str = inputStreamToString(
response.getEntity().getContent()).toString();
Log.w("SENCIDE", str);
if (str.toString().equalsIgnoreCase("true")) {
Log.w("SENCIDE", "TRUE");
Toast.makeText(getApplicationContext(),
"FUking hell yeh!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"Sorry it failed", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
if (result != null) {
JSONArray jArray = new JSONArray(result);
Log.i("log_tag", Integer.toString(jArray.length()));
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
}
} else {
Toast.makeText(getApplicationContext(), "NULL",
Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
private Object inputStreamToString(InputStream is) {
// TODO Auto-generated method stub
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(
new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
});
Is this correct which i have written?
how to write the Php for this?
use this
JSONObject myjson=new JSONObject();
myjson.put("userName", "someOne");
myjson.put("password", "123");
and StringEntity se = new StringEntity(myjson.toString());
and httpPost.setEntity(se);