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.
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 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);
?>
I need to delete an item from a list view on android when clicked. The thing is, my table is not on the phone(SQLite), but on the server. So I'm using a PHP code for this.
I have set up an onClickListener.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v,int position, long id) {
Show_Alert_box(v.getContext(),
"Please select action.", position);
}
});
public void Show_Alert_box(Context context, String message, int position) {
final int pos = position;
final AlertDialog alertDialog = new AlertDialog.Builder(context)
.create();
//alertDialog.setTitle(getString(R.string.app_name_for_alert_Dialog));
alertDialog.setButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
DBHandlerComments dbhelper = new DBHandlerComments(Comments.this);
SQLiteDatabase db = dbhelper.getWritableDatabase();
try{
JSONObject json2 = JSONParser.makeHttpRequest(urlDelete, "POST", params);
try {
int success = json2.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about product update
setResult(100, i);
finish();
} else {
// failed to update product
}
} catch (JSONException e) {
e.printStackTrace();
}
//adapter.notifyDataSetChanged();
db.close();
}catch(Exception e){
}
}
});
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.setMessage(message);
alertDialog.show();
}
This is my JSONParser's makehttprequest code:
public static JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
//from here
while ((line = reader.readLine()) != null) {
if(!line.startsWith("<", 0)){
if(!line.startsWith("(", 0)){
sb.append(line + "\n");
}
}
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
`
And this is my PHP code:
$response = array();
if (isset($_POST['id'])) {
$id = $_POST['id'];
// include db connect class
$db = mysql_connect("localhost","tbl","password");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("shareity",$db);
// mysql update row with matched id
$result = mysql_query("DELETE FROM comments_activities WHERE id = $id");
// check if row deleted or not
if (mysql_affected_rows() > 0) {
// successfully updated
$response["success"] = 1;
$response["message"] = "Product successfully deleted";
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
I'm adding the params like this:
params.add(new BasicNameValuePair(KEY_ID, id));
params.add(new BasicNameValuePair(KEY_AID, aid));
params.add(new BasicNameValuePair(KEY_ANAME, an));
params.add(new BasicNameValuePair(KEY_EVENT, ev));
params.add(new BasicNameValuePair(KEY_COMMENT, cb));
params.add(new BasicNameValuePair(KEY_USER, cby));
params.add(new BasicNameValuePair(KEY_TIME, cd));
I don't get any result. Can I know why?
I have noticed that you add unneeded parameters although you just need the id.
This is a simple code for deleting the given id, you can try it. If it worked, the error would be in your android code.
<?php
$servername = "your servername";
$username = "your username";
$password = "your password";
$dbname = "your dbname";
$link = mysql_connect($servername, $username, $password);
mysql_select_db($dbname, $link);
$id=$_POST['id'];
$result = mysql_query("DELETE FROM table_name WHERE id=$id", $link);
$response["success"] = 1;
$response["message"] = "Deleted successfully!";
echo json_encode($response);
?>
Change the servername to your database url and so on the other information.
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);