I am inserting some values from my android login page to mysql database using php .
login.php
<?php
$con = mysql_connect("localhost","abc","xyz") or die(mysql_error());
mysql_select_db("sync",$con) or die(mysql_error());
$user_name = $_POST['user_name'];
$user_mobile_no = $_POST['user_mobile_no'];
$user_email_id = $_POST['user_email_id'];
$imei_no = $_POST['imei_no'];
$login_date = $_POST['login_date'];
$time = $_POST['time'];
$user_name = 'Navdeep';
$user_mobile_no = '12345678990';
$user_email_id = 'nav#gmail.com';
$imei_no = '1234567890';
$login_date = '24-12-2012';
$time = '01:01:01';
$result = mysql_query("INSERT INTO
login_details(user_name,user_mobile_no,user_email_id,
imei_no,login_date,time)
VALUES('$user_name','$user_mobile_no','$user_email_id',' $imei_no','$login_date','$time')");
if($result)
{
$response["success"] = 1;
$response["message"] = "User Details inserted successfully";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "There was an error inserting user details";
echo json_encode($response);
}
mysql_close($con);
?>
When i use $_POST[''] values are getting inserted as blank , but when i hardcode the values it is getting inserted , need some help
Android code :
try{
JSONObject jsonObject = new JSONObject();
jsonObject.put("user_name",userName);
jsonObject.put("user_mobile_no",mobNo);
jsonObject.put("user_email_id",email);
jsonObject.put("imei_no",imeino);
jsonObject.put("login_date",date);
jsonObject.put("time",time);
JSONArray jsonArray = new JSONArray();
jsonArray.put(jsonObject);
String basicAuth = "Device " + new
String(Base64.encode((imeino).getBytes(), Base64.NO_WRAP));
RequestBody body =
RequestBody.create(JSON,String.valueOf(jsonArray));
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().header("Authorization",
basicAuth).url(url).post(body).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
Login.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(), "Request to the
server failed", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResponse(Call call, Response response) throws
IOException {
Log.i("response ", "onResponse(): " + response );
StatusLine statusLine = null;
String result = response.body().string();
if(result.equals("") || result.equals(null)){
Log.i("No response", "No response");
}else{
Log.i("Response","Response "+result);
statusLine = StatusLine.get(response);
final int responseCode = statusLine.code;
Log.d("Code:", String.valueOf(responseCode));
}
}
});
}catch (Exception e){
e.printStackTrace();
}
You should send form data request from android.
Replace this
JSONObject jsonObject = new JSONObject();
jsonObject.put("user_name",userName);
jsonObject.put("user_mobile_no",mobNo);
jsonObject.put("user_email_id",email);
jsonObject.put("imei_no",imeino);
jsonObject.put("login_date",date);
jsonObject.put("time",time);
JSONArray jsonArray = new JSONArray();
jsonArray.put(jsonObject);
String basicAuth = "Device " + new
String(Base64.encode((imeino).getBytes(), Base64.NO_WRAP));
RequestBody body =
RequestBody.create(JSON,String.valueOf(jsonArray));
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().header("Authorization",
basicAuth).url(url).post(body).build();
With
RequestBody formBody = new FormBody.Builder()
.add("user_name",userName)
.add("user_mobile_no",mobNo)
.add("user_email_id",email)
.add("imei_no",imeino)
.add("login_date",date)
.add("time",time)
.build();
String basicAuth = "Device " + new
String(Base64.encode((imeino).getBytes(), Base64.NO_WRAP));
Request request = new Request.Builder().header("Authorization",
basicAuth).url(url).post(formBody).build();
Related
I know how to send data using volley library and get those from php. Problem is, I want to send a Json String and decode those data from the php side.
This is the method I am using to send data using param. Last item is the json String
private void checkOrderNo() {
pDialog.setMessage("Sending...");
showDialog();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
final String nowDate = df.format(new Date());
//final day of the month
Date today = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(today);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
Date lastDayOfMonth = calendar.getTime();
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
final String lastDate = sdf.format(lastDayOfMonth);
Log.d("Last day ", sdf.format(lastDayOfMonth) + " // Today" + nowDate);
// Tag used to cancel the insert
String tag_string_req = "req_insert";
final StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_ITEM_DETAILS_SEND, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
if (jObj.names().get(0).equals("found")) {
newOrderId = jObj.getString("found").toString();
orderIdForItemTable = newOrderId;
Log.d(TAG, "newOrderId: " + newOrderId);
Log.d(TAG, "New repID 2 inserted into sqlite: " + newOrderId + " " + nowDate);
sqLiteHandler.addItemDetails(newOrderId, repID, dealerID, nowDate, lastDate, selectedDisChannel);
finish();
Bundle basket = new Bundle();
basket.putString("dealerName", dealerName);
basket.putString("orderNo", newOrderId);
basket.putString("jsonString", json_string);
Intent intent = new Intent(SelectItem.this, ItemCart.class);
intent.putExtras(basket);
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(), "Invalied Request", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Inserting Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("order_no", orderId);
params.put("repID", repID);
params.put("dealerID", dealerID);
params.put("nowDate", nowDate);
params.put("lastDate", lastDate);
params.put("disChannel", selectedDisChannel);
params.put("jsonString", json_string);
return params;
}
};
strReq.setRetryPolicy(new DefaultRetryPolicy(15000, 1,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
This is my PhP for volley
<?php
require_once 'include/Config_test.php';
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("connection failed");
mysql_select_db(DB_DATABASE,$con) or die("db selection failed");
$order_no = $repID = $dealerID = $nowDate = $jsonString = $lastDate = $disChannel = "";
if(isset($_POST['order_no'])){
$order_no = $_POST['order_no'];
$repID = $_POST['repID'];
$dealerID = $_POST['dealerID'];
$nowDate = $_POST['nowDate'];
$lastDate = $_POST['lastDate'];
$disChannel = $_POST['disChannel'];
$jsonString= $_POST['jsonString'];
}
$result = mysql_query("SELECT MAX(order_no) FROM tbl_items_header_t");
$row = mysql_fetch_row($result);
if($row[0] < 70000000){
$highest_id = 70000000;
} else{
$highest_id = $row[0] + '1';
}
//$highest_id = $row[0] + '1';
$query = mysql_query("INSERT INTO tbl_items_header_t(order_no,rep_no,dealer_no,order_date,last_date,dis_channel,status)
VALUES('$highest_id','$repID','$dealerID','$nowDate','$lastDate','$disChannel','')");
$json['found']= $highest_id;
echo json_encode($json);
?>
I know send json String using DefaultHttpClient but it is deprecated. I have to use two PHP also. I want to do it using volley.
This is what I use for get json String using DefaultHttpClient. It worked. But I want to use this in the volley.
<?php
require_once 'include/Config_test.php';
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("connection failed");
mysql_select_db(DB_DATABASE,$con) or die("db selection failed");
$postdata = file_get_contents('php://input');
$data = json_decode($postdata, true);
if (is_array($data['sending_items'])) {
foreach ($data['sending_items'] as $record) {
$order_no = $record['order_no'];
$items = $record['items'];
$items_no = $record['items_no'];
$plant = $record['plant'];
$quantity = $record['quantity'];
mysql_query("INSERT INTO tbl_item_list(order_no, items, items_no, plant, quantity) VALUES('$order_no', '$items', '$items_no', '$plant', '$quantity')");
}
}
echo json_encode($data);
mysql_close($con);
?>
i want to send all contacts with contact name and number in one row in one array in my android application like
john => "+92312xxxxxxx" ,
Right now i'm using namevaluepairs to post two arrays but it's not working like :
public class ContactList extends Activity {
public TextView outputText;
String phoneNumber = null;
String names = null;
String[] keyValue;
String[] kes;
int Count;
String s = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
outputText = (TextView) findViewById(R.id.textView1);
fetchContacts();
//Http connection
InputStream is=null;
List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>(1);
for (int i = 0; i < Count ; i++)
{
nameValuePairs.add(new BasicNameValuePair("CN[]", keyValue[i]));
nameValuePairs.add(new BasicNameValuePair("names[]",kes[i]));
Log.i("Response", "you sent :" +kes[i]+" :"+ keyValue[i] + "\n ");
}
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.107/older/ContactList.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(ClientProtocolException e)
{
Log.e("ClientProtocol","Log_tag");
e.printStackTrace();
System.out.println("Excep: "+e);
}
catch(IOException e)
{
Log.e("Log_tag","IOException");
e.printStackTrace();
}
String result = "";
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");
}
reader.close();
is.close();
result=sb.toString();
Log.i("Response", "result "+ result);
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
//result = "[{\"0\":\"Muhaimin\",\"1\":\"3\",\"2\":\"o+\"}]";
try
{
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++)
{
s= s +";"+ jArray.getString(i) + "\n";
}
}
catch (Exception e)
{
Log.e("Response", "error fetching indexes" + e);
}
String[] friends= s.split(";");
StringBuffer output = new StringBuffer();
for (int i = 0; i < friends.length; i++)
{
Log.i("List","Your friends namee"+friends[i]);
output.append("\n Your friend's number"+ friends[i]);
}
}
//Fetch Contacts
public void fetchContacts() {
// String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
// Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
//String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
// String DATA = ContactsContract.CommonDataKinds.Email.DATA;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, null);
// Loop for every contact in the phone
Count = cursor.getCount();
if (cursor.getCount() > 0) {
keyValue= new String[Count];
kes= new String[Count];
while (cursor.moveToNext()) {
String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER )));
if (hasPhoneNumber > 0) {
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);
while (phoneCursor.moveToNext())
{
int i=0;
String stu = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
phoneNumber +=":"+ stu;
names +=":" + name;
Log.i("List",stu + name +"\n" );
}
phoneCursor.close();
}
}
}
keyValue = phoneNumber.split(":");
kes = names.split(":");
Log.i("List","24th"+keyValue[23]);
Toast.makeText(getApplicationContext(), "99th "+keyValue[909] ,Toast.LENGTH_LONG).show();
}
PHP after receiving contacts will match them and return only those which have a match with database contacts. And then it returns contacts with names
i'm stuck with sending and receving part
Here is php code
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'verification');
define('DB_USER','root');
define('DB_PASSWORD','');
// 1. Create a database connection
$connection = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD);
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
$PhoneNum= $_POST["CN"];
$i=0;
$j=0;
$friends = array();
$Invite = array();
unset ($PhoneNum[0]);
foreach ($PhoneNum as $i=> $element){
//or do whatever you need to do to that variable
$query="SELECT Number FROM `user` WHERE Number=$element";
$query_exec = mysqli_query($connection ,$query);
if (!$query_exec)
{ echo mysql_error(); }
ELSE {
if(mysqli_num_rows($query_exec)>0)
{
$friends["$j"]= $PhoneNum[$i];
$j++;
}
else
{
;
}}
}
echo (json_encode($friends));
?>
You'll get a URL now that would look like:
www.example.com/yourscript?CN[]=keyValue1&names[]=key1&CN[]=keyValue2&names[]=key2 etc.. going on untill your whole list has looped.
I doubt that is what your PHP script wants to receive, you probably want to send the POST for each time you increment the loop. But thats just conjecture untill you post more information/code.
Instead send a JSON array as the value of the nameValuePair and convert it to a PHP array using json_decode function in the server side.
my codes is fine, not returning any errors but the values being retrieved are the same as the previous field..for example, if i set table3 to 'HELLO' then table4 is also 'HELLO' which is kinda wrong,i wanted separate values..here is my code...
my SigninActivity:
public class SigninActivity extends AsyncTask<String,Void,String>{
private TextView statusField,roleField, sampleField;
private Context context;
private int byGetOrPost = 0;
//flag 0 means get and 1 means post.(By default it is get.)
public SigninActivity(Context context,TextView statusField,TextView roleField,TextView sampleField,int flag) {
this.context = context;
this.statusField = statusField;
this.roleField = roleField;
this.sampleField = sampleField;
byGetOrPost = flag;
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
if(byGetOrPost == 0){ //means by Get Method
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "http://XXX.XXX.X.X/XXX/ins.php?username="
+username+"&password="+password;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
else{
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link="http://XXX.XXX.X.X/XXX/sel.php";
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter
(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}
#Override
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
this.sampleField.setText(result);
}
}
my select.php file (sel.php):
<?php
$con=mysqli_connect("localhost","root","","db_name");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con,"SELECT role,sample FROM table1 WHERE
username='$username' and password='$password'");
$row = mysqli_fetch_array($result);
$data = $row[0];
if($data){
echo $data;
}
mysqli_close($con);
?>
This is where your problem is:
#Override
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
this.sampleField.setText(result);
}
If you want different values for sampleField and roleField, you should set different values.
Update
I see where your other problem is. In the un-updated PHP source, you are selecting both role and sample from the database table, but you are outputting only role because $data equals $row[0]. If you want sample as well, you would need to retrieve $row[1] as well.
Or you could also use $row["role"] and $row["sample"] to get the values returned from the database table.
<?php
$con=mysqli_connect("localhost","root","","db_name");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con,"SELECT role,sample FROM table1 WHERE
username='$username' and password='$password'");
$row = mysqli_fetch_array($result);
if($row){
// returns a json object in the form
// {"role":"<role-from-database>","sample":"<sample-from-database>"}
$output = array("role" => $row["role"] ,"sample" => $row["sample"]);
echo json_encode($output);
}
mysqli_close($con);
?>
With the updated PHP source, you should process the JSON object in your SigninActivity.
Update 2
#Override
protected void onPostExecute(String result){
String role = "", sample = "";
// read the json object with JsonReader
JsonReader reader = new JsonReader(new StringReader(result));
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("role")) {
role = reader.nextString();
} else if (name.equals("sample")) {
sample = reader.nextString();
} else {
reader.skipValue();
}
}
reader.endObject();
// set the text here
}
Let me know if this helps.
I'm trying to update a row in my database via my android app. My pulling from the database is working but I'm having trouble with the updating. My code for updating is as follows:
My AsyncTask class:
private class UpdateAnimalTask extends AsyncTask<Void, Void, Boolean>
{
#Override
protected Boolean doInBackground(Void... arg0)
{
try
{
ID = (EditText) findViewById(R.id.eTid);
Name = (EditText) findViewById(R.id.eTname);
Type = (EditText) findViewById(R.id.eTtype);
Breed = (EditText) findViewById(R.id.eTbreed);
Gender = (EditText) findViewById(R.id.eTgender);
Injuries = (EditText) findViewById(R.id.eTinjuries);
Treat = (EditText) findViewById(R.id.eTtreat);
String nM = Name.getText().toString();
String tP = Type.getText().toString();
String bR = Breed.getText().toString();
String gE = Gender.getText().toString();
String iN = Injuries.getText().toString();
String tR = Treat.getText().toString();
ArrayList<NameValuePair> up = new ArrayList<NameValuePair>();
up.add(new BasicNameValuePair("name", nM));
up.add(new BasicNameValuePair("type", tP));
up.add(new BasicNameValuePair("breed", bR));
up.add(new BasicNameValuePair("gender", gE));
up.add(new BasicNameValuePair("injuries", iN));
up.add(new BasicNameValuePair("treatment", tR));
String phpLink = "http://select.garethprice.co.za/update.php?name=" + nM;
Log.e("Test", up.toString());
dbUpdate(up, phpLink);
Log.e("Test", up.toString());
}
catch(Exception e)
{
Log.e("log_tag", "Error in uploading " + e.toString());
Toast.makeText(getBaseContext(), "Error " + e.toString(), Toast.LENGTH_LONG).show();
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean result)
{
if(result)
{
Toast.makeText(getBaseContext(), "Successfully updated", Toast.LENGTH_LONG).show();
}
}
}
My dbUpdate method which is being called inside my asynctask class:
public void dbUpdate(ArrayList<NameValuePair> data, String phpL)
{
InputStream iS = null;
try
{
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(phpL);
httppost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
iS = entity.getContent();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection " + e.toString());
Toast.makeText(getBaseContext(), "Error " + e.toString(), Toast.LENGTH_LONG).show();
}
}
My php:
<?php
include_once 'db.php';
$con=mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)or die("cannot connect");
mysql_select_db(DB_DATABASE)or die("cannot select DB");
$nM = $_GET['name'];
$tP = $_POST['type'];
$bR = $_POST['breed'];
$gE = $_POST['gender'];
$iN = $_POST['injuries'];
$tR = $_POST['treatment'];
$sql = "UPDATE tbl_Animals SET animal_Type = '$tP', animal_Breed = '$bR', animal_Gender = '$gE', animal_Injuries = '$iN', animal_Treatments = '$tR' WHERE animal_Name = '$nM'";
echo "test: " . $nM . $tP . $bR . $gE . $iN . $tR;
mysql_query($sql,$con) or die("error: " . mysql_error());
mysql_close($con)
?>
Executing the asynctask in my update button:
public void Update(View v)
{
new UpdateAnimalTask().execute();
}
The android code is not breaking so I suspect it's something with the php because my toast pops up that says update successful in my onPostExecute.
Thank you in advance.
I have to send byte array using Http post method,but in basicnamevalue pair class its gives
me error as the constructor BasicNameValuePair(String, byte[]) is undefined.is any onother way to solved this issue please help me.
AsyncTask :
public void SaveDatandImage() {
Byte[] image1,image2;
new AsyncTask<Void, Void, String>() {
protected void onPreExecute() {
pDialog = new ProgressDialog(DetailsAcceptActivity.this);
pDialog.setTitle("Sending Query");
pDialog.setMessage("Please Wait...");
pDialog.setCancelable(true);
pDialog.show();
};
protected String doInBackground(Void... params) {
String response = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
Date today = new Date();
nameValuePairs.add(new BasicNameValuePair("name","Name"));
nameValuePairs.add(new BasicNameValuePair("image1",image1));
nameValuePairs.add(new BasicNameValuePair("image2",image2));
if (Common.isInternetConnected(DetailsAcceptActivity.this)) {
try {
response = Common.httpPost(url_make_query, nameValuePairs, new String[] {});
// Jobj=jparser.makeHttpRequest(url_make_query, "POST", nameValuePairs);
Log.v(Common.TAG, "Record respose : " + response);
Intent intent = new Intent(DetailsAcceptActivity.this, LoginActivity.class);
DetailsAcceptActivity.this.finish();
startActivity(intent);
//Toast.makeText(MenuActivity.this,"Record Saved",Toast.LENGTH_SHORT).show();
/*JSONObject jObj = new JSONObject(response);
strRespCode = jObj.getString("success");
strRespMessage=jObj.getString("message");
int success=Jobj.getInt(TAG_SUCCESS);
if(success==1) {
Toast.makeText(MenuActivity.this,"inserted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MenuActivity.this,"Error", Toast.LENGTH_SHORT).show();
}*/
//if(response.e)
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
//groupMember.setSynced_with_server(StaticMembers.ZERO);
return "NO_NETWORK";
}
return response;
};
protected void onPostExecute(String result) {
if (result != null) {
if(!result.equals("NO_NETWORK")) {
//groupMember.setSynced_with_server(StaticMembers.ONE);
}
//Log.w("strRespMessage= "+strRespMessage, "********");
// Toast.makeText(MenuActivity.this, "Query Sent!!", Toast.LENGTH_LONG).show();
//finish();
}
pDialog.dismiss();
}
}.execute(null, null);
}
PHP Script to accept data from front end
<?php
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['sender_mobile_no'])) {
$name = $_POST['name'];
$image1= $_POST['image1'];
$image2= $_POST['image2'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
// mysql inserting a new row
$result = mysqli_query($con,"INSERT INTO tbl_query_master(name,image1,image2) VALUES('$name','$sender_name', '$image1', '$image2')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Order placed successfully.";
// 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);
}
?>
You can encode your image bytes into String and then send it on server. You can use
String strImage=Base64.encodeToString(image1, Base64.DEFAULT); // image1 is your byte[]
and then set this String in your namevaluepair as
nameValuePairs.add(new BasicNameValuePair("image1",strImage));
In php:
you can decode your string to get bytearray as follows.
$str=$_POST['image1'];
$abc=base64_decode($str);