改造:onFailure().....预计BEGIN_OBJECT但是STRING

时间:2017-08-17 19:04:08

标签: java php android retrofit2

我试图让onResponse()在我的回调中执行。由于某种原因onFailure不断被调用,即使服务器返回200代码,我也完整地获取我的数据。

我不确定onResponse必须要做什么才能正确执行,这样我就可以解析JSON并将对象添加到List View中。

相关片段: -

public class ActivePostFragment extends ListFragment  implements AdapterView.OnItemClickListener, OnClickListener{
    private ProgressBar progress;
    private Button btn_newPost;
    private RecyclerView recyclerView;
    private MyItemRecyclerViewAdapter mAdapter;
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_activepost,container,false);
        initViews(view);
        int uIdValue = getArguments().getInt("userID");
        Log.d(Constants.TAG, String.valueOf(uIdValue));
        progress.setVisibility(View.VISIBLE);
        loadPostsProcess(uIdValue);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        return view;
    }
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    }
    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.newPost:
                goToNewPost();
                break;
        }
    }
    private void initViews(View view){
        btn_newPost = (Button) view.findViewById(R.id.newPost);
        recyclerView = (android.support.v7.widget.RecyclerView) view.findViewById(R.id.recyclerView);
        btn_newPost.setOnClickListener(this);
        progress = (ProgressBar)view.findViewById(R.id.activePostProgress);
    }
    private void loadPostsProcess(int uIdValue) {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
        RequestInterface requestInterface = retrofit.create(RequestInterface.class);
        User user = new User();
        ServerRequest request = new ServerRequest();
        request.setOperation(Constants.RETRIEVE_ALL_OPERATION);
        request.setUser(user);
        final Call<PostsServerResponse> response = requestInterface.postsByUser(uIdValue);
            response.enqueue(new Callback<PostsServerResponse>() {
                @Override
                public void onResponse(Call<PostsServerResponse> call, retrofit2.Response<PostsServerResponse> response) {
                    PostsServerResponse resp = response.body();
                    String jsonServerPosts = resp.getPosts();

                    Type listType = new TypeToken<ArrayList<Post>>(){}.getType();
                    final ArrayList<Post> jsonArrayList = new Gson().fromJson(jsonServerPosts, listType);
                    Log.d(Constants.TAG, jsonArrayList.toString());

                    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
                    recyclerView.setLayoutManager(mLayoutManager);
                    recyclerView.setItemAnimator(new DefaultItemAnimator());
                    recyclerView.setAdapter(new MyItemRecyclerViewAdapter(jsonArrayList, getActivity()));
                    progress.setVisibility(View.INVISIBLE);
                }
                @Override
                public void onFailure(Call<PostsServerResponse> call, Throwable t) {
                    Log.d(Constants.TAG, "Retrofit: onResponse not called, onFailure called instead... ");
                    Log.d(Constants.TAG, t.getStackTrace().toString());
                    Log.d(Constants.TAG, t.getMessage());
                    Snackbar.make(getView(), t.getLocalizedMessage(), Snackbar.LENGTH_INDEFINITE).show();
                    progress.setVisibility(View.INVISIBLE);
                }
            });
    }
    private void goToViewPost(){
    }
    private void goToNewPost(){
        Fragment newPost = new NewPostFragment();
        FragmentTransaction ft = getFragmentManager()
                .beginTransaction();
        ft.replace(R.id.fragment_frame, newPost);
        ft.commit();
    }
}

请求界面: -

public interface RequestInterface {

@POST("index.php/")
Call<LoginServerResponse> operation(@Body ServerRequest request);

@GET("activePosts.php/")
Call<PostsServerResponse> postsByUser(@Query("uid") int userID);}

ServerResponse类:

public class PostsServerResponse {
    private String result;
    private String message;
    private String posts;
    public String getResult() {
        return result;
    }
    public String getMessage() {
        return message;
    }
    public String getPosts() {
        return posts;
    }
}

php代码: -

require_once 'Functions.php';
$fun = new Functions();

if ($_SERVER['REQUEST_METHOD'] == 'GET'){
  $queryUserID = htmlspecialchars($_GET["uid"]);
  echo 'url query ID is: '.$queryUserID.'. ';
  echo $fun -> getPosts($queryUserID);

的functions.php:

public function getPosts($queryUserID){
      $db = $this -> db;

  if ($db -> postsExist($queryUserID)){
    $result = $db -> getUserPosts($queryUserID);
    $response["result"] = "Success. ";
    $response["message"] = "Posts found. ";
    // might need to handle the formatting of the '$posts' object if there are multiple lines
    $response["posts"] = $result;
    return json_encode($response);
  }
  else{
    echo 'no active posts for this user ID. ';
  }
}

DBOperations:

public function getUserPosts($queryUserID){
    $sql = 'SELECT title, content FROM users JOIN post
                ON post.userID = users.sno WHERE sno = ?';
    $queryStmt = $this -> conn -> prepare($sql);
    if ($queryStmt -> bindParam(1, $queryUserID, PDO::PARAM_INT)) {
        echo '<br> userID: '.$queryUserID.' URL parameter bound successfully. </br>';
        if($queryStmt -> execute() ){
            echo '<br> query execution successful. there are rows. </br>';
            $resultSet = $queryStmt -> fetchAll(PDO::FETCH_ASSOC);

            return $resultSet;
        }
    }
}

这是我对服务器的回复:

url query ID is: 3. <br> userID: 3 URL parameter bound successfully. </br><br> query execution successful. there are rows. </br>{"posts":[{"title":"test title 1","content":"hey this is the content for test title 1"},{"title":"test title 2","content":"hey this is the content for the second post!"}]}

这是堆栈跟踪和异常:

  

[Ljava.lang.StackTraceElement; @ efa7528    java.lang.IllegalStateException:预期为BEGIN_OBJECT但在第1行第1行为STRING

如果我没有包含所有相关信息,请告诉我

1 个答案:

答案 0 :(得分:0)

Retrofit期待一个对象,但它正在接收一个字符串。

替换 echo 'url query ID is: '.$queryUserID.'. '; echo $fun -> getPosts($queryUserID);

使用

echo getPosts($queryUserID);