I am trying to connect to MySQL DB using php script. But I don't get any output only exception code. I can't figure it out where is the problem. I used a tutorial code.
private EditText outputStream;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String result = null;
InputStream input = null;
StringBuilder sbuilder = null;
outputStream = (EditText)findViewById(R.id.output);
ArrayList <NameValuePair> nameValuePairs = new ArrayList <NameValuePair>();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://ik.su.lt/~jbarzelis/Bandymas/index.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
input = entity.getContent();
}
catch(Exception e){
Log.e("log_tag","Error in internet connection"+e.toString());
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(input,"iso-8859-1"),8);
sbuilder = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
sbuilder.append(line + "\n");
System.out.println(line);
}
input.close();
result = sbuilder.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
int fd_id;
String fd_name;
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
fd_id = json_data.getInt("FOOD_ID");
fd_name = json_data.getString("FOOD_NAME");
outputStream.append(fd_id +" " + fd_name + "\n");
}
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "No food found", Toast.LENGTH_LONG).show();
}
catch(ParseException e1){
e1.printStackTrace();
}
}
PHP script:
<?php
mysql_connect("localhost","**********","******");
mysql_select_db("test");
$sql = mysql_query("select FOOD_NAME as 'Maistas' from FOOD where FOOD_NAME like 'A%'");
while($row = mysql_fetch_assoc($sql)) $output[]=$row;
print(json_encode($output));
mysql_close;
?>
Any ideas how to fix it?
First, dont use Exception.toString(), use Exception.printStackTrace():
catch (Exception e) {
e.printStackTrace();
}
Second, in your PHP code, your not checking for any errors. If any errors occur, I suggest you issue a different HTTP status code (like 400), then, in your Android code:
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error.);
}
This way you will know if something happened on the server.
Hope this helps
Related
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 sending data from android to php script using json object as follows:
jobj.put("uname", userName);
jobj.put("password", passWord);
JSONObject re = JSONParser.doPost(url, jobj);
Then the doPost() method 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);
HttpResponse response;
try{
Log.v("Request",""+request);
response = httpclient.execute(request);
//Log.v("response",""+response);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
}
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) {
sb.append(line + "\n");
}
//Log.v("response",sb.toString());
is.close();
json = sb.toString();
Log.v("response",json);
} 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 (Exception e) {
Log.v("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
I have a php script which validates the input as follows:
$response = array();
$con=mysqli_connect("localhost","user","password","manage");
if((isset($_POST['uname']) && isset($_POST['password']))){
$empid = $_POST['uname'];
$pass = $_POST['password']);
$query = "SELECT empid,password FROM master WHERE mm_emp_id='".mysql_real_escape_string($empid)."' and mm_password='".mysql_real_escape_string($pass)."'";
$result = mysqli_query($con, $query);
if($result->num_rows != 0){
$response["success"] = 1;
$response["message"] = "";
print_r(json_encode($response));
}
else{
$response["success"] = 0;
$response["message"] = "The username/password does not match";
print_r(json_encode($response));
}
}
The problem is the isset() does not catch the uname key and I get undefined index for 'uname' and 'password' key. As you can see the json object is converted to string and added as String entity to the request. I cannot figure out what have I been doing wrong that the $_post is not receiving the values.
Please do suggest on what I have been doing so that i can receive the parameters in my php script.
you are posting data as application/json from android so you can access data in php with:
$post_data = json_decode(file_get_contents('php://input'));
Here my code:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1980"));
InputStream is = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("dropbox link to php code");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
System.out.println(is);
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
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();
result=sb.toString();
System.out.println("1 " + result);
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("id")+
", name: "+json_data.getString("name")+
", sex: "+json_data.getInt("sex")+
", birthyear: "+json_data.getInt("birthyear")
);
}
}
catch (JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
The link in the HTTPPost is a download link to the PHP code on Dropbox. That code looks like this:
<?php
mysql_connect("host","username","password");
mysql_select_db("1487057_test");
$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
The problem is that the PHP code does not seem to be "executed" by the HTTPClient. When I do a print of the input stream, I just get back the first two lines of the PHP code. The JSON log does not seem to print at all. Anyone see what's wrong?
If you have the json data from ftp server it will work fine, since u r
using dropbox for php file, u need to make sure that it works, would
suggest you to test service on browser first if it works fine then u
can move ahead with code.possibly setup the ftp instead of Dropbox as
file server.
modify your PHP to something like:
<?php
$sql = "SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'";
mysql_query("set names utf8");
$result = mysql_query($sql);
while ($e = mysql_fetch_assoc($result)) {
$output[]=$e;
}
print(json_encode($output));
mysql_close($dbhost);
?>
I am connecting to external database from my android applicaio. it is MS SQL Server using PHP JSON.
I am successfully connected to database and getting results in browser. while coming to android i am not getting any results it is showing Error Parsing Data org.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray. Below is my code.
getDatabase.php
<?php header('content-type: application/json; charset=utf-8');
$myServer = "example";
$myUser = "user";
$myPass = "pq";
$myDB = "dbname";
$conn = new COM ("ADODB.Connection")
or die("Cannot start ADO");
$connStr ="PROVIDER=SQLOLEDB;SERVER=".$myServer.";
UID=".$myUser.";PWD=".$myPass.";DATABASE=".$myDB;
$conn->open($connStr);
$query = "SELECT parkingtitle,address FROM parkd_dailyparkingslots";
$rs = $conn->execute($query);
$num_columns = $rs->Fields->Count();
for ($i=0; $i < $num_columns; $i++) {
$fld[$i] = $rs->Fields($i);
}
while (!$rs->EOF)
{
for ($i=0; $i < $num_columns; $i++) {
print(json_encode($fld[$i]->value));
}
$rs->MoveNext(); //move on to the next record
}
$rs->Close();
$conn->Close();
$rs = null;
$conn = null;
?>
Database activity
public class Database extends Activity {
/** Called when the activity is first created. */
TextView resultView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.database);
StrictMode.enableDefaults(); // STRICT MODE ENABLED
resultView = (TextView) findViewById(R.id.result);
getData();
}
public void getData() {
String result = "";
InputStream isr = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.example.com/getDatabase.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
resultView.setText("Couldnt connect to database");
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
isr, "utf-8"), 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++) {
String json = jArray.getString(i); // JSONObject
// json = jArray.getJSONObject(i);
JSONObject jObj = new JSONObject(json);
s = s + "Name: " + jObj.getString("parkingtitle") + "\n\n"
+ "Address: " + jObj.getString("address") + "\n\n";
}
resultView.setText(s);
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data " + e.toString());
}
}
}
I searched in google and check all the posts but i did not get any solution.
Please help me on this.
Thanks in advance.
Try using:
JSONObject jObj = jArray.getJSONObject(i);
Instead of:
jArray.getString(i); // JSONObject // json = jArray.getJSONObject(i);
JSONObject jObj = new JSONObject(json);
I read data from a database (only the last row, I do it in my php file) what I want to do is to use the data of each field separately but the problem is that the JSONArray is empty I tried a lot of ways to do it looking for it in different posts but it´s always empty.
This is my code
public class MainActivity extends Activity {
/** Called when the activity is first created. */
JSONArray jArray = null;
String result = null;
InputStream is = null;
StringBuilder sb=null;
String ct_id;
String ct_name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost= new HttpPost("http://xxx.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
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());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
String line=null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getString("fecha");
ct_name=json_data.getString("dia");
}
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "JSON is empty" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
It always catchs JSONException e1.
Thank you everibody in advance
Check returned string in result. Probably there are not only json structure(errors, warning, etc..). JSON spellchecker: http://jsonlint.com/
after checking the json response; better to try using GSON, much more convenient;
JsonParser jsonParser = new JsonParser();
JsonArray jArray;
if ( jsonParser.parse(result).isJsonArray() ) {
jArray = jsonParser.parse(result).getAsJsonArray();
}
else { jArray = new JsonArray(); }
The problem was in PHP file, JSON couldn´t understand the data and that is why it was empty, I changed it and now works properly.