循环JsonArray成功,但未显示任何内容

时间:2018-07-24 01:27:29

标签: java android json android-recyclerview recycler-adapter

我是Android Studio的新手。我想制作一个仅针对当前用户名显示的RecyclerView。示例:我以我的用户名“ rzyd”登录,我想显示数据库中的笔记。我得到了白色的显示屏,但是说成功了。我的logcat显示如下:“ E / RecyclerView:未连接适配器;正在跳过布局”。有人可以帮我吗?

这是我的代码:

Catatan.java

public class Catatan extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listItems;
Dialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_catatan);
    recyclerView = findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    listItems = new ArrayList<>();
    dialog = new Dialog(this);
    loadRecyclerViewData();
}
public void loadRecyclerViewData(){
    final String url = "http://xxxxxxxxx.xxxxxxxxxx.com/tampilcatatan.php";
    dialog.setContentView(R.layout.cobaloding);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    dialog.show();
    dialog.setCanceledOnTouchOutside(false);
    dialog.setCancelable(false);
    Intent intent = getIntent();
    final String usernamenya = intent.getStringExtra("usernamev2");
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                        try {
                            dialog.setCanceledOnTouchOutside(true);
                            dialog.setCancelable(true);
                            dialog.hide();
                            JSONObject jsonObject = new JSONObject(s);
                            String status = jsonObject.getString("status");
                            if(status.equals("sukses")){
                                Intent intent = getIntent();
                                String usernamenya = intent.getStringExtra("usernamev2");
                                Toast.makeText(getApplicationContext(), "Sukses, your username: " + usernamenya, Toast.LENGTH_LONG).show();
                                JSONArray array = jsonObject.getJSONArray("semua");
                                for (int i = 0; i < array.length(); i++) {
                                    JSONObject o = array.getJSONObject(i);
                                    ListItem item = new ListItem(
                                            o.getString("judul"),
                                            o.getString("catatan")
                                    );
                                    listItems.add(item);
                                }
                            } else {
                                dialog.setCanceledOnTouchOutside(true);
                                dialog.setCancelable(true);
                                dialog.hide();
                                Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
                            }
                            LinearLayoutManager manager = new LinearLayoutManager(getApplicationContext());
                            recyclerView.setLayoutManager(manager);
                            recyclerView.setHasFixedSize(true);
                            adapter = new CatatanAdapter(listItems, getApplicationContext());
                            recyclerView.setAdapter(adapter);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    dialog.setCanceledOnTouchOutside(true);
                    dialog.setCancelable(true);
                    dialog.setContentView(R.layout.popup_koneksigagal);
                    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    dialog.show();
                    error.printStackTrace();
                }
            }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            Intent intent = getIntent();
            String usernamenya = intent.getStringExtra("usernamev2");
            params.put("username", usernamenya.trim());
            return params;
        }
    };
    Volley.newRequestQueue(this).add(stringRequest);
}

}

我的适配器:

public class CatatanAdapter extends 
RecyclerView.Adapter<CatatanAdapter.ViewHolder> {
private List<ListItem> listItems;
private Context context;

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.list_item, parent, false);
    return new ViewHolder(v);
}

public CatatanAdapter(List<ListItem> listItems, Context context) {
    this.listItems = listItems;
    this.context = context;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    ListItem listItem = listItems.get(position);
    holder.textViewJudulnya.setText(listItem.getJudulnya());
    holder.textViewCatatannya.setText(listItem.getCatatannya());

}

@Override
public int getItemCount() {
    return listItems.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    public TextView textViewJudulnya;
    public TextView textViewCatatannya;

    public ViewHolder(View itemView) {
        super(itemView);
        textViewJudulnya = itemView.findViewById(R.id.judulnya);
        textViewCatatannya = itemView.findViewById(R.id.catatannya);

    }
}
}

我的php脚本:

<?php
error_reporting(0);
$conn = mysqli_connect("localhost", "id6487272_kuch", "xxxxxxxxx", "id6487272_bowo_db");
$username = $_POST['username'];
$mysqli = "SELECT * FROM catatan WHERE username='$username'";
$result = mysqli_query($conn, $mysqli) or die('error: ' .mysql_error());
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
}
if (mysqli_num_rows($result) >= 1) {
echo json_encode(Array('status' => 'sukses'));
echo '{"semua":'.json_encode($rows).'}';
} else {
 echo json_encode(Array('status' => 'gagal'));  
}
?>

通过手机拍摄图片:

Screenshoot from my phone show success

2 个答案:

答案 0 :(得分:0)

您可以将所有这些移动到onCreate中。不应将其复制到Volley响应中

LinearLayoutManager manager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(manager);
recyclerView.setHasFixedSize(true);
adapter = new CatatanAdapter(listItems, this);
recyclerView.setAdapter(adapter);

然后,您需要验证您实际上是否在获取任何JSON值。仅仅因为您得到了吐司并不意味着您就遍历了

例如,您很可能在logcat中获得ParseExceptiom,因为您回显了两个单独的JSON对象而不是一个。

您需要这个

if (mysqli_num_rows($result) >= 1) {
    echo json_encode(Array('status' => 'sukses', 'semua' => $rows));
}

我建议尝试使用RecyclerView之前先打印出logcat中的各个JSON元素

答案 1 :(得分:0)

尝试一下

recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(LinearLayoutManager(Catatan .this, 
LinearLayoutManager.VERTICAL, false));