Read error with Json file - android

I am working on an app in Android Studio that downloads a json file from a php query, however when I have managed to read the contents of the json file from android, this contents does not behave as text, because when comparing a text entered from the app against the read from the json file, it never matches despite being the same text. (Example: password text from app and the password from the json file).
Php Code:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
include('functions.php');
$col=$_GET["col"];
$colbus=$_GET["colbus"];
$tabla=$_GET["nomtable"];
$todfilas=$_GET["todasf"];
$dbuser =$_GET["username"];
$dbpass=$_GET["password"];
$dbbase=$_GET["dbname"];
//echo "$todfilas <br>";
if($todfilas == 1){
$sqlt="SELECT * FROM $tabla";
}else{
$sqlt="SELECT * FROM $tabla WHERE $col='$colbus'";
}
//echo "$sqlt <br>";
if($resultset=getSQLResultSet($sqlt,$dbuser,$dbpass,$dbbase)){
while ($row = $resultset->mysqli_fetch_array(MYSQLI_NUM)){
echo json_encode($row);
}
}
?>
Code from Android Studio:
private class ConsultData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "No es posible cargar pagina web o la direccion es invalida!";
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
JSONArray ja = null;
try {
ja = new JSONArray(result);
Log.d("Password:",ja.getString(7)+"="+logPass.getText().toString().trim());
logPass2.setText(ja.getString(7).trim());
String pass1 =logPass2.toString();
String pass0 = logPass.toString().trim();
if(pass0==pass1){
showAlertDialog("Session:","login is valid!");
} else{
showAlertDialog("Session:","password does not match!");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I'm not sure if the way to create the json file in the php query is the problem? because I can see the contents of the json array in Android Studio, but when I compare text from json array, they do not match even if they are the same ("123" = "123").

As seeing your code you doing so many mistakes like you are getting textview value thats not right way
change code like this
String pass1 =logPass2.getText().toString();
String pass0 = logPass.getText().toString().trim();
Also comparsion of string
if(pass0.equals(pass1)){
showAlertDialog("Session:","login is valid!");
} else{
showAlertDialog("Session:","password does not match!");
}
instead of this
if(pass0==pass1){
showAlertDialog("Session:","login is valid!");
} else{
showAlertDialog("Session:","password does not match!");
}

Related

for not running in onPostExecute

I am getting some info from the server and the for used in onPostExecute was supposed to store the data into 2 different arrays. The server's response it's alright, it gets to the app, it is recognized as a JSON object, but when it comes to transforming it to a JSONArray to get the elements it just gets over that part of the code, as it wouldn't be written. So, after the JSONArray departamenteArray = obj.getJSONArray("departamente"); line, it just goes over the rest of it without making any changes.
.java code:
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//hiding the progressbar after completion
try {
//converting response to json object
JSONObject obj = new JSONObject(s);
//if no error in response
if (!obj.getBoolean("error")) {
JSONArray departamenteArray = obj.getJSONArray("departamente");
for (int i = 0; i < departamenteArray.length(); i++) {
JSONObject dep = departamenteArray.getJSONObject(i);
// Verificare daca s-au primit probleme trimise de server
if (!dep.isNull("Departament")) {
String departament = SchimbareDiactritice(dep.getString("Departament")).replace("&","");
String id_departament= dep.getString("id_departament");
id_departamente.add(id_departament);
departamente.add(departament);
}
}
} else {
Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
layout_validare.setVisibility(GONE);
linearLayout_obs_redirectionare.setVisibility(View.VISIBLE);
}
JSON response from the server :
{
"error": false,
"message": "Alerte reimprospatate",
"departamente": [{
"Departament": "Parcări",
"id_departament": 2
}, {
"Departament": "Trafic rutier și iluminat public",
"id_departament": 3
}, {
"Departament": "Salubritate și vandalism",
"id_departament": 4
}, {
"Departament": "Altele",
"id_departament": 5
}]
}
.php code on the server side:
if($stmt->num_rows > 0){
$stmt->bind_result($departament, $id_departament);
while($stmt->fetch()) {
$departamente[] = array (
"Departament"=>$departament,
"id_departament"=>$id_departament
);
$response['error'] = false;
$response['message'] = 'Alerte reimprospatate';
$response['departamente']= $departamente;
It seems that after a restart of the Android Studio it works. It must have been only a bug. The code shown above it's working properly.

Waiting for AsyncTask postExecute to continue

I am pretty new with the concept of asynctask and i have an asynctask that gets me a json from an api with parameter an then(postexecute) puts the content inside textviews to be shown(they are set visible after setting the text), the thing is i am trying to validate that the json isnt actually empty, and with my code i actually do that, but if the parameter i use is correct, the validation still detects that its empty, if i try to get it again(by pressing the button that triggers the asynctask) after 2 or three tries it will actually get it tho, i think its because i am doing it on the background, here is the asynctask
private class ConsultarDatos extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
JSONArray ja = null;
try {
ja = new JSONArray(result);
txtNombre.setText(ja.getString(0) +" " + ja.getString(1));
txtCategoria.setText(ja.getString(2));
txtDNI.setText(ja.getString(3));
txtEstado.setText(ja.getString(4));
//working=false;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
and here is what i am trying to do
btnGenerar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new ConsultarDatos().execute("https://api-adress/file.php?DNI=" + etDNI.getText().toString());
//while(working)
//{
//}
if (txtCategoria.getText()!="") {
btnGenerar.setVisibility(View.INVISIBLE);
etDNI.setVisibility(View.INVISIBLE);
txtCategoria.setVisibility(View.VISIBLE);
txtDNI.setVisibility(View.VISIBLE);
txtEstado.setVisibility(View.VISIBLE);
txtNombre.setVisibility(View.VISIBLE);
imgTarjeta.setVisibility(View.VISIBLE);
}
else
{
Toast.makeText(getApplicationContext(),"DNI Incorrecto",Toast.LENGTH_LONG).show();
}
}
});
as i commented i tried to do a while that would wait until the textsviews are all set but that just crashed my app
I resolved it, just moved the the visibility set and validation to the end of the onPostExecute and just to be sure i put the toast in the exception too just so the user gets some feedback
protected void onPostExecute(String result) {
JSONArray ja = null;
try {
ja = new JSONArray(result);
txtNombre.setText(ja.getString(0) +" " + ja.getString(1));
txtCategoria.setText(ja.getString(2));
txtDNI.setText(ja.getString(3));
txtEstado.setText(ja.getString(4));
if (txtCategoria.getText()!="") {
btnGenerar.setVisibility(View.INVISIBLE);
etDNI.setVisibility(View.INVISIBLE);
txtCategoria.setVisibility(View.VISIBLE);
txtDNI.setVisibility(View.VISIBLE);
txtEstado.setVisibility(View.VISIBLE);
txtNombre.setVisibility(View.VISIBLE);
imgTarjeta.setVisibility(View.VISIBLE);
}
else
{
Toast.makeText(getApplicationContext(),"DNI Incorrecto",Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"DNI Incorrecto",Toast.LENGTH_LONG).show();
}
}
Use something like https://www.getpostman.com/ to see what the result of your API call is. Right now it seems like you don't know what you're getting back, and how consistently it comes back. You need to validate that your server is sending you back valid data.
Using a json library to parse the JSON response, such as GSON or Moshi would help you out as well. Right now you're trying to get the values based on arbitrary numbers. You could be having an exception from just one field missing, but there's not enough info to tell. Gson is fairly easy to set up in my experience: https://github.com/google/gson

How to retrieve particular row data from mysql through android Volley or JSON?

Hi guys i have already made login and register using volley library and data gets saved successfully as shown in the snap 1 below. Now my question is how to retrieve particular or specific row data for the particular user when he/she logins?? For example if user admin gets logged in how to fetch her entire row alone
saved data in server side
<?php
$conn = mysql_connect("localhost", "root", "");
if(isset($conn))
{
mysql_select_db('your_db', $conn);
}
else
{
echo 'Sorry,can not connect to database' ;
}
$userid = isset($_GET['id']) ? mysql_real_escape_string($_GET['id']) : "";
$qur = mysql_query("select usename,other_fields from `your_tbl` where userid= $userid");
$result =array();
while($r = mysql_fetch_array($qur)){
extract($r);
$result[] = array("usename" => $usename,"other_fields" => $other_fields);
}
$json =array("data"=>$result);
mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
You will have to use server side scripting. Webservice that will fetch that particular row of data.
The script should take your input parameters and give you the out put in Json Array or Object.
You then hit this script using volley and the response you receive can then be utilized for the next step.
//call volley get method and get data in success method
public void onSuccess(string response)
{
try {
String s = new String(response);
JSONObject jsonObject = new JSONObject(s);
if (jsonObject.has("data")) {
JSONArray country =jsonObject.getJSONArray("data");
for (int i = 0; i < country.length(); i++) {
JSONObject cnt = country.getJSONObject(i);
String res=cnt.getString("username"));
//now you can use res as per your requirement
}
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}

Not getting anything return from query written in php file

PHP file
$con=mysqli_connect("mysql3.000webhost.com","a9225790_studio","pwd","a9225790_studio");
$sub=$_REQUEST['$subject'];
$data=mysqli_query($con,"select * from Questions where Subject='$sub'");
if(mysqli_num_rows($data)>0)
{
$resp['question-status']="SUCCESS";
while($r=mysqli_fetch_array($data))
{
$resp['Questions'].=$r['Question'].",".$r['Option1'].",".$r['Option2'].",".$r['Option3'].",".$r['Option4'].",".$r['Answer'].";";
}
echo json_encode($resp);
}
else
{
$resp['question-status']="ERROR";
echo json_encode($resp);
}
mysqli_close($con);
?>
Select query not returning anything for the $sub Subject. However Question,options and answer for the corresponding $sub Subject is there in the table.
It always going in else loop
$resp['question-status']="ERROR";
Android Code
public class Exam extends AppCompatActivity implements View.OnClickListener {
TextView no,ques;
RadioGroup op;
RadioButton op1,op2,op3,op4;
Button ne,pass,submit;
String correctAnswer,userAnswer,n,subject;
int totalQuestion,currentQuestion;
ArrayList<String> allQuestion=new ArrayList<String>();
int score=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exam);
Bundle b=getIntent().getExtras();
n=b.getString("UN");
subject=b.getString("SUB");
userAnswer="";
// time=(TextView)findViewById(R.id.time);
//totq=(TextView)findViewById(R.id.totq);
no=(TextView)findViewById(R.id.no);
ques=(TextView)findViewById(R.id.ques);
op=(RadioGroup)findViewById(R.id.op);
op1=(RadioButton)findViewById(R.id.op1);
op2=(RadioButton)findViewById(R.id.op2);
op3=(RadioButton)findViewById(R.id.op3);
op4=(RadioButton)findViewById(R.id.op4);
ne=(Button)findViewById(R.id.ne);
pass=(Button)findViewById(R.id.pass);
submit=(Button)findViewById(R.id.submit);
ne.setOnClickListener(this);
pass.setOnClickListener(this);
submit.setOnClickListener(this);
op1.setOnClickListener(new MyAnswerListener());
op2.setOnClickListener(new MyAnswerListener());
op3.setOnClickListener(new MyAnswerListener());
op4.setOnClickListener(new MyAnswerListener());
ArrayList<NameValuePair> list=new ArrayList<NameValuePair>(1);
list.add(new BasicNameValuePair("subject",subject));
Toast.makeText(getApplicationContext(),subject,Toast.LENGTH_SHORT).show();
String res=MyJsonToStringConverter.convert(list,"http://rgworks.site90.net/android_studio/e_exam/FetchQuestions.php");
try
{
JSONObject j=new JSONObject(res);
if(j.getString("question-status").equals("SUCCESS"))
{
String [] data=j.getString("Questions").split(";");
for (String s1 : data)
{
allQuestion.add(s1);
}
}
else if(j.getString("question-status").equals("ERROR"))
{
Toast.makeText(getApplicationContext(), "No questions available", Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Log.e("log_e", e.toString());
}
totalQuestion=allQuestion.size();
if (totalQuestion == 0)
{
Toast.makeText(getApplicationContext(),"No Question",Toast.LENGTH_SHORT).show();
}
else
{
nextQuestion();
}
}
public void nextQuestion()
{
String [] q1=allQuestion.get(currentQuestion).split(",");
no.setText(String.valueOf(currentQuestion+1 +"."+" "));
ques.setText(q1[0]);
op1.setText(q1[1]);
op2.setText(q1[2]);
op3.setText(q1[3]);
op4.setText(q1[4]);
correctAnswer=q1[5];
op.clearCheck();
}
And in the android code i have checked for the value of 'subject' by printing it in Toast. Before sending this value to Php file it is Successfully printed. But in the php code it is unable to get anything from the table for the Subject '$sub'.
First i would suggest that you use PDO instead of mysqli in your php.
The php code seems ok but PDO is better agents sql injection.
And in your Android code use Volley i can give you good tutorials so you can learn ti, it is easy, if you want

Android cannot check json success and error response

I am struggling with one situation. I am returning some json data from PHP server my code is as follows,
PHP API code:
if ($user != false) {
$result = mysql_query("SELECT stock_name,stock_location FROM btrack_stock WHERE user_id= '$user_id'") or die(mysql_error());
$rows = array();
$count = mysql_num_rows($result);
if($count > 0){
while ($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode(array('usertransaction' => $rows));
}else{
$response["error"] = 1;
$response["error_msg"] = "You do not have any transaction so far. ";
echo json_encode($response);
}
}
On android side, I use a class that extends AsyncTask and on my onPostExecute I use:
protected void onPostExecute(JSONObject json) {
try {
if(json.getString("error_msg") != null){
String err = json.getString("error_msg");
stock_error.setText(err);
stock_error.setVisibility(View.VISIBLE);
pDialog.dismiss();
}else{
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_LONG).show();
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Well actually, I wanted to display error message that is returned from PHP server and display all the data if I got success message (here I am showing a Toast).
My question is how can we display error message if json returns error message and display success if json does not return error message.
* My code works fine if I get error_msg as json response but if I return other data the app stuck in process dialog with a warning in LogCat as " There is no value for error_msg".
Thanks in Advance.
Try this:
if json.isNull("error_msg") {
do_something()
}
else {
json.getString("error_msg");
do_something_else()
}

Categories

Resources