I get nothing from php on android

Asked

Viewed 188 times

0

Good afternoon I have a problem. I can fetch all the information I have in the table, but when changing the code so that I only appear the information of a certain person error and returns no value value for android. I’m new on android so please help. If you can post the code fixed Thanks.

Functional Php code (Returns the whole table(not that goal)): Here it works: log: jsonResult: {"info":[{"Nprocess":"467","Dataquery":"11-7-2014","Schedulequery":"14:41"....}]}

  <?php
       $host     = "XXXXX";
       $username = "XXXXX";
       $password = "XXXXX";
       $db_name  = "android";

       $con = mysql_connect("$host", "$username", "$password") or die("cannot connect");
       mysql_select_db("$db_name") or die("cannot select DB");
       $tec    = $_POST['Tecnica'];
       $sql    = "select * from info order by Registo desc";
       $result = mysql_query($sql);
       $json   = array();

       if (mysql_num_rows($result)) {
       while ($row = mysql_fetch_assoc($result)) {
           $json['info'][] = $row;
       }
      }
     mysql_close($con);
     echo json_encode($json);
   ?> 

Php code I want to put to work(goal: only show the information of the person who logs in): The PROBLEM with this code is that it does not send me anything for android. The log: jsonResult: []

      <?php
      $host     = "XXXXX";
      $username = "XXXXXX";
       $password = "XXXXXX";
      $db_name  = "android";

       $con = mysql_connect("$host", "$username", "$password") or die("cannot connect");
      mysql_select_db("$db_name") or die("cannot select DB");
      $tec    = $_POST['Tecnica'];
      $sql    = "select * from info where Tecnica = $tec order by Registo desc";
      $result = mysql_query($sql);
      $json   = array();

       if (mysql_num_rows($result)) {
        while ($row = mysql_fetch_assoc($result)) {
          $json['info'][] = $row;
        }
         }
        mysql_close($con);
         echo json_encode($json);
       ?> 

And my class (without changing the class, works the first php but not the second):

public class Readinfo extends Activity {

ListAdapter adapter;
String NTECNICA;
private String jsonResult;
private String url = "http://www.cresceranorte.com/WebService/info.php";
private ListView listView;

@Override
protected void onCreate(Bundle savedInstanceState) {


    super.onCreate(savedInstanceState);

    setContentView(R.layout.read_info);
    Bundle extras = getIntent().getExtras();
    if (extras != null) {

        Intent intent = getIntent();
        NTECNICA=  intent.getExtras().getString("NTECNICA");
        Log.d("Atencao NTecnica", NTECNICA);

        //Toast.makeText(MainMenu.this, value, Toast.LENGTH_SHORT).show();
    }
    listView = (ListView) findViewById(R.id.list);
    accessWebService();

}




@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
public void addInfo(View v)
        {
                Intent i = new Intent(ReadInfo.this, AddInfo.class);

            i.putExtra("NTECNICA",NTECNICA);
                startActivity(i);
            }


public void actList(View v)
{
    Intent i = new Intent(ReadInfo.this, ReadInfo.class);
    startActivity(i);
}




// Async Task to access the web
public class JsonReadTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {


        String post_Tecnica=NTECNICA;

        HttpClient httpclient = new DefaultHttpClient();
        HttpGet ger = new HttpGet(url);
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("Tecnica", post_Tecnica));

        String oo;
        oo = String.valueOf(nameValuePairs);
        Log.d("HTTP: ", oo);
        try {

            HttpResponse response = httpclient.execute(ger);

            oo = String.valueOf(response);
            Log.d("HTTPResponse: ", oo);
            jsonResult = inputStreamToString(
                    response.getEntity().getContent()).toString();
            Log.d("Atencao jsonResult: ", jsonResult);

        }

        catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private StringBuilder inputStreamToString(InputStream is) {
        String rLine = "";
        StringBuilder answer = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        try {
            while ((rLine = rd.readLine()) != null) {
                answer.append(rLine);
            }
        }

        catch (IOException e) {
            // e.printStackTrace();
            Toast.makeText(getApplicationContext(),
                    "Error..." + e.toString(), Toast.LENGTH_LONG).show();

        }
        return answer;
    }

    @Override
    protected void onPostExecute(String result) {
        ListDrwaer();
    }
}// end async task

public void accessWebService() {
    JsonReadTask task = new JsonReadTask();
    // passes values for the urls string array
    task.execute(new String[] { url });
}

// build hash set for list view
public void ListDrwaer() {

    List<Map<String, String>> consultasList = new ArrayList<Map<String, String>>();


    try {

        JSONObject jsonResponse = new JSONObject(jsonResult);
        JSONArray jsonMainNode = jsonResponse.optJSONArray("info");


        for (int i = 0; i < jsonMainNode.length(); i++) {
            JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
            String name = jsonChildNode.optString("NProcesso");
            String number = jsonChildNode.optString("DataConsulta");
            String dat = jsonChildNode.optString("HoraConsulta");
            String outPut = "Nº Processo: "+ name + "\n" + "Data: "+ number + "\n" + "Hora: "+ dat + "\n";
            consultasList.add(createEmployee("employ", outPut));
        }
    } catch (JSONException e) {
        Toast.makeText(getApplicationContext(), "Error ListDrwaer " + e.toString(),
                Toast.LENGTH_SHORT).show();
        Log.d("Error ListDrwaer  ", e.toString());
    }

    SimpleAdapter simpleAdapter = new SimpleAdapter(this, consultasList,
            android.R.layout.simple_list_item_1,
            new String[] { "employ" }, new int[] { android.R.id.text1 });
    listView.setAdapter(simpleAdapter);
}

private HashMap<String, String> createEmployee(String name, String number) {
    HashMap<String, String> employeeNameNo = new HashMap<String, String>();
    employeeNameNo.put(name, number);
    return employeeNameNo;
}

}

  • The "error" is evidently in the query, because the parameter you passed in the second code makes the query not find any entry with these requirements, which makes the query come back empty. Try to check if the variable $tec is not null, and also if this query returns something if tested directly in the Mysql console.

  • Also, avoid using mysql_query(), even more when you pass variables directly in the query. This function is deprecated and has security loopholes. Try to use Mysqli or PDO in her stead.

  • As you said most likely is the $tec variable being empty the problem is that I’ve been watching this for a day but I just don’t know where I went wrong in class. This class is the junction of another 2, the original that was used to read the information of the whole table and another class that I use to enter values.

  • I tried to use the class that sends values to the table to simply send a variable to do Where but it seems that it is not so simple

1 answer

1

Your SQL query is not escaping the variable, if it is a string, it may be causing problems when the database runs the query.

Change to:

$sql=sprintf("select * from info where Tecnica = '%s' order by Registo desc", $tec);

In addition, the function group mysql_* is precarious and insecure. Use the group mysqli_* or the PDO class.

  • Thanks for the answer but that’s not the problem I insert it in php but gives me the same error.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.