我可以获取我的Json数据但是我无法加载RecyclerView。我使用Logcat来检查数据是否被提取。我可以看到Json数据。 我的代码如下。
Category.java
public class Category extends AppCompatActivity {
public List<String> Category;
public RecyclerView rcv;
public ImageView img;
public List<CategoryList> items;
public List<String> Images;
public CategoryAdapter cartAdapter;
JSONObject jsonObject = new JSONObject();
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_category);
Category = new ArrayList<>();
items = new ArrayList<>();
Images=new ArrayList<>();
rcv=(RecyclerView)findViewById(R.id.recycler_view);
img=(ImageView)findViewById(R.id.Img);
CategoryAdapter cartAdapter;
cartAdapter = new CategoryAdapter(Category.this, items);
rcv.setLayoutManager(new LinearLayoutManager(Category.this));
rcv.setAdapter(cartAdapter);
new getCart().execute();
}
private class getCart extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(Category.this);
HttpURLConnection conn;
URL url = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
@Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL("http://www.dazecorp.com/demos/Vellore_Kitchen/API/CategoryApi.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder().appendQueryParameter("request", "Category");
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
@Override
protected void onPostExecute(String result) {
pdLoading.dismiss();
Log.d("result", result);
String error = jsonObject.optString("error");
if (error.equalsIgnoreCase("false")) {
JSONArray carts = jsonObject.optJSONArray("Details");
for (int i = 0; i < carts.length(); i++)
{
JSONObject object = carts.optJSONObject(i);
Log.d("object", object.toString());
Category.set(i, object.optString("Category"));
Images.set(i, object.optString("CategoryImage"));
}
for (int i = 0; i < Category.size(); i++) {
CategoryList item = new CategoryList(Category.get(i),Images.get(i));
items.add(item);
Log.d("items",items.toString());
}
cartAdapter.notifyDataSetChanged();
}
}
}
}
CategoryAdapter.java
public class CategoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private LayoutInflater inflater;
List<CategoryList> items;
CategoryList current;
int currentPos=0;
class MyHolder extends RecyclerView.ViewHolder{
TextView CategoryName;
ImageView CategoryImage;
// create constructor to get widget reference
public MyHolder(View itemView) {
super(itemView);
CategoryName= (TextView) itemView.findViewById(R.id.txtview);
CategoryImage= (ImageView) itemView.findViewById(R.id.Img);
}
}
public CategoryAdapter(Context context, List<CategoryList> items){
this.context=context;
inflater= LayoutInflater.from(context);
this.items=items;
}
// Inflate the layout when viewholder created
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.category_list, parent,false);
MyHolder holder=new MyHolder(view);
return holder;
}
// Bind data
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// Get current position of item in recyclerview to bind data and assign values from list
MyHolder myHolder= (MyHolder) holder;
CategoryList current=items.get(position);
myHolder.CategoryName.setText(current.getCategory());
// load image into imageview using glide
Glide.with(context).load("http://www.dazecorp.com/demos/Vellore_Kitchen/API/CategoryApi.php" + current.getCategoryImage())
.into(myHolder.CategoryImage);
}
// return total item from List
@Override
public int getItemCount() {
return (null!= items ? items.size():0);
}
}
CategoryList.java
public class CategoryList {
public String Category;
public String CategoryImage;
public CategoryList(String Category,String CategoryImage)
{
this.Category=Category;
this.CategoryImage=CategoryImage;
}
public String getCategory()
{
return Category;
}
public void setCategory(String Category)
{
this.Category=Category;
}
public String getCategoryImage()
{
return CategoryImage;
}
public void setCategoryImage(String CategoryImage)
{
this.CategoryImage=CategoryImage;
}
}
content_category.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/activity_category"
tools:context="com.example.yuvaraj.vellorekitchen.Category">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical" />
</RelativeLayout>
&#13;
category_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/txtview"
android:layout_height="100dp"
android:layout_width="100dp
"
android:layout_gravity="center_horizontal" />
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="@+id/Img"
android:layout_gravity="center_horizontal" />
</LinearLayout>
&#13;
答案 0 :(得分:0)
在onPostExecute()中,结果是String,需要在进行任何处理之前转换为JSONObject。
try {
jsonObject = new JSONObject(result);
} catch (JSONException e) {
e.printStackTrace();
}
String error = jsonObject.optString("error");
没有json对象&#34;错误&#34;,所以不要检查onPostExecute()中的错误 要么对支票发表评论。
//if (error.equalsIgnoreCase("false")) {
没有jasonArray&#34;详情&#34;作为回应,它是&#34;细节&#34; (小写字母d)。所以把它改成细节
JSONArray carts = jsonObject.optJSONArray("details");
然后错误msg-&gt; java.lang.IndexOutOfBoundsException:索引0无效,大小为0
Category.set(i, object.optString("Category"));
Images.set(i, object.optString("CategoryImage"));
因为之前没有添加任何元素。所以改变它来添加。
Category.add(i, object.optString("Category"));
Images.add(i, object.optString("CategoryImage"));
//Category.set(i, object.optString("Category"));
//Images.set(i, object.optString("CategoryImage"));
然后java.lang.NullPointerException:尝试在cartAdapter.notifyDataSetChanged();的空对象引用上调用虚方法notifyDataSetChanged()。这是因为全局CategoryAdapter cartAdapter;未初始化,因为onCreate()中有另一个本地decaration,它具有本地范围。所以在onCreate()
中注释本地声明//CategoryAdapter cartAdapter;