private void AddGroupTasks(){
title1 = tTitle.getText().toString();
detail1 = tDetail.getText().toString();
ArrayList<NameValuePair> b = new ArrayList<NameValuePair>();
Tasks = new ArrayList<String>();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost ("http://203.209.111.88/AddGroupTasks.php");
httppost.setEntity(new UrlEncodedFormEntity(b));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
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");
}
So, When I click add,the information is supposed to be added to database. However, it gives a null value. By the way, I'm writing a to-do list app.
$Title = $_REQUEST['tTitle'];
$Detail = $_REQUEST['tDetail'];
$Group = $_REQUEST['spin'];
$DueDate = $_REQUEST['tDueDate'];
$Title = "'".$Title."'";
$Detail = "'".$Detail."'";
$Group = "'".$Group."'";
$DueDate = "'".$DueDate."'";
print $Title;
$database = "CloudList";
mysql_connect("localhost","root","1234");
mysql_select_db($database) or die("Unable to select database");
$q = "INSERT INTO message(group_name,message_title,message_details,message_due) VALUES($Group,$Title,$Detail,$DueDate)";
$result = mysql_query($q);
print $q;
mysql_close();
Here, This is my PHP Script.
Try this code, replace with your code and let me know what happen,
private void AddGroupTasks(){
title1 = tTitle.getText().toString();
detail1 = tDetail.getText().toString();
ArrayList<NameValuePair> b = new ArrayList<NameValuePair>();
Tasks = new ArrayList<String>();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost ("http://203.209.111.88/AddGroupTasks.php");
b.add(new BasicNameValuePair("tTitle",
"anyTitle"));
b.add(new BasicNameValuePair("tDetail",
"anyDetail"));
b.add(new BasicNameValuePair("spin",
"AnythingaboutSpin"));
b.add(new BasicNameValuePair("tDueDate",
"anytDueDate"));
httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
httppost.setEntity(new UrlEncodedFormEntity(b, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
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");
}
Try to set quotes in your Values section. It should look like:
$q = "INSERT INTO message(group_name,message_title,message_details,message_due) VALUES('$Group','$Title','$Detail','$DueDate')";
Related
{"college1":{"data":[{"id":"1","name":"nithin","location":"kannur s","time":"2016-06-20 12:06:30"},{"id":"2","name":"riy","location":"sdsdvxc","time":"2016-06-20 12:49:52"},{"id":"3","name":"royop","location":"kjpooj","time":"2016-06-20 06:15:36"},{"id":"4","name":"butr","location":"kjpooj","time":"2016-06-20 06:16:52"},17:17:03"}],"last_date":["2016-06-20 18:18:15"]}}
json data
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("lasttime",lasttime));
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(ip);
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
String result="";
if(is !=null)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
is.close();
i am trying to develop communication with android and wamp .when trying to send sqlite date to mysql database. it shows this error message. this is my web service.
$latest = '';
$datetime=mysql_query("SELECT MAX(time) AS latest from college1");
while ($row = mysql_fetch_assoc($datetime))
{
$latest = $row['latest'];
}
if(isset($_POST['lasttime']))
{
$dates=$_POST['lasttime'];
$datetime=mysql_query("SELECT * from college1 WHERE time > '{$dates}'");
while ($row = mysql_fetch_assoc($datetime))
{
//print_r($row);
//$array1[] = $row;
$retArr['college1']['data'][] = $row;
$retArr[$row['id']] = $row;
$retArr[$row['id']]['latest'] = $latest;
}
$retArr = json_encode($retArr);
echo $retArr;
//echo($retArr);
}
mysql_close($con);
?>
org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject.
this error shows when passing data to server and respose as null
I am trying to send a string to php script using namevaluepair. But i couldn't receive it on the other side. Here is my code.
protected String doInBackground(String... args) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("Username",code ));
Log.v("username", code);
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://192.168.42.21:8080/sellapp/menuitem.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish {}
}
return result;
}
Here i want to pass the value in the string code to my php script. my php script is
$con = mysqli_connect(HOST,USER,PASS,DB);
$cst_id=$_REQUEST['Username'];
// $cst_id= 'cus02';
$sql = "
select
cust_code, segment_type, cust_name, cust_address, cust_payment_type, cust_credit_limit, cust_cr_balance
from customer where cust_code='".$cst_id."'
";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push(
$result,
[
'cust_id'=>$row[0],
'cust_seg'=>$row[1],
'cust_name'=>$row[2],
'cust_type'=>$row[3],
'cust_ad'=>$row[4],
'cust_cr'=>$row[5],
'cust_bl'=>$row[6]
]
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
When I am giving the value directly to the php it works. But through name/value pair it returns a null array as result.
Please help me to get an answer.I tried questions related to it. But didn't worked.
<?php
$con = mysqli_connect(HOST,USER,PASS,DB);
$cst_id = $_POST['Username']; // --------- not $_REQUEST['Username'];
// $cst_id= 'cus02';
$sql = "select cust_code,segment_type,cust_name,cust_address,cust_payment_type,cust_credit_limit,cust_cr_balance from customer where cust_code='".$cst_id."' ";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
['cust_id'=>$row[0],
'cust_seg'=>$row[1],
'cust_name'=>$row[2],
'cust_type'=>$row[3],
'cust_ad'=>$row[4],
'cust_cr'=>$row[5],
'cust_bl'=>$row[6]
]);
}
//echo json_encode(array("result"=>$result));
echo json_encode($result);
mysqli_close($con);
?>
I'm comparing the username and password from the user input to the database data, and I used count to check if it is equal to 1 or 0.
If it's equal to 1, the editText should be set to 1, and if it's 0 it should be set to 0.
My problem is, it's always set to 0 even if the username and password is correct.
here is the name value pair and connection to the database:
username = etlogUsername.getText().toString();
password = etlogPassword.getText().toString();
String output = "";
//setting the NameValuePair
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
//adding the string variables inside the nameValuePairs
nameValuePairs.add(new BasicNameValuePair("user_username", username));
nameValuePairs.add(new BasicNameValuePair("user_password", password));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://thesis-account.byethost7.com/workout_select_username.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//getting the response
HttpResponse response = httpclient.execute(httppost);
//setting up the entity
HttpEntity entity = response.getEntity();
is = entity.getContent();
here is the json that will read the data:
JSONArray jArray= new JSONArray(output);
for(int i = 0; i <jArray.length() ; i++){
JSONObject json = jArray.getJSONObject(i);
COUNT_user_id = json.getInt("num_rows");
if(COUNT_user_id == 1)
{
isEqual = true;
}
}
etlogUsername.setText(COUNT_user_id+"");
and here is the php file:
$sql = mysql_query("SELECT COUNT(user_id) AS num_rows FROM tbl_users
WHERE user_username='{ $username}' && user_password = '{$password}' ");
while($row=mysql_fetch_assoc($sql))
{
$output[]=$row;
}
print(json_encode($output));
mysql_close($con);
Im a newbie to android, I am learning to connect to a server through android client using Php, MySql and JSON. For testing purpose im running on localhost.
So for here's what I've done.
Database demo.php
public class Database_demo extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
List<String> r = new ArrayList<String>();
try{
//http post
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/PhpAndMySql/category.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
}
//Convert response to string
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch(Exception e)
{
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
}
//END Convert response to string
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
r.add(json_data.getString("category"));
}
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, r));
}
catch(JSONException e1){
Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
}
}
}
category.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$q=mysql_query("SELECT * FROM category ORDER BY 'category'.'category' ASC");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
MySQL
CREATE TABLE `test`.`category` (
`category_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`category` VARCHAR( 255 ) NOT NULL
) ENGINE = MYISAM ;
I am getting a NullPointer Exception, when I execute in android.
Is the Php File correct?
Please I need your help with this!
Thanks
I'm thinking your php should be as follows (instead of quotes on the table.column use backticks).
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$q=mysql_query("SELECT * FROM category ORDER BY `category` ASC");
$output = array();
while($row = mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
Trying to have my PHP script return some SQL table queries. Here's my script as it stands right now:
<?php
define("DB_HOST", "localhost");
define("DB_USER", "*");
define("DB_PASSWORD", "*");
define("DB_DATABASE", "*");
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db(DB_DATABASE);
if (isset($_POST['tag']) && $_POST['tag'] != '') {
$tag = $_POST['tag'];
echo $tag;
if ($tag == 'question') {
$category = $_POST['category'];
$response=mysql_query("select * from QUESTIONS where CATEGORY like '$category'");
return $category; //just doing this, rather than $response to see if it works
}
}
?>
And here's the Android code that's associated with it:
public JSONObject getQuestionsJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// 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();
} 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) {
Log.v("while", line);
sb.append(line + "\n");
//Log.v("err", line);
}
is.close();
And the method that calls getQuestionsJSON...:
private static String question_tag = "question";
public JSONObject getQuestions(String category) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", question_tag));
params.add(new BasicNameValuePair("category", category));
//JSONObject json;
JSONObject questionsList = jsonParser.getQuestionsJSONFromUrl(questionURL, params);
//return json
return null;
}
And here's the LogCat of the Log.v() I have in the getQuestionsJSON...() method:
04-04 20:41:58.721: V/while(933): question
So I don't really see why this is returning 'question' rather than the String that is passed when I run getQuestions()?
In PHP file you have
echo $tag;
And it is response to request.
This should return mysql response:
if (isset($_POST['tag']) && $_POST['tag'] != '') {
$tag = $_POST['tag'];
if ($tag == 'question') {
$category = $_POST['category'];
$response=mysql_query("select * from QUESTIONS where CATEGORY like '$category'");
$rows = array();
while($r = mysql_fetch_assoc($response)) {
$rows[] = $r;
}
print json_encode($rows);
}
}