hi i am trying to check the username and password from mysql database, where i inserted my password using md5() hashing now i wanna access this username, password. i am getting
"org.json.jsonexception end of input at character 1 of"
error.
this is my php code.
<?php
error_reporting(E_ALL^E_NOTICE^E_WARNING);
$dbhost="localhost";
$dbuser="dev";
$dbpass="dev";
$dbdb="myandroid";
$connect =mysql_connect($dbhost,$dbuser,$dbpass) or die("connection error");
mysql_select_db($dbdb) or die("database selection error");
$username=$_POST["username"];
$password=$_POST["password"];
$pass=md5('$password');
$query=mysql_query("SELECT * FROM androidtable WHERE username='$username' AND password='$pass'")or die(mysql_error());
$num=mysql_num_rows($query);
if($num==1){
while($list=mysql_fetch_assoc($query)){
$output=$list;
echo json_encode($output);
}
mysql_close();
}
?>
the android code
public class DBActivity extends Activity implements OnClickListener{
EditText eduser, edpass;
Button logbutton;
String username, password;
HttpClient httpclient;
HttpPost httppost;
ArrayList<NameValuePair> nameValuePair;
HttpResponse httpresponse;
HttpEntity httpentity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_db);
initialise();
}
private void initialise() {
eduser=(EditText) findViewById(R.id.eduser);
edpass=(EditText) findViewById(R.id.edpass);
logbutton=(Button) findViewById(R.id.login);
logbutton.setOnClickListener(this);
}
public void onClick(View v) {
httpclient=new DefaultHttpClient();
httppost=new HttpPost("http://192.168.1.2/androidtut/check.php");
username=eduser.getText().toString();
password=edpass.getText().toString();
try{
nameValuePair=new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("username", username));
nameValuePair.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
httpresponse=httpclient.execute(httppost);
if(httpresponse.getStatusLine().getStatusCode()==200){
httpentity=httpresponse.getEntity();
if(httpentity != null){
InputStream is=httpentity.getContent();
JSONObject jresp=new JSONObject(convertStreamToString(is));
String retUser=jresp.getString("username");
String retPass=jresp.getString("password");
if(username.equals(retUser) && password.equals(retPass)){
SharedPreferences sp=getSharedPreferences("tableandroid",0);
SharedPreferences.Editor spedit=sp.edit();
spedit.putString("username", username);
spedit.putString("password", password);
spedit.commit();
Toast.makeText(getBaseContext(), "loggin success",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getBaseContext(), "user invalid",Toast.LENGTH_LONG).show();
}
}
}
}catch(Exception e){
String error=e.toString();
Toast.makeText(getBaseContext(), error,Toast.LENGTH_LONG).show();
}
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Your server isn't returning anything. So your Android client has nothing to marshall.
$pass=md5('$password');
Isn't hashing the password, but the $password string literal instead (single quotes don't expand variables). Use the following instead:
$pass=md5($password);
Related
I need to send a string obtained from EditText in android to the PHP to be used as an id to query the database. So, I got the string from EditText as follows:
childIDVal = childID.getText().toString();
Toast.makeText(getApplicationContext(),childIDVal,Toast.LENGTH_LONG).show();
// To do : transfer data to PHP
transferToPhp(childIDVal);
So, what should my transferToPhp() contain? And also the php code is:
<?php
if( isset($_POST["ChildID"]) ) {
$data = json_decode($_POST["ChildID"]);
$data->msg = strrev($data->msg);
echo json_encode($data);
}
Is it okay? I am a newbie to both android and Php, so i need some help right now. Thanks!
I' m offering you to use AsyncTask which reaches PHP file existing in your server using HttpClient:
/*Sending data to PHP and receives success result*/
private class AsyncDataClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(params[0]);
String jsonResults = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
// SENDING PARAMETERS WITH GIVEN NAMES
nameValuePairs.add(new BasicNameValuePair("paramName_1", params[1]));
nameValuePairs.add(new BasicNameValuePair("paramName_2", params[2]));
// ...
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
jsonResults = inputStreamToString(response.getEntity().getContent()).toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonResults;
}
// DO SOMETHING BEFORE PHP RESPONSE
#Override
protected void onPreExecute() {
super.onPreExecute();
}
// DO SOMETHING AFTER PHP RESPONSE
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result.equals("") || result.equals(null)){
return;
}
// Json response from PHP
String jsonResult = returnParsedJsonObject(result);
// i.e.
if (jsonResult.equals("some_response") {
// do something
}
}
// READING ANSWER FROM PHP
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}
// GET ALL RETURNED VALUES FROM PHP
private String returnParsedJsonObject(String result){
JSONObject resultObject;
String returnedResult = "0";
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getString("response");
String value1 = resultObject.getString("value1");
String value2 = resultObject.getString("value2");
//...
// do something with retrieved values
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
To send some parameters use:
AsyncDataClass asyncRequestObject = new AsyncDataClass();
asyncRequestObject.execute("server_url", param1, param2,...);
Hope it helps you.
This is my code for Android:
public void SendDataToServer(final String name, final String email, final String password){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String QuickName = name ;
String QuickEmail = email ;
String QuickPassword = password;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("nome", QuickName));
nameValuePairs.add(new BasicNameValuePair("email", QuickEmail));
nameValuePairs.add(new BasicNameValuePair("password", QuickPassword));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Configs.signup);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "Data Submit Successfully";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d(result, "Value");
try {
JSONObject jo = new JSONObject(result);
String status = jo.optString("status");
if (status.equals("0")) {
Toast.makeText(Signup.this, "Username already exists", Toast.LENGTH_LONG).show();
} else if (status.equals("1")) {
Intent intent = new Intent(Signup.this, Login.class);
startActivity(intent);
Toast.makeText(Signup.this, "Registered successfully", Toast.LENGTH_LONG).show();
Toast.makeText(Signup.this, "Verify your email adress in email received", Toast.LENGTH_SHORT).show();
finish();
} else if (status.equals("2")) {
Toast.makeText(Signup.this, "Failed to Signup", Toast.LENGTH_LONG).show();
}
//}
}catch (JSONException e) {
e.printStackTrace();
}
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, email, password);
}
This is the error:
07-21 12:55:35.297 24973-24973/com.futegolo.igomessenger W/System.err:
org.json.JSONException: Value Data of type java.lang.String cannot be
converted to JSONObject
This is my json response
{"status":0}
This is because you are not returning the actual response from service in doInBackground() method. You are returning as
return "Data Submit Successfully"
And when you convert that string in onPostExecute() method obviously that is not valid JsonObject
Replace your code after this "HttpEntity entity = response.getEntity();"
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
result= convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
And rather returning your hard coded string return result. Hope that helps.
for further reference you can follow below links
https://stackoverflow.com/questions/4457492/how-do-i-use-the-simple-http-client-in-android
Use the code as following:
public void SendDataToServer(final String name, final String email, final String password){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String QuickName = name ;
String QuickEmail = email ;
String QuickPassword = password;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("nome", QuickName));
nameValuePairs.add(new BasicNameValuePair("email", QuickEmail));
nameValuePairs.add(new BasicNameValuePair("password", QuickPassword));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Configs.signup);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
StringBuffer result= new StringBuffer();
BufferedReader in = new BufferedReader(
new InputStreamReader(entity.getContent()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result.append(inputLine);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d(result, "Value");
try {
JSONObject jo = new JSONObject(result);
String status = jo.optString("status");
if (status.equals("0")) {
Toast.makeText(Signup.this, "Username already exists", Toast.LENGTH_LONG).show();
} else if (status.equals("1")) {
Intent intent = new Intent(Signup.this, Login.class);
startActivity(intent);
Toast.makeText(Signup.this, "Registered successfully", Toast.LENGTH_LONG).show();
Toast.makeText(Signup.this, "Verify your email adress in email received", Toast.LENGTH_SHORT).show();
finish();
} else if (status.equals("2")) {
Toast.makeText(Signup.this, "Failed to Signup", Toast.LENGTH_LONG).show();
}
//}
}catch (JSONException e) {
e.printStackTrace();
}
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, email, password);
}
Appache has already provided a Util class for that called EntityUtils.
Replace return "Data Submit Successfully" with this code
String responseText = EntityUtils.toString(httpResponse.getEntity());
EntityUtils.consume(httpResponse.getEntity());
return responseText;
I want to get response after post data but it fails. I want to create a login system, I have successfully submited data to php file, everything is working fine now I want to get response from same function but I'm unable to know where the issue is.
Here is the Java function:
public class PostDataGetRes extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
postRData();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String lenghtOfFile) {
// do stuff after posting data
}
}
public void postRData() {
String result = "";
InputStream isr = null;
final String email = editEmail.getText().toString();
final String pass = editPass.getText().toString();
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://website.com/appservice.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", email));
nameValuePairs.add(new BasicNameValuePair("stringdata", pass));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
resultView.setText("Inserted");
HttpEntity entity = response.getEntity();
isr = entity.getContent();
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
s = s +
"Name : "+json.getString("first_name")+"\n\n";
//"User ID : "+json.getInt("user_id")+"\n"+
//"Name : "+json.getString("first_name")+"\n"+
//"Email : "+json.getString("email")+"\n\n";
}
resultView.setText(s);
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
resultView.setText("Done");
}
And here is php code:
if($id){
$query = mysql_query("SELECT first_name FROM users where email = '$id' ");
while($row=mysql_fetch_assoc($query)){
$selectedData[]=$row;
}
print(json_encode($selectedData));
}
Please help me I have tried so far but could not achieve any results. Please help me how can I get response from php file after query execution.
At first be sure you get correct JSON object from your website - try printing it as Toast.makeText(). As far the web browsers keep the html comments away, android gets it in response.
AsyncTask objects and classes aren't designed to be made the way u provided and also you can't make any UI operations in doInBackground(). AsyncTask is made in a way to not to block GUI.
Here is a not much different example how it uses methods you have in AsyncTask class:
class Logging extends AsyncTask<String,String,Void>{
JSONObject json=null;
String output="";
String log=StringCheck.buildSpaces(login.getText().toString());
String pas=StringCheck.buildSpaces(password.getText().toString());
String url="http://www.mastah.esy.es/webservice/login.php?login="+log+"&pass="+pas;
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "Operation pending, please wait", Toast.LENGTH_SHORT).show();
}
#Override
protected Void doInBackground(String... params) {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
request.addHeader("User-Agent", "User-Agent");
HttpResponse response;
try {
response = client.execute(request);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line="";
StringBuilder result = new StringBuilder();
while ((line = br.readLine()) != null) {
result.append(line);
}
output=result.toString();
} catch (ClientProtocolException e) {
Toast.makeText(getApplicationContext(), "Connection problems", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Conversion problems", Toast.LENGTH_LONG).show();
}
return null;
}
#Override
protected void onPostExecute(Void w) {
try {
json = new JSONObject(output);
if(json.getInt("err")==1){
Toast.makeText(getApplicationContext(), json.getString("msg"), Toast.LENGTH_LONG).show();
}else{
String id_user="-1";
Toast.makeText(getApplicationContext(), json.getString("msg"), Toast.LENGTH_LONG).show();
JSONArray arr = json.getJSONArray("data");
for(int i =0;i<arr.length();i++){
JSONObject o = arr.getJSONObject(i);
id_user = o.getString("id_user");
}
User.getInstance().setName(log);
User.getInstance().setId(Integer.valueOf(id_user));
Intent i = new Intent(getApplicationContext(),Discover.class);
startActivity(i);
}
} catch (JSONException e) {
}
super.onPostExecute(w);
}
}
PHP file content:
$data = array(
'err' => 0,
'msg' => "",
'data' => array(),
);
$mysqli = new MySQLi($dbhost,$dbuser,$dbpass,$dbname);
if($mysqli->connect_errno){
$data['err'] = 1;
$data['msg'] = "Brak polaczenia z baza";
exit(json_encode($data));
}
if(isset($_GET['login']) && isset($_GET['pass'])){
$mysqli->query("SET CHARACTER SET 'utf8';");
$query = $mysqli->query("SELECT banned.id_user FROM banned JOIN user ON user.id_user = banned.id_user WHERE user.login ='{$_GET['login']}' LIMIT 1;");
if($query->num_rows){
$data['err']=1;
$data['msg']="User banned";
exit(json_encode($data));
}else{
$query = $mysqli->query("SELECT login FROM user WHERE login='{$_GET['login']}' LIMIT 1;");
if($query->num_rows){
$query = $mysqli->query("SELECT pass FROM user WHERE pass ='{$_GET['pass']}' LIMIT 1;");
if($query->num_rows){
$data['msg']="Logged IN!";
$query = $mysqli->query("SELECT id_user FROM user WHERE login='{$_GET['login']}' LIMIT 1;");
$data['data'][]=$query->fetch_assoc();
exit(json_encode($data));
}else{
$data['err']=1;
$data['msg']="Wrong login credentials.";
exit(json_encode($data));
}
}else{
$data['err']=1;
$data['msg']="This login doesn't exist.";
exit(json_encode($data));
}
}
}else{
$data['err']=1;
$data['msg']="Wrong login credentials";
exit(json_encode($data));
}
I have created there small dictionary $data for my app. I used its err key as a flag to know if any error appeared, msg to inform user about operation results and data to send JSON objects.
Thing you would want to do with if(response == true) if it had exist is similar to construction i used in my onPostExecute(Void w) method in AsyncTask:
if(json.getInt("err")==1){
//something went wrong
}else{
//everything is okay, get JSON, inform user, start new Activity
}
Also here is the way I used $data['data'] to get JSON response:
if($query->num_rows){
while($res=$query->fetch_assoc()){
$data['data'][]=$res;
}
exit(json_encode($data));
}
I am making an app which performs a transaction through a PHP script stored in the www folder of Wampserver of localhost.
But when I perform the transaction values are not inserted into the database and logcat displays this error:
07-26 16:55:54.036: E/Buffer Error(5511): Error converting result java.lang.NullPointerException
07-26 16:55:54.037: E/JSON Parser(5511): Error parsing data org.json.JSONException: End of input at character 0 of
But my app does not even crash and says the transaction is successful, which is called onPostExecute of my AsyncTask.
Please help me found out the bug that is causing unsuccessful insertion into the database.
I have two classes JSONParser and NewProductActivity as follows:
This one is NewProductActivity.java:
public class NewProductActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
// url to create new product use wireless lan adapter wifi ipv4 address using ipconfig
// String url_create_product = "http://192.168.0.100/toll_system/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
String first_name;
String last_name;
String toll_no;
String toll_location;
String trans_amt;
String v_license_no;
String make_model;
String v_type;
String email_id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
TextView tv=(TextView)findViewById(R.id.textView1);
String contents = getIntent().getStringExtra("KEY1");
String ip_address=getIntent().getStringExtra("KEY2");
/* String arr[]=contents.split(",");
String trans_receipt_no=arr[0];
String firstname=arr[1];
String lastname=arr[2];
String toll_no=arr[3];
String toll_location=arr[4];
String trans_amt=arr[5];
String v_license_no=arr[6];
String make_model=arr[7];
String v_type=arr[8];*/
Toast toast = Toast.makeText(this, "Content:" + contents , Toast.LENGTH_LONG);
toast.show();
new CreateNewProduct().execute(contents,ip_address);
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Woooohoooo...");
Log.d("Perform:", "Performing");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
// String name = inputName.getText().toString();
// String price = inputPrice.getText().toString();
// String description = inputDesc.getText().toString();
String contents=args[0];
String ip_address=args[1];
String arr[]=contents.split(",");
Log.d("Inside doInBackground :", contents);
//String trans_receipt_no=arr[0];
first_name=arr[0];
Log.d("First_name", first_name);
last_name=arr[1];
Log.d("Last_name", last_name);
toll_no=arr[2];
toll_location=arr[3];
trans_amt=arr[4];
v_license_no=arr[5];
make_model=arr[6];
v_type=arr[7];
email_id=arr[8];
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair("name", name));
//params.add(new BasicNameValuePair("price", price));
//params.add(new BasicNameValuePair("description", description));
// params.add(new BasicNameValuePair("trans_receipt_no", trans_receipt_no));
params.add(new BasicNameValuePair("first_name", first_name));
params.add(new BasicNameValuePair("last_name", last_name));
params.add(new BasicNameValuePair("toll_no", toll_no));
params.add(new BasicNameValuePair("toll_location", toll_location));
params.add(new BasicNameValuePair("trans_amount", trans_amt));
params.add(new BasicNameValuePair("v_license_no", v_license_no));
params.add(new BasicNameValuePair("v_make_model", make_model));
params.add(new BasicNameValuePair("v_type", v_type));
params.add(new BasicNameValuePair("email_id", email_id));
// getting JSON Object
String url_create_product = "http://"+ip_address+"/toll_system/create_product.php";
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"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 product
// Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
//startActivity(i);
String s="Transaction done!";
Toast toast = Toast.makeText(getApplicationContext(),"Status:"+s, Toast.LENGTH_LONG);
toast.show();
// closing this screen
finish();
} else {
Toast toast = Toast.makeText(getApplicationContext(),"Status:Failed", Toast.LENGTH_LONG);
toast.show();
// failed to create product
}
} 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
TextView tv=(TextView)findViewById(R.id.textView1);
tv.setText("Transaction done!!!");
TextView tv1=(TextView)findViewById(R.id.textView3);
tv1.setText(first_name+" "+last_name);
TextView tv2=(TextView)findViewById(R.id.textView5);
tv2.setText(make_model);
TextView tv3=(TextView)findViewById(R.id.textView7);
tv3.setText(v_license_no);
TextView tv4=(TextView)findViewById(R.id.textView9);
tv4.setText("Rs."+trans_amt);
pDialog.dismiss();
}
}
}
And this is JSONParser:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public 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;
while ((line = reader.readLine()) != null) {
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;
}
}
I am trying to insert data from android to MySQL but it does not show any error in logcat but displays the json message in the app.
Here is my PHP script.
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
require("config.inc.php");
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['userName']) && isset($_POST['userContact']) && isset($_POST['userAddress']) && isset($_POST['userStore']) && isset($_POST['userRequest'])) {
$userName = $_POST['userName'];
$userContact = $_POST['userContact'];
$userAddress = $_POST['userAddress'];
$userStore = $_POST['userStore'];
$userRequest = $_POST['userRequest'];
// mysql inserting a new row
$result = mysql_query("INSERT INTO userrequests(userName, contactNumber, userAddress, storeList, requestBody) VALUES('$userName', '$userContact', '$userAddress', '$userStore', '$userRequest')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "IsitdispllayingthusOops! An error occurred.";
// echoing JSON response
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);
}
?>
Here is my JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
Log.i("log_tag","Line reads: " + line);
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to 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 the JSON Object.
return jObj;
}
// function get json from url
// by making HTTP POST or GET mehtod
public 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, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
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;
}
}
Here is my MainActivity.java
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private EditText userName, userContact, userAddress, userRequest;
private Spinner userStore;
private Button mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script
//localhost :
//testing on your device
//put your local ip instead, on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/register.php";
//testing on Emulator:
private static final String LOGIN_URL = "http://10.0.2.2/callarocket/register.php";
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/register.php";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner dropdown = (Spinner)findViewById(R.id.StoreSpinner);
String[] items = new String[]{"NZ Mamak", "Indo Shop", "NZ Supermarket"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
dropdown.setAdapter(adapter);
userName = (EditText)findViewById(R.id.EditName);
userContact = (EditText)findViewById(R.id.EditContact);
userAddress = (EditText)findViewById(R.id.EditAddress);
userStore = (Spinner)findViewById(R.id.StoreSpinner);
userRequest = (EditText)findViewById(R.id.EditRequest);
mRegister = (Button)findViewById(R.id.SubmitButton);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Creating Request...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = userName.getText().toString();
String usercontact = userContact.getText().toString();
String useraddress = userAddress.getText().toString();
String userstore = userStore.getSelectedItem().toString();
String userrequest = userRequest.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userName", username));
params.add(new BasicNameValuePair("userContact", usercontact));
params.add(new BasicNameValuePair("userAddress", useraddress));
params.add(new BasicNameValuePair("userStore", userstore));
params.add(new BasicNameValuePair("userRequest", userrequest));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// full json response
Log.d("Login attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} 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 product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
And the error I am getting inside the emulator is this json message in my php script
$response["message"] = "IsitdispllayingthusOops! An error occurred.";
I couldn't find the reason why new row cannot be inserted into MySQL.
POST can not be used by external applications. You have to use GET instead.