MySQL request from android error - java

I have MySQL database. I'm trying to get some data from android using PHP.
This is my PHP code: Here I'm trying to get User's info using his id.
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["id"])) {
$id = $_GET['id'];
// get a product from products table
$result = mysql_query("SELECT * FROM app WHERE vk_id = $id");
//echo $result;
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$users = array();
$product["id"] = $result["id"];
$product["first_name"] = $result["first_name"];
$product["last_name"] = $result["last_name"];
$product["vk_id"] = $result["vk_id"];
$product["points"] = $result["points"];
// success
$response["success"] = 1;
// user node
$response["users"] = array();
array_push($response["users"], $product);
// 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 {
// no product found
$response["success"] = 0;
$response["message"] = "No user 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);
}
?>
Testing with browser gives seccess result, it means PHP code working fine
So, here is the Android part:
public class DB_read_by_id extends AsyncTask<String, String, String> {
Context context;
private static String url_read_by_id = "http://women.egeshki.ru/blockphonedb/read_by_id.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_USERS = "users";
private static final String TAG_POINTS = "points";
JSONArray users = null;
String vk_id;
String points;
JSONParser jParser = new JSONParser();
public DB_read_by_id(String _vk_id, Context _context) {
vk_id = _vk_id;
context = _context;
url_read_by_id += "?id=" + vk_id;
Log.e("DB_read_by_id", "Constructor");
}
#Override
protected String doInBackground(String... strings) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_read_by_id, "GET", params);
Log.e("DB_read_by_id", "doInBackground");
Log.e("DB_read_by_id: ", url_read_by_id);
Log.e("DB_read_by_id json ", json.toString());
// Check your log cat for JSON response
//Log.e("Users_all: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
String message = json.getString(TAG_MESSAGE);
users = json.getJSONArray(TAG_USERS);
Log.e("DB_read_by_id", "Attempt to get from db");
if (success == 1) {
JSONObject c = users.getJSONObject(0);
points = c.getString(TAG_POINTS);
Log.e("DB_read_by_id Points", points);
} else if (message.equals("No user found")) {
Log.e("DB_read_by_id", "No user found");
} else if (message.equals("Required field(s) is missing")) {
Log.e("DB_read_by_id", "Required field(s) is missing");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
Here is the logcat:
com.example.myapplication E/DB_read_by_id﹕ Constructor
com.example.myapplication E/DB_read_by_id﹕ doInBackground
com.example.myapplication E/DB_read_by_id:﹕ http://women.egeshki.ru/blockphonedb/read_by_id.php?id=150923434
com.example.myapplication E/DB_read_by_id json﹕ {"message":"No user found","success":0}
When I test from browser the link, which I get from logcat it's againg working fine. But from android it gives me an error. The problem is the link is ok, but android gives an error
Where is my mistake?

you didn't send the id to server
List<NameValuePair> params = new ArrayList<NameValuePair>();
//add this
params.add(new BasicNameValuePair("id","the value here));//
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_read_by_id, "GET", params);
Edit :after reading your comments
i think the problem is that you use your parametre in the link instead off using the right way .. just try to use this :
List<NameValuePair> params = new ArrayList<NameValuePair>();
//add this
params.add(new BasicNameValuePair("id","150923434"));//
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_read_by_id, "GET", params);
try this and report

Related

Nothing happens when jsonResponse gets null data from mySQL-DB

im just new to java/android programming.
Im writing an app, where users can register themselves and login. data is saved in an online mysql-db. registering and login is working fine. The user stays loggig by using a session.
Even fetching the data from the mysql-db works but theres one issue when some db fields are responsing "null".
this is the code im working with
public class UserProfileSettingsFragment extends PreferenceFragment
{
SessionManager session;
#Override
public void onCreate(final Bundle savedInstanceState)
{
SharedPreferences prefs = this.getActivity().getSharedPreferences("JampSharedPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.usersettings);
session = new SessionManager(this.getActivity().getApplicationContext());
HashMap<String,String> user = session.getUserDetails();
final String sessionUsername = user.get(SessionManager.KEY_USERNAME);
// ResponseListener um Request Nutzerdaten auszulesen.
Response.Listener<String> UserDataResponseListener = new Response.Listener<String>(){
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
// Wenn Datenabfrage erfolgreich, JSONResponse auswerten.
if (success) {
String responseRealName = jsonResponse.getString("realname");
String responseStreetName = jsonResponse.getString("streetname");
int responsePostcode = jsonResponse.getInt ("postcode");
String responseCity = jsonResponse.getString("city");
String responseState = jsonResponse.getString("state");
int responseAge = jsonResponse.getInt ("age");
int responseIsPremium = jsonResponse.getInt ("isPremium"); // BOOLEAN
Preference prefUserData = (Preference) findPreference("preferencescreen_userdata");
prefUserData.setTitle(sessionUsername);
//prefUserData.setSummary(responseRealName+"\n"+responseStreetName+"\n"+responsePostcode + " " + responseCity);
Preference prefUsername = (Preference) findPreference("settings_username");
prefUsername.setTitle(sessionUsername);
Toast.makeText(getActivity(),sessionUsername, Toast.LENGTH_LONG);
if (responseIsPremium==1){
//ivPremiumIcon.setVisibility(View.VISIBLE);
}
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Konnte Nutzerdaten nicht abrufen.")
.setNegativeButton("Nochmal",null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
// Request an userdatarequest.php senden
UserDataRequest userDataRequest = new UserDataRequest(sessionUsername, UserDataResponseListener);
RequestQueue queue = Volley.newRequestQueue(this.getActivity());
queue.add(userDataRequest);
}
}
Php-Code:
$con = mysqli_connect("localhost","web506","lalala","usr_web506_1");
$username = $_POST["username"];
$statement = mysqli_prepare($con,"SELECT * FROM user WHERE username = ?");
mysqli_stmt_bind_param($statement,"s",$username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement,
$userID,
$username,
$password,
$email,
$age,
$realname,
$streetname,
$postcode,
$city,
$state,
$isPremium,
$isLoggedIn);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
$response["success"] = true;
$response["username"] = $username;
$response["password"] = $password;
$response["email"] = $email;
$response["age"] = $age;
$response["realname"] = $realname;
$response["streetname"] = $streetname;
$response["postcode"] = $postcode;
$response["city"] = $city;
$response["state"] = $state;
$response["isPremium"] = $isPremium;
$response["isLoggedIn"] = $isLoggedIn;
}
echo json_encode($response);
?>
So, when i fetch user data i can display them with Toast, change preference.summaries or whatsoever. But if some of the mysql entries are empty/null then nothing happens. the application doesn't crash but it seems that it doesnt get the "success" boolean from the php-file. whats the clue?
thanks in advance.
eirik
should i delete the $response["success"] = false;?
usually i get an alertmessage if the app can't connect to the database and the false bool reaches my application, so i thought its right there.
When i add blanks behind my variables from which i know their DB-cells are empty then jsonresponse delivers a "0" value as string result like this:
$response["realname"] = $realname+" ";
$response["streetname"] = $streetname+" ";
$response["postcode"] = $postcode+" ";
$response["city"] = $city+" ";
$response["state"] = $state+ " ";
i a textview are they displayed row by row as "0".
do i have to work around this inside my application or is there an easy way to filter empty cells somehow and skip to the next one?
$response["success"] = true;
$record_size = 0;
while(mysqli_stmt_fetch($statement)){
$response["success"] = true;
$response["username"] = $username;
$response["password"] = $password;
$response["email"] = $email;
$response["age"] = $age;
$response["realname"] = $realname;
$response["streetname"] = $streetname;
$response["postcode"] = $postcode;
$response["city"] = $city;
$response["state"] = $state;
$response["isPremium"] = $isPremium;
$response["isLoggedIn"] = $isLoggedIn;
$record_size++;
}
$response["record_size"] = $record_size;
echo json_encode($response);
For number of records I am using $record_size variable so that you can get the idea about records. because $response["success"] = true; means you are successfully able to get the DB and for records you can use $response["record_size"].. I hope it will help you..
My workaround looks now like this:
if i get 0 values i replace them with a "missing [...]" from an xml recource.
There was another mismatch too.. it seems that i get my jsonresponse always as a string, but i wanted to get the postcode in my first code as an integer, this didnt work too. so i will have to parse it to an int when i need it this way.
String responseRealName = jsonResponse.getString("realname"); if (responseRealName.equals("0")) {responseRealName = getResources().getString(R.string.MissingRealName);}
String responseStreetName = jsonResponse.getString("streetname"); if (responseStreetName.equals("0")) {responseStreetName = getResources().getString(R.string.MissingStreetName);}
String responsePostcode = jsonResponse.getString("postcode"); if (responsePostcode.equals("0")) {responsePostcode = getResources().getString(R.string.MissingPostcode);}
String responseCity = jsonResponse.getString("city"); if (responseCity.equals("0")) {responseCity = getResources().getString(R.string.MissingCity);}
String responseState = jsonResponse.getString("state"); if (responseState.equals("0")) {responseState = getResources().getString(R.string.MissingState);}
i think my question has been answered enough.

JSONArrayRequest and PHP pair not working

I am creating class which should send JSONArrayRequest using volley with specific params, then find mysql rows which equals these params and send it back. I wrote simple mysql function which receive POST params and Java method which send and receive JSONObjects. But it isn't working and I receive nothing.
This is my PHP file called details.php. It receive parameters from my Android App and send back an array.
require_once __DIR__ . '/db_connect.php'
$db = new DB_CONNECT();
$path= $_POST["path"];
$result = mysql_query("SELECT * FROM modx_ms2_product_files WHERE path = $path") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$json_response = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product ["file"] = $row["file"];
// push single product into final response array
array_push($json_response, $product);
}
// echoing JSON response
echo json_encode($json_response);
$conn->close();
}
This is my method getArray(), which send request and receive response:
public void getarray() {
String path = "1578/";
final String URL = "http://myurl.io/details.php";
HashMap<String, String> params = new HashMap<String, String>();
params.put("path", path);
JsonArrayRequest customarray = new JsonArrayRequest(Request.Method.POST,URL,new JSONObject(params),new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject Obj = response.getJSONObject(i);
pics pic = new pics();
pic.setFile(Obj.getString("file"));
Log.i("cmon", Obj.getString("file"));
pics.add(pic);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(customarray);
}
This is my modx_ms2_product_files table:
http://i.imgur.com/yl1f7Ze.png
http://i.imgur.com/9V6PrBU.png
Have you tried using StringRequest? For some reason when i used JsonArrayRequest i didn't get any response back from the server. If you decide to create a StringRequest you could convert your response to a JSONArray like this:
StringRequest get = new StringRequest(Method.POST, URL, new Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray myArray = new JSONArray(response);
for(int i = 0; i < myArray.length(); i++)
{
JSONObject jObj = myArray.getJSONObject(i);
// get your data here
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Then of course add your request to the request queue.

Get JSON response from PHP file with OkHttp

I need to make simple JSON request from PHP file which is on my localhost server. PHP code executes smoothly and it looks like:
<?php
header('Content-type: application/json');
$db = new PDO('mysql:host=localhost;dbname=nadjiprijevoz;charset=utf8', 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query = "Select * FROM rute";
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
} catch(PDOException $ex) {
// Greska kod izvodjenja querija
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
$rows = $stmt->fetchAll();
if($rows) {
$response["success"] = 1;
$response["message"] = "Rute dohvacene";
$response["rute"] = array();
foreach($rows as $row) {
$ruta = array();
$ruta["id"] = $row["id"];
$ruta["naziv"] = $row["naziv"];
$ruta["polaziste"] = $row["polaziste"];
$ruta["odrediste"] = $row["odrediste"];
array_push($response["rute"] , $ruta);
}
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Nema ruta";
die(json_encode($response));
}
?>
When i try to fetch JSON data with my android application i dont get any response from the PHP file. Im using OkHttp library for fetching response and until now it worked smoothly (i havent been using php files before, only pure json) but when i try to get php response it doesnt work. Main activity code looks like:
public class activityMain extends ActionBarActivity {
private final static String TAG = activityMain.class.getSimpleName();
Ruta[] mRute;
#InjectView(R.id.textView) TextView text1;
#InjectView(R.id.textView2) TextView text2;
#InjectView(R.id.textView3) TextView text3;
String redditUrl = "http://localhost/nadjiprijevoz/connect.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_mainmenu);
ButterKnife.inject(this);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(redditUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
}
#Override
public void onResponse(Response response) throws IOException {
try {
String jsonData = response.body().string();
Log.i(TAG, response.body().string());
if (response.isSuccessful()) {
mRute = parsePostDetails(jsonData);
text1.setText(mRute[0].getNaziv());
text2.setText(mRute[0].getPolaziste());
text3.setText(mRute[0].getOdrediste());
}
} catch (IOException e) {
Log.e(TAG, "Excepiton caught: " , e);
} catch (JSONException e) {
Log.e(TAG, "Excepiton caught: " , e);
}
}
});
}
private Ruta[] parsePostDetails(String jsonData) throws JSONException {
JSONObject rutaObjectJSON = new JSONObject(jsonData);
JSONArray rutaArrayJSON = rutaObjectJSON.getJSONArray("rute");
Ruta[] ruteTemp = new Ruta[rutaArrayJSON.length()];
for (int i = 0; i < ruteTemp.length; i++) {
JSONObject rutaDetailJSON = rutaArrayJSON.getJSONObject(i);
Ruta tempRuta = new Ruta();
tempRuta.setNaziv(rutaDetailJSON.getString("naziv"));
tempRuta.setOdrediste(rutaDetailJSON.getString("odrediste"));
tempRuta.setPolaziste(rutaDetailJSON.getString("polaziste"));
ruteTemp[i] = tempRuta;
}
return ruteTemp;
}
}
Does anyone know where am i making mistake, if you do i would be very thankful.

Making replies to an existing comment system in Android

So we have a comment system in our application, and now we want to be able to add replies to specific comments, like a Facebook wall.
Our Java method for posting a comment:
class PostComment extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddCommentActivity.this);
pDialog.setMessage("Posting Comment...");
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 post_title = title.getText().toString();
String post_message = message.getText().toString();
//We need to change this:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(AddCommentActivity.this);
String post_username = sp.getString("username", "anon");
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("username", post_username));
params.add(new BasicNameValuePair("title", post_title));
params.add(new BasicNameValuePair("message", post_message));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
POST_COMMENT_URL, "POST", params);
// full json response
Log.d("Post Comment attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Comment Added!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Comment Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(AddCommentActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
and our PHP to send to MySQL:
<?php
//load and connect to MySQL database stuff
require("config.inc.php");
$query_params=null;
if (!empty($_POST)) {
//initial query
$query = "INSERT INTO comments ( username, title, message ) VALUES ( :user, :title, :message ) ";
//Update query
$query_params = array(
':user' => $_POST['username'],
':title' => $_POST['title'],
':message' => $_POST['message']
);
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one:
$response["success"] = 0;
$response["message"] = "Database Error. Couldn't add post!";
die(json_encode($response));
}
$response["success"] = 1;
$response["message"] = "Post Successfully Added!";
//echo json_encode($response);
} else {
?>
I've made a new table in MySQL called replies which has:
reply_id (INT AI)
reply_content (text)
reply_postid (INT)
reply_byusername (varchar)
I'm guessing somehow we make an arraylist that picks the commentid from the original comment and we can chain that to replies, but I don't know how. I generally have no idea how to proceed from here.

Returning success on query successfully in PHP to java

I need to check if the username is already present in the database.If so then only Login. After login,I need a response to be sent from php file to java class saying success.
When I access the result array in my java file using Json,it is giving NULL though the Username is already present in Database.
Any Help?
I am using the below Php and java code
<?php
include("db_config.php");
$myusername = $_GET['username'];
$mypassword = $_GET['password'];
$sql="SELECT id FROM tablename WHERE username='$myusername' and password='$mypassword'";
echo $sql;
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$active=$row['active'];
$count=mysql_num_rows($result);
if($count==1)
{
$result['login'] == 'success';
}
else
{
$result['login'] == 'failed';
}
echo json_encode($result);
This is my Java code
btnLogin.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
username= textFieldUserName.getText().toString();
password = textFieldPassword.getText().toString();
// discount = textFieldDiscount.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username",username));
params.add(new BasicNameValuePair("password",password ));
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
try {
status = json.getString(TAG_SUCCESS);
System.out.println(" status is "+status);
if(status.equalsIgnoreCase("success"))
{
System.out.println("Login success");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Also,I tried
if(response.getStatusLine().getStatusCode()==200)
which returns 200 if OK from the from the server.
[Edit: Code ReFormation]
use this code for java
JSONObject json = (JSONObject)jParser.makeHttpRequest(url_all_products, "GET", params);
try {
//status = json.getString(TAG_SUCCESS);
String status = (String) json.get("login");
System.out.println(" status is "+status);
if(status.equalsIgnoreCase("success"))
{
System.out.println("Login success");
}
}

Categories

Resources