dtp19819
dtp19819
2017-04-23 13:55

Retrofit 2.0 GET @Query参数未传递给PHP的$ GET [“”];

已采纳

I am new to Retrofit 2.0 and have been trying to solve this problem for the past few days without any progress. I have a working code which uses Retrofit 2.0 in order to populate an Android activity's recyclerview with JSON data fetched from SQL DB by using a PHP script.

After having looked at many various posts and tutorials, I have modified the above-described working code in order to enable a datePicker's selected date to be sent to PHP's script via Retrofit's GET @Query Parameter within Retrofit's interface class and intercepted by $selected_date = $GET["date"]; inside PHP's script.

If I set a value inside selected_date_lectures.php like this => $selected_date = "2017-04-22"; data is successfully fetched back to the recyclerview upon datePicker's selection. Also the DatePicker's date is also successfully displayed using a toast upon selection.

This makes me believe that I must be doing something wrong when making the Retrofit Get @Query request or when trying to get the @query parameter from PHP using $GET["date"]; although I don't spot anything that could be wrong in my code.

I ran out of ideas to solve this issues and would really appreciate any suggestions.

Below is a code fragment from DatePicker's onDataSet's method which is when HTTP request is triggered upon Date selected.

@Override

public void onDateSet(DatePickerDialog view, int Year, int Month, int Day) {

    // For some reason selected month's output is previous month
    Month +=1;

    // Selected date is formated in the same manner as DB's date which will be compared to find a match.
    String date = Year + "-" + String.format("%02d", Month) + "-" + String.format("%02d", Day);

    swipeRefreshLayout.setRefreshing(true);

    ApiInterface apiService =
            ApiClient.getClient().create(ApiInterface.class);

    // Selected date from date picker is added to apiService.getSelectedDateLectures(date);

    Call<List<Message>> call = apiService.getSelectedDateLectures(date);

    call.enqueue(new Callback<List<Message>>() {

        @Override
        public void onResponse(Call<List<Message>> call, Response<List<Message>> response) {

            // clear the inbox
            messages.clear();

            swipeRefreshLayout.setRefreshing(false);

            // add all the messages
            // messages.addAll(response.body());

            // TODO - avoid looping
            // the loop was performed to add colors to each message

            for (Message message : response.body()) {
                // generate a random color
                // message.setColor(getRandomMaterialColor("400"));
                messages.add(message);

            }


            mAdapter.notifyDataSetChanged();
            swipeRefreshLayout.setRefreshing(false);

        }

        @Override
        public void onFailure(Call<List<Message>> call, Throwable t) {
            Toast.makeText(getApplicationContext(), "Unable to fetch json: " + t.getMessage(), Toast.LENGTH_LONG).show();
            swipeRefreshLayout.setRefreshing(false);
        }


    });

    Toast.makeText(MainActivity.this, date, Toast.LENGTH_LONG).show();
}

ApiClient.java - This is where the interface's HTTP request is being constructed

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class ApiClient {

public static final String BASE_URL = "http://lankabentara.tech/FC6P01/android_sign_attendance/";

private static Retrofit retrofit = null;

public static Retrofit getClient() {
    if (retrofit == null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
  }
}

ApiInterface.java -This is where all the network requests are written.

import info.codex.app.model.Message;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

public interface ApiInterface {

// HTTP OPERATION => Fetch today's lectures
@GET("today_lectures.php")
Call<List<Message>> getInbox();

// HTTP OPERATION => Fetch selected date's lectures
@GET("selected_date_lectures.php")
Call<List<Message>> getSelectedDateLectures(@Query("date") String date);
}

selected_date_lectures.php -Lastly, the third line is where I am attempting to get the date parameter using $GET["date"];

<?php
 ini_set('date.timezone', 'Europe/London');

 $selected_date =  $GET["date"];

 $host="localhost"; //replace with database hostname
 $username="user"; //replace with database username
 $password="password"; //replace with database password
 $db_name="db_name"; //replace with database name

 $con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
 mysql_select_db("$db_name")or die("cannot select DB");
 //include("user_control.php"); 
 session_start();

 $uid = $_SESSION['user'];

 $sql = "select users.id,
           degree.degree_id,
           degree.degree_title,
           modules.module_id,       
           modules.degree_id,
           modules.title,
           LectureRoom.code,   
           LectureRoom.date,
           LectureRoom.time,
           LectureRoom.end_time
           from LectureRoom
     JOIN modules ON modules.module_id = LectureRoom.module_id
     JOIN degree ON degree.degree_id = modules.degree_id
     JOIN users ON users.degree_id = degree.degree_id
    WHERE users.id = '32' AND DATE(LectureRoom.date)= '$selected_date'; ";

   $result = mysql_query($sql);
   $json = array();

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

At this point any help would be much appreciated. Thank you in advance.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dqm7854 dqm7854 4年前

    $selected_date = $GET["date"];

    It should be $_GET not $GET, so:

    $selected_date = $_GET["date"];
    

    Mandatory RTM here. Also consider error_reporting(E_ALL); while you are developing.

    点赞 评论 复制链接分享