I am having a problem with the connection to my PHP script, it keeps on returning "Oops! Its this one." - which is my error message if it could not inset into the mySQL database.
///PHP SCRIPT
<?php
$con = mysqli_connect("postgrad.nmmu.ac.za", "Christian", "Christian123", "drmdb");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// array for JSON response
$response = array();
$PointerID = $_POST['PointerID'];
$ActivityID = $_POST['ActivityID'];
$StartX = $_POST['StartX'];
$EndX = $_POST['EndX'];
$StartY = $_POST['StartY'];
$EndY = $_POST['EndY'];
$Content = $_POST['Content'];
$Head = $_POST['Head'];
$NodeID = $_POST['NodeID'];
$Step = $_POST['Step'];
$result = mysqli_query(
$con,
"INSERT INTO pointersequence(PointerID, ActivityID, StartX, StartY, EndX, EndY, Content, Head, NodeID, Step) VALUES('$PointerID','$ActivityID', '$StartX', '$StartY', '$EndX', '$Content', '$Head', '$NodeID', '$Step')"
);
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Person successfully created hahaha.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! Its this one.";
// echoing JSON response
echo json_encode($response);
}
mysql_close($con);
?>
OUTPUT: Oops! Its this one.
//Method in Android to Insert
private void UploadPointerSequence() {
int num11 = 1;
final String URL12 = "http://drm.csdev.nmmu.ac.za/UploadPointerSequence.php";
for (int x = 0; x <= PointerSequence.size() - 1; x++) {
List<NameValuePair> param12 = new ArrayList<NameValuePair>();
param12.add(new BasicNameValuePair("PointerID", String
.valueOf(num11)));
num11++;
param12.add(new BasicNameValuePair("ActivityID", String
.valueOf(PointerSequence.get(x).getActivityID())));
param12.add(new BasicNameValuePair("StartX", String
.valueOf(PointerSequence.get(x).getStartX())));
param12.add(new BasicNameValuePair("StartY", String
.valueOf(PointerSequence.get(x).getStartY())));
param12.add(new BasicNameValuePair("EndX", String
.valueOf(PointerSequence.get(x).getEndX())));
param12.add(new BasicNameValuePair("EndY", String
.valueOf(PointerSequence.get(x).getEndY())));
param12.add(new BasicNameValuePair("Content", PointerSequence
.get(x).getContent()));
param12.add(new BasicNameValuePair("Head", String
.valueOf(PointerSequence.get(x).isHead())));
param12.add(new BasicNameValuePair("NodeID", String
.valueOf(PointerSequence.get(x).getNodeID())));
param12.add(new BasicNameValuePair("Step", String
.valueOf(PointerSequence.get(x).getStep())));
JSONObject json = jsonParser.makeHttpRequest(URL12, "POST",
param12);
}
}
>JSON CLASS:
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;
}
}
Thanks in Advance!
Related
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.
Hi i am new in android php client server. At present, i am doing the response from php sql server sending to Android client multiple result from sql row. Previously, i sending a simple string and receive android like below:
$result_data = array(
'ResultArray' => 'success',
);
#Output the JSON data
echo json_encode($result_data);
Then in android:
// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);
//Retrieve the data from the JSON object
String resultLoging = jsonObject.getString("ResultArray");
Now i want to receive from database having 3 columns: id, phone, name. How would i do that? Thank for your helping
use the following format in php
$result = mysql_query("SELECT *FROM tablename") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0)
{
// looping through all results
// products node
$response["details"] = array();
while ($row = mysql_fetch_array($result))
{
// temp user array
$product = array();
$product["id"] = $row["id"];
$product["name"] = $row["name"];
array_push($response["details"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
In android
get success value
int success = json.getInt(TAG_SUCCESS);
get the datas using following format
JSONArray spi = json.getJSONArray("details");
Use a for loop to get the object values in the array
for (int i = 0; i < spi.length(); i++)
{
JSONObject c = spi.getJSONObject(i);
id = c.getString("id");
}
Use JSONArray for multiple json result :
JSONArray jsonArray = jsonObject.getJSONArray("ResultArray");
Iterate JSONArray and get value from JSONObject :
for (int i=0;i<jsonArray.length();i++){
JSONObject json = jsonArray.getJSONObject(i);
String id = json.getString("id");
String phone = json.getString("phone");
String name = json.getString("name");
}
just found this, would be the best for my question
https://stackoverflow.com/a/3563464/1345454
$results = array();
while($row = mysql_fetch_array($sql))
{
$results[] = array(
'title' => base64_decode($row['title']),
'price' => $row['price'],
'seller_user' => $row['user']
);
}
$json = json_encode($results);
try this
$result_data = array(
'ResultArray' => 'success',
);
echo json_encode(array('result'=>$result_data));
in android
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl("url of php file");
JsonArray arry = json.getJSONArray("result");
JSONObject c = arry .getJSONObject(0);
String resultarr= c.getString("ResultArray");
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();
// System.out.println(json);
} 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 get all the Json data into my Mysql database through php, I have all my phone contacts details in this json object, But It only insert just one last phone contact detail to my database, please help as I have already posted a question but did not find a satisfactory answers. I debugged the application and it contains all of my contact detail in params of makehttprequest(.....)function, but Insert only last contact detail into database.
My php code is given below:
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['id']) && isset($_POST['phone'])&& isset($_POST['email'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO crm(id, name, phone, email) VALUES('$id', '$name', '$phone', '$email')");
// 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"] = "Oops! 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);
}
?>
My json object Which I copied during debugging the application is:
[id=85, name=, phone=, email=2, id=106, name=, phone=, email=2, id=93, name=, phone=, email=2, id=62, name=., phone=*100#, email=2, id=104, name=00, phone=00, email=2, id=90, name=03005103877, phone=03005103877, email=2, id=26, name=03005580234, phone=03005580234, email=2, id=154, name=Wajaht, phone=+923336124178, email=2, id=230, name=Yasir Altaf, phone=03215169284, email=2, id=55, name=Zafar Abbas, phone=03016775189, email=2]
But It it inserted the last contact detail which is name=Zafar Abbas, phone=03016775189, email=2 But I want insert all the detail in one go, please help me Thanks
AYsync task Class:
public class LoadSavingInDatabase extends AsyncTask<ArrayList<SavingContacts>,String,String>{
private static final String TAG_SUCCESS = "success";
private static final String URL = "http://amiranzur.com/android_connect/create_product.php";
JSONObject jsonObject= null;
#Override
protected String doInBackground(ArrayList<SavingContacts>... param) {
ArrayList<SavingContacts> contactArray = param[0];
List<NameValuePair> params = new ArrayList<NameValuePair>();
for(int i = 0; i < contactArray.size(); i++){
SavingContacts contact = contactArray.get(i);
params.add(new BasicNameValuePair("id", contact.id));
params.add(new BasicNameValuePair("name", contact.name));
params.add(new BasicNameValuePair("phone", contact.phone));
params.add(new BasicNameValuePair("email" , contact.email ));
}
JSONObject jsonObject= new JSONParser().makeHttpRequest(URL, "POST", params);
if(jsonObject != null){
try {
int success = jsonObject.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("create","ok2");
bool = true;
Log.d("insert","true" + bool);
} else {
}
} catch (JSONException e) {
Log.d("exception","exc "+e);
Log.d("create","lpc");
}
}
else if(jsonObject == null){
Log.d("null", "null1");
bool = false;
}
return null;
}
}
protected void onPostExecute(boolean bool){
if(bool == false)
Log.d("Insertion failed", "ID already inserted");
}
Json P arser Class:
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");
Log.d("Hope","Hope 1");
url += "?" + paramString;
Log.d("Hope","Hope 2");
HttpGet httpGet = new HttpGet(url);
Log.d("Hope","Hope 3");
HttpResponse httpResponse = httpClient.execute(httpGet);
Log.d("Hope","Hope 4");
HttpEntity httpEntity = httpResponse.getEntity();
Log.d("Hope","Hope 5");
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
Log.d("ex1","ex1 "+e);
e.printStackTrace();
} catch (ClientProtocolException e) {
Log.d("ex1","ex2 "+e);
e.printStackTrace();
} catch (IOException e) {
Log.d("ex1","ex3 "+e);
e.printStackTrace();
}
try {
Log.d("Hope","Hope 6");
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
Log.d("Hope","Hope 7");
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
Log.d("Hope","Hope 8");
is.close();
json = sb.toString();
Log.d("eee","json"+ json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + json);
}
//char[] chars = json.toCharArray();
// try parse the string to a JSON object
//if(chars[0] != 'D'){
try {
jObj = new JSONObject(json);
} catch (Exception e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
//}
//else {
// Log.d("null","null");
// }
return jObj;
}
}
The problem is here:
for(int i = 0; i < contactArray.size(); i++){
SavingContacts contact = contactArray.get(i);
params.add(new BasicNameValuePair("id", contact.id));
params.add(new BasicNameValuePair("name", contact.name));
params.add(new BasicNameValuePair("phone", contact.phone));
params.add(new BasicNameValuePair("email" , contact.email ));
}
JSONObject jsonObject= new JSONParser().makeHttpRequest(URL, "POST", params);
You make the request only after the loop,that will explain why you only INSERT the last value.
Move the request inside the loop so that you perform an insert at each iteration:
bool isSuccessful;
for(int i = 0; i < contactArray.size(); i++){
SavingContacts contact = contactArray.get(i);
params.add(new BasicNameValuePair("id", contact.id));
params.add(new BasicNameValuePair("name", contact.name));
params.add(new BasicNameValuePair("phone", contact.phone));
params.add(new BasicNameValuePair("email" , contact.email ));
//INSERT at each iteration
JSONObject jsonObject= new JSONParser().makeHttpRequest(URL, "POST", params);
if(jsonObject != null){
try {
int success = jsonObject.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("debug", "Contact Id# " + contact.id +" Inserted");
} else {
Log.d("debug", "Contact Id# " + contact.id +" FAILED");
}
isSuccessful = true;
} catch (JSONException e) {
Log.d("exception","exc "+e);
Log.d("create","lpc");
isSuccessful = false;
}
}else{
Log.d("debug", "json is null");
isSuccessful = false;
}
}
return isSuccessful;
I am new to android development and I am trying to make a login page which sends the password and username to a php script as a json array and the php script returns a json array response which contains the meassage accordingly.
I have made a android code as:
jobj.put("uname", userName);
jobj.put("password", passWord);
JSONObject re = JSONParser.doPost(url, jobj);
Log.v("Received","Response received . . ."+re);
// Check your log cat for JSON reponse
Log.v("Response: ", re.toString());
int success = re.getInt("success");
if (success == 1) {
return 1;
}
else{
return 0;
}
}
catch(Exception e){ e.getMessage(); }
}
The JsonParser doPost code is as follows:
public static JSONObject doPost(String url, JSONObject c) throws ClientProtocolException, IOException
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
HttpEntity entity;
StringEntity s = new StringEntity(c.toString());
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
entity = s;
request.setEntity(entity);
Log.v("entity",""+entity);
HttpResponse response;
try{
response = httpclient.execute(request);
Log.v("REceiving","Received . . .");
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
Log.v("RESPONSE",""+is);
}
catch(Exception e){
Log.v("Error in response",""+e.getMessage());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
Log.v("Reader",""+reader.readLine());
while ((line = reader.readLine()) != null) {
Log.v("line",""+line);
sb.append(line + "\n");
}
Log.v("builder",""+sb);
is.close();
json = sb.toString();
} catch (Exception e) {
Log.v("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.v("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I have the php script as:
$response = array();
$con=mysqli_connect("localhost","uname","password","db_manage");
if((isset($_POST['uname']) && isset($_POST['password']))){
$empid = $_POST['uname'];
$pass = $_POST['password'];
$query = "SELECT mm_emp_id,mm_password FROM employee_master WHERE mm_emp_id='$empid'and mm_password='$pass'";
$result = mysqli_query($con, $query);
if(count($result) > 0){
$response["success"] = 1;
$response["message"] = "";
echo json_encode($response);
}
else{
$response["success"] = 0;
$response["message"] = "The username/password does not match";
echo json_encode($response);
}
}
I am getting undefined index at the line where I check for isset(). What am I doing wrong in receiving the json in php script?
If you can see I have used a link for my help
Please do help me out.
In the doPost method you don't use the JSON object (JSONobject c) that contains the variables
public class JSONTransmitter extends AsyncTask<JSONObject, JSONObject, JSONObject> {
String url = "http://test.myhodo.in/index.php/test/execute";
#Override
protected JSONObject doInBackground(JSONObject... data) {
JSONObject json = data[0];
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);
JSONObject jsonResponse = null;
HttpPost post = new HttpPost(url);
try {
StringEntity se = new StringEntity("json="+json.toString());
post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setEntity(se);
HttpResponse response;
response = client.execute(post);
String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
jsonResponse=new JSONObject(resFromServer);
Log.i("Response from server", jsonResponse.getString("msg"));
} catch (Exception e) { e.printStackTrace();}
return jsonResponse;
}
Main Activity
try {
JSONObject toSend = new JSONObject();
toSend.put("msg", "hello");
JSONTransmitter transmitter = new JSONTransmitter();
transmitter.execute(new JSONObject[] {toSend});
} catch (JSONException e) {
e.printStackTrace();
}
I working on a tutorial how to connect Android to MySQL via PHP. I edited my code from this tutorial and I can't send POST or GET data.
I always have message Login and/or password field empty
This is my method:
class LogIn extends AsyncTask<String, String, String>{
String state, msg;
String id, login, pass;
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Checking, please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
List<NameValuePair> parames = new ArrayList<NameValuePair>(1);
parames.add(new BasicNameValuePair("login", u_name.getText().toString()));
parames.add(new BasicNameValuePair("pass", u_pass.getText().toString()));
Log.e("[INFO]",u_name.getText().toString());
Log.e("[INFO]",u_pass.getText().toString());
JSONObject json = jParser.makeHttpRequest(check_url, "POST", parames);
try{
int success = json.getInt("success");
if(success == 1){
SharedPreferences.Editor edytor = preferences.edit();
edytor.putString("name", json.getString("name"));
edytor.putString("login", u_name.toString());
edytor.putString("pass", u_pass.toString());
edytor.putBoolean("logged", true); //dfdf
edytor.commit();
state = "ok";
}
else{
SharedPreferences.Editor edytor = preferences.edit();
edytor.putBoolean("logged", false);
msg = json.getString("message");
state = "not_ok";
}
} catch(JSONException e){
Log.e("[JSON ERROR]: ", e.toString());
}
return null;
}
protected void onPostExecute(String file_url){
pDialog.dismiss();
if(state.equals("ok")){
Toast.makeText(LoginActivity.this, "You are logged in ;)", Toast.LENGTH_LONG).show();
Intent i = new Intent(LoginActivity.this,MainActivity.class);
startActivity(i);
}else if(state.equals("not_ok")){
Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_LONG).show();
}
}
}
and this is my JSON parser:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params){
try{
if(method == "POST"){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
Log.e("[TEST]",params.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
else if(method == "GET"){
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "iso-8859-1");
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{
jObj = new JSONObject(json);
} catch(JSONException e){
Log.e("JSON Parser", "Error parsing data " + e.toString() + " DATA: "+json);
}
return jObj;
}
}
and this is my PHP script:
$response = array();
if( (!empty($_POST['login'])) && (!empty($_POST['pass'])) )
{
include('config.php');
$zapytanie = mysql_query("SELECT * FROM users WHERE login = '".$_POST['login']."' AND pass='".$_POST['pass']."' LIMIT 1");
if(mysql_num_rows($zapytanie)>0){
while($row = mysql_fetch_assoc($zapytanie)){
$response["name"] = $row["name"];
$response["success"] = 1;
}
}
else{
$response["success"] = 0;
$response["message"] = "Bad login or pass";
}
} else{
$response["success"] = 0;
$response["message"] = "Login and/or password field empty";
}
print(json_encode($response));