Making replies to an existing comment system in Android - java

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.

Related

Android Volley - POST-Parameter not reaching PHP-Script

I want to get Infos from a Database. When i use a Query without parameters (e.g. "Select * from users;" my script works fine.
Now i have the following script which returns an empty Array. When i replace the $groupId in script with a string value (e.g. "Group1") it returns the expected Items.
<?php
$sql = "";
if($_SERVER['REQUEST_METHOD']== 'POST') {
$flag = array();
$groupId = $_POST['groupId'];
require_once('dbConnect.php');
$sql = "SELECT * FROM users where groupId = '$groupId'";
if($out = mysqli_query($con,$sql)){
//echo "Successfully Registered";
while($row = mysqli_fetch_array($out))
{
$flag[] = $row;
}
print(json_encode($flag));
}else{
echo "Could not register";
}
}else{
echo 'error';
}
//mysqli_close($con);
?>
When i call the following function with the hashmap hashMapGetNames.put("groupId", "Group#1");
then i get an empty array and the info: "No, Group ID is not set"
public ArrayList<String> get(String url, final HashMap<String, String> hashMap, final Context context) {
//Download the items from DB
final ArrayList<String> items = new ArrayList<>();
RequestQueue queue = Volley.newRequestQueue(context);
JSONObject parameters = new JSONObject(hashMap);
final JsonRequest<JSONArray> jsonArrayRequest = new
JsonRequest<JSONArray>(Request.Method.GET, url, parameters.toString(),
new com.android.volley.Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
if(jsonArray == null){
Log.d("Downloader", "FAIL: NO NAMES FOUND");
}
else {
for (int zähler = 0; zähler < jsonArray.length(); zähler++){
try {
Log.d("Downloader", "sind bei zähler " + zähler);
JSONObject object = jsonArray.getJSONObject(zähler);
String name = object.getString("name");
Log.d("Name", name);
items.add(name);
}
catch (JSONException e) {
Log.d("Downloader", "Catching exception");
e.printStackTrace();
}
}
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Downloader", "Error: " + error.toString());
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Log.d("Downloader", "gettingParams");
return hashMap;
}
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
Log.d("Downloader", "parsing Network response");
try {
String jsonString = new String(response.data,
HttpHeaderParser
.parseCharset(response.headers));
Log.d("Downloader", "Parsing success");
return Response.success(new JSONArray(jsonString),
HttpHeaderParser
.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
Log.d("Downloader", e.toString());
return Response.error(new ParseError(e));
} catch (JSONException je) {
Log.d("Downloader", je.toString());
return Response.error(new ParseError(je));
}
}
};
queue.add(jsonArrayRequest);
return items;
}
So the Script seems right but the parameter does not reach the Script. Any Ideas where the error could hide?
EDIT: I edited the code like shown in the tutorial commented below and use the same dbConnect.php file. but it prints out error - so the problem still exist. That means that the Request Method is not "Post".
Android Monitor prints out:
parsing Network response
Downloader: Parsing success
Error: com.android.volley.ParseError: org.json.JSONException: End of input at character 0
try this code...
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Creating parameters
Map<String,String> params = new Hashtable<String, String>();
//Adding parameters
params.put("groupId", "122");
//returning parameters
return params;
}

com.android.volley.ParseError: org.json.JSONException: Value <html><body><script of type java.lang.String cannot be converted to JSONObject

I am trying to parse a JSON in Android, a basic Login and Password Screen
I am getting the following error
com.android.volley.ParseError: org.json.JSONException: Value html body script of type java.lang.String cannot be converted
to JSONObject
Here is the PHP CODE
<?php
header("Content-type: application/json");
$hostname="sql313.freecluster.eu";
$user="fceu_18433487";
$pass="password";
$dbname="fceu_18433487_testdb";
$db=mysqli_connect($hostname,$user,$pass,$dbname);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$username =$_POST["Email"];
$password = $_POST["Password"];
$statement=mysqli_prepare($db,"SELECT * FROM `login` WHERE `Email` = ? AND `Password` = ?");
mysqli_stmt_bind_param($statement,"ss",$username,$password);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement,$username,$password);
$response = array();$rearray=array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement))
{
$response["success"] = true;
$response["username"] = $username;
$response["password"] = $password;
$rearray["username"] = $username;
$rearray["password"] = $password;
}
echo json_encode($response);
?>
And here is My code where I do the Json Parsing in Android
JsonObjectRequest jsonRequest= new JsonObjectRequest(Request.Method.POST, login_URL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject o = new JSONObject(String.valueOf(response));
String name12=o.getString("success");
Toast.makeText(getApplicationContext(),name12,Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),error.toString(),Toast.LENGTH_LONG).show();
Log.d("lala",error.toString());
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("Email",e1.getText().toString());
params.put("Password",e2.getText().toString());
return params;
}
};
I have tried running this script on Postman but was not able to get any preview
What am I doing wrong here ?

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.

MySQL request from android error

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

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