I am trying to do a simple insert from an Android application. I can run my php script from the browser by concatenating ?entry="Sample value from browser", but when I run the application from Android, I get no insert.
Here is where I am calling the insert class that uses JSON and implements AsyncTask:
package us.jtaylorok.android.sqlite.first;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
public class RemoteInsert extends AsyncTask<Void, String,String >{
protected String TAG;
protected Context context;
protected String input;
protected ProgressDialog progressDialog;
public RemoteInsert(String i,Context c){
this.input = i;
this.context = c;
}
protected void onPreExecute() {
//ProgressDialog progressDialog; // = new ProgressDialog(context);
//progressDialog=ProgressDialog.show(,"Please Wait..","Sending data to database", false);
progressDialog=ProgressDialog.show(context,"Please Wait..","Sending data to database", false);
}
#Override
protected String doInBackground(Void... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
//HttpPost httppost = new HttpPost("http://localhost/index.php");
//HttpPost httppost = new HttpPost("http://10.253.8.88/patient_data/patient_data.php");
HttpPost httppost = new HttpPost("http://10.100.205.72/patient_data/patient_data.php");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("entry", "Input from Android"));
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
Log.i("postData", response.getStatusLine().toString());
} catch(Exception e) {
Log.e(TAG, "Error: "+e.toString());
}
return "";
}
protected void onPostExecute(String result) {
progressDialog.dismiss();
Toast.makeText(context, "Finished", Toast.LENGTH_LONG).show();
}
}
And here is my PHP script:
<?php
// mysql_connect("host","username","password");
mysql_connect("localhost","user1","mypassword");
mysql_select_db("test");
$entry_value = $_REQUEST["entry"];
$query = "INSERT INTO patientdata (entry) values (".$entry_value.");";
if( !mysql_query($query) ) {
/*insert failed*/
}
mysql_close();
?>
Again, this works perfectly if I call it from the browser, but it throws an exception before implementing AsyncTask.
I do get the AVD to display the add and remove, but when I do that there is no request in my apache2 access_log or error_log. Any suggestions?
I think you have stored php script on local server. So use this 10.0.2.2 while initializing HttpPost instead of your machine's ip address. Its localhost equivalent in android Virtual device.
That was not the issue for this particular problem. The issue was a magic quotes setting in the php.ini
Related
I have created REST web service using jersey which returns JSON response. JSON response returned by web service is as follow-
{
"Disease": "Bacterial_blight",
"Control": "Foliar sprays of streptocycline sulphate # 0.5 gm/land copper-oxychlode # 3 g / l of water as and when symptoms seen."
}
I have made Android app activity for demo purpose which contains one radio button, one Edit text box and one Button to submit the parameters to REST web service. But Problem is I'm getting force close when I try to click on Submit Button.
This is the actual android activity class code-
package com.doitgeek.agroadvisorysystem;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
public class DiseaseResultActivity extends AppCompatActivity {
public TextView diseaseTV;
public TextView controlMechanismTV;
public EditText etSymptom;
public RadioButton rbL;
public Button btnSubmit;
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_disease_result);
diseaseTV = (TextView)findViewById(R.id.diseaseTV);
controlMechanismTV = (TextView)findViewById(R.id.controlMechanismTV);
etSymptom = (EditText)findViewById(R.id.etSymptom);
rbL = (RadioButton)findViewById(R.id.rbL1);
btnSubmit = (Button)findViewById(R.id.btnSubmit);
}
public void onClickSubmit(View view) {
RequestParams params = new RequestParams();
String affectedPart = rbL.getText().toString();
String symptom = etSymptom.getText().toString();
params.put("affectedPart", affectedPart);
params.put("symptom", symptom);
invokeWS(params);
}
/* Invocation of RESTful WS */
public void invokeWS(RequestParams params) {
dialog.show();
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://192.168.0.100:8080/AgroAdvisorySystem/webapi/disease_prediction/result", params, new AsyncHttpResponseHandler(){
#Override
public void onSuccess(String response) {
dialog.hide();
try {
JSONObject obj = (JSONObject)new JSONTokener(response.toString()).nextValue();
JSONObject obj2 = obj.getJSONObject("Disease");
String disease = obj2.toString();
/*JSONObject obj = new JSONObject(response);
String disease = obj.getJSONObject("Disease").toString();*/
diseaseTV.setText(disease);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error Occurred [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
dialog.hide();
if(statusCode == 404) {
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
} else if(statusCode == 500) {
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unexpected Error occurred! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
}
}
});
}
}
I didn't find working solution till now that is why I am posting this as question.
So, what`s the Exception record?
It seems that the problem is in:
JSONObject obj2 = obj.getJSONObject("Disease");
where the item Disease is no longer a JSONObject.
Try obj.getSyting("Disease")
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 8 years ago.
Hi i want to fetch the selected column from mysql by matching one column name i.e
"select column_name from day where date='$date'"
But it is giving me serious error , i have check the connectivity issues they are fine , i think there is some problem in code please help me
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;
public class Day extends Activity {
String dt="";
String mc="";
String bc="";
ImageView dateimg;
String name;
String date;
InputStream is=null;
String result=null;
String line=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.day_lay);
getCurrDate();
select();
dateimg = (ImageView) findViewById(R.id.img);
dateimg.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
//getCurrDate();
}
});
}
public String getCurrDate()
{
Date cal = Calendar.getInstance().getTime();
dt = cal.toLocaleString();
mc = dt.substring(0, dt.length() - 17);
bc=mc.substring(4);
System.out.println("Date is"+bc);
date=bc;
return dt;
}
public void select()
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("date",date));
try
{
HttpClient httpclient = new DefaultHttpClient()
HttpPost httppost = new HttpPost("http://192.168.1.1/wpcontent/themes/app/day.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);
name=(json_data.getString("name"));
Toast.makeText(getBaseContext(), "Name : "+name,
Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
System.out.println("Got Value"+name);
}
}
// Database select
<?php
$host='127.0.0.1';
$uname='root';
$pwd='password';
$db="android";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$date=$_REQUEST['date'];
$r=mysql_query("select mat from vicks where date='$date'",$con);
while($row=mysql_fetch_array($r))
{
$flag[name]=$row[name];
}
print(json_encode($flag));
mysql_close($con);
?>
//Logcat
05-08 14:04:34.938: I/dalvikvm-heap(995): Grow heap (frag case) to 54.839MB for 2312016-byte allocation
05-08 14:04:35.218: D/dalvikvm(995): GC_CONCURRENT freed 1K, 4% free 56085K/58055K, paused 11ms+23ms
05-08 14:04:35.758: D/dalvikvm(995): GC_FOR_ALLOC freed 564K, 4% free 56086K/58055K, paused 172ms
05-08 14:04:35.788: I/dalvikvm-heap(995): Grow heap (frag case) to 57.044MB for 2312016-byte allocation
05-08 14:04:36.538: D/dalvikvm(995): GC_CONCURRENT freed <1K, 4% free 58344K/60359K, paused 11ms+98ms
05-08 14:08:30.258: I/System.out(995): Date is8
05-08 14:08:30.298: E/Fail 1(995): android.os.NetworkOnMainThreadException
05-08 14:08:30.338: E/Fail 2(995): java.lang.NullPointerException
05-08 14:08:30.338: E/Fail 3(995): java.lang.NullPointerException
05-08 14:08:30.338: I/System.out(995): Got valuenull
This is not about connectivity. This is about handling network activity on the main thread.
You can either disable that warning (which is bad practice) or perform that task in a separate thread.
A common Android pattern is using an AsyncTask for that.
The AsyncTask class uses three paramters in its constructor: params, progress, result. In your case they can all be null if you only need to run something in the background.
private class DatabaseTask extends AsyncTask<void, void, void>
{
protected void doInBackground(Void... params)
{
// YOUR DB CODE
}
}
And execute like this:
new DatabaseTask().execute();
Or, you can change the first void to whatever type you need if you want to use input parameters. Read more here.
I am trying to do the session handling process in android.
Here I have successfully logged into through android and now i waant to handle the session of the logged in user.
this is my login_suer.java(android part)
package com.iwantnew.www;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class login_user extends Activity{
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText login_email;
EditText login_password;
Button signin;
TextView error_msg;
private static String url_create_signin= "http://10.0.2.2/android_iwant/login_user.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_form);
// Edit Text
login_email = (EditText) findViewById(R.id.login_email);
login_password = (EditText) findViewById(R.id.login_password);
signin = (Button) findViewById(R.id.signin);
error_msg = (TextView) findViewById(R.id.error_msg);
signin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CheckLogin().execute();
}
});
}
class CheckLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(login_user.this);
pDialog.setMessage("Signing in..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
//Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email",login_email.getText().toString()));
params.add(new BasicNameValuePair("password", login_password.getText().toString()));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_signin,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created users
Intent i = new Intent(getApplicationContext(), post_item.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to sign in
error_msg.setText("Incorrect username/password");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
now i need the idea to start session handling in this java file.
and the code of the server side is below: ie login_user.php
<?php
session_start();
// array for JSON response
$response = array();
if(isset($_POST['email']) && isset($_POST['password'])){
$email = $_POST['email'];
$password = $_POST['password'];
// include db handler
require_once 'DB_Functions.php';
$db = new DB_Functions();
$user = $db->getUesrByEmailAndPassword($email, $password);
if ($user != false) {
// user found
// echo json with success = 1
$response["success"] = 1;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
}
?>
the function used in this above php file is i.e getUesrByEmailAndPassword($email, $password)
is below :
public function getUserByEmailAndPassword($email, $password) {
$result = mysql_query("SELECT * FROM users WHERE email = '$email'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
$salt = $result['salt'];
$encrypted_password = $result['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
//return $result;
session_start();
$_SESSION['clientId'] = $result[0];
$_SESSION['logged_in'] = TRUE;
}
} else {
// user not found
return false;
}
}
Please help me to make my code working.
Any help will be appreciated.
Any link containing such problem solution can be helpful for me. thank you!
As far as I can see, your getUserByEmailAndPassword() never returns actual user data after successfull password check. //return $result; is commented out. $user is therefore null, and client receives "Incorrect email or password!" message.
Another thing. For PHP sessions to work, client has to receive and remember its session_id and send it with every request as GET or COOKIE parameter. Looking at your code, I don't see android receiving its session_id. See: http://www.php.net/manual/en/session.idpassing.php
By the way, using unescaped $email in your SQL query directly from POST is a bad idea. See: How can I prevent SQL injection in PHP?
I am trying to do a very simple POST from an android application to a php script that will update a database. Unfortunately, this is giving me a debugger error (eclipse) on line 52. Below is the code:
package com.example.testhttppost;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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;
}
public void updateDiscountTable(View view)
{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.test.com/jsonpost.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("shop", "ZARA"));
nameValuePairs.add(new BasicNameValuePair("discount", "20%"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost); //Line 52
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
and the PHP script is:
<?php
// PHP variable to store the host address
$db_host = "localhost";
// PHP variable to store the username
$db_uid = "dsdsdsv_android";
// PHP variable to store the password
$db_pass = "test1234";
// PHP variable to store the Database name
$db_name = "dsdsdsv_android";
// PHP variable to store the result of the PHP function 'mysql_connect()' which establishes the PHP & MySQL connection
$db_con = mysql_connect($db_host,$db_uid,$db_pass) or die('could not connect');
mysql_select_db($db_name);
$shopId = $_POST['id'];
$shopName = $_POST['shop'];
$discount = $_POST['discount'];
mysql_query("insert into discounts(id, shop, discount) values ($shopId, $shopName, $discount)");
// mysql_query("insert into discounts(id, shop, discount)values(121, 'sadsdas','dasdasdsa')");
?>
The interface of the application is nothing but a button. This button is linked with the method above defined updateDiscountTable. Thanks and looking forward to replies.
You are performing networking operations on the main application thread probably. You need to move this to a background thread. You can use Asynctask.
You need to Keep your app responsive.
I apologize as this might be a very basic question. when i execute this code, the query in the php file is getting executed twice. This is because once the http client is executed and assigned to http response variable and second time to get the data from the php file .
please see the highlighted code.
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class NfcRegisterationActivity extends Activity {
/** Called when the activity is first created. */
TextView t;
Button submit;
EditText name,address, email,phone;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t=(TextView)findViewById(R.id.textView2);
name =(EditText)findViewById(R.id.name);
address=(EditText)findViewById(R.id.address);
email=(EditText)findViewById(R.id.email);
phone =(EditText)findViewById(R.id.phone);
submit =(Button)findViewById(R.id.submit);
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://10.0.2.2/customersInsert.php");
nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("name", name.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("phone",phone.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("email", email.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("address", address.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String res = httpclient.execute(httppost, responseHandler);
t.setText("Response from PHP :"+ res);
}catch (Exception e) {
// TODO: handle exception
System.out.println("Exception : " + e.getMessage());
}
}
});
}
}
Have you considered the following?:
response=httpclient.execute(httppost);
ResponseHandler responseHandler = new BasicResponseHandler();
String res = responseHandler.handleResponse(response);
t.setText("Response from PHP :"+ res);
No need to call the execute function twice when you can declare your handler and call it's handleResponse function. Not sure why you need two variables if you're just trying to get the response text as a string. If you only need the response as text, you could do:
ResponseHandler responseHandler = new BasicResponseHandler();
String res = httpclient.execute(httppost, responseHandler);
t.setText("Response from PHP :"+ res);
According to the HttpClient documentation, if the the execute function is provided with a response handler it will return the response as the data type returned by the response handler.
Hope this helps.