首页 > 解决方案 > 如何将具有 json 的活动转换为片段

问题描述

我正在尝试将具有 json 数组的活动转换为片段。

我怎么能意识到它?

请帮助我是android的初学者,我尝试了很多次。

错误发生在“this”
活动上,如下所示:

public class MainActivity extends AppCompatActivity implements ProductAdapter.OnItemClickListener {

    public static final String EXTRA_URL = "imageUrl";
    public static final String EXTRA_TITLE = "jobTitle";
    public static final String EXTRA_DESC = "jobDesc";
    public static final String EXTRA_CREATED = "jobCreated";

    //this is the JSON Data URL
    //make sure you are using the correct ip else it will not work
    private static final String URL_PRODUCTS = "http://techpoint123.000webhostapp.com/api.php";

    //a list to store all the products
    List<Product> productList;

    //the recyclerview
    RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //getting the recyclerview from xml
        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        //initializing the productlist
        productList = new ArrayList<>();

        //this method will fetch and parse json
        //to display it in recyclerview
        loadProducts();
    }

    private void loadProducts() {
        /*
         * Creating a String Request
         * The request type is GET defined by first parameter
         * The URL is defined in the second parameter
         * Then we have a Response Listener and a Error Listener
         * In response listener we will get the JSON response as a String
         * */
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            //converting the string to json array objec
                            JSONArray array = new JSONArray(response);
                            //traversing through all the object
                            for (int i = 0; i < array.length(); i++) {
                                //getting product object from json arra
                                JSONObject product = array.getJSONObject(i);
                                //adding the product to product list
                                productList.add(new Product(
                                        product.getString("Id"),
                                        product.getString("Title"),
                                        product.getString("Desc"),
                                        product.getString("Image Url"),
                                        product.getString("Created")

                                ));
                            }
                            //creating adapter object and setting it to recyclerview
                            ProductAdapter adapter = new ProductAdapter(MainActivity.this, productList);
                            recyclerView.setAdapter(adapter);
                        adapter.setOnItemClickListener(MainActivity.this);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        //adding our stringrequest to queue
        Volley.newRequestQueue(this).add(stringRequest);
    }

    @Override
    public void onItemClick(int position) {
        Intent detailIntent = new Intent(this, DetailActivity.class);
        Product clickedItem = productList.get(position);

        detailIntent.putExtra(EXTRA_URL, clickedItem.getImageUrl());
        detailIntent.putExtra(EXTRA_TITLE, clickedItem.getTitle());
        detailIntent.putExtra(EXTRA_DESC, clickedItem.getDesc());
        detailIntent.putExtra(EXTRA_CREATED, clickedItem.getCreated());

        startActivity(detailIntent);
    }

}

标签: androidandroid-layoutandroid-fragmentsandroid-activity

解决方案


MainActivity.java

package com.robotics.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String URL_PRODUCTS = "http://techpoint123.000webhostapp.com/api.php";
    List<Product> productList = new ArrayList<>();
    private RecyclerView mRecyclerView;
    private RecyclerView.LayoutManager layoutManager;
    ProductAdapter mAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);

        mRecyclerView = (RecyclerView) findViewById(R.id.my_product_view);
        layoutManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(layoutManager);
        mAdapter = new ProductAdapter();
        mRecyclerView.setAdapter(mAdapter);

        RequestQueue queue = Volley.newRequestQueue(this);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray array = new JSONArray(response);
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject product = array.getJSONObject(i);
                                productList.add(new Product(
                                        product.getString("Id"),
                                        product.getString("Title"),
                                        product.getString("Desc"),
                                        product.getString("Image Url"),
                                        product.getString("Created")

                                ));
                            }
                            mAdapter.addItems(productList);
                            Log.d("YOG",""+response);
                        }catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("YOG",""+error.toString());
            }
        });
        queue.add(stringRequest);
        queue.start();
    }


}

产品.java

package com.robotics.myapplication;

public class Product {
    public String Id, Title, Desc, ImageUrl, Created;
    public Product(String Id,String Title,String Desc,String ImageUrl,String Created){
        this.Id = Id;
        this.Title = Title;
        this.Desc = Desc;
        this.ImageUrl=ImageUrl;
        this.Created =Created;
    }
}

ProductAdapter.java

package com.robotics.myapplication;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;


public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
    private List<Product> OutList = new ArrayList<Product>();
    public ProductAdapter() {}
    public class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView mtxtId,mtxtTitle,mtxtDesc,mtxtImageUrl,mtxtCreated;
        private ProductViewHolder(View view) {
            super(view);
            mtxtId = view.findViewById(R.id.txtid);;
            mtxtTitle = view.findViewById(R.id.txttitle);
            mtxtDesc = view.findViewById(R.id.txtdesc);
            mtxtImageUrl= view.findViewById(R.id.txturl);
            mtxtCreated = view.findViewById(R.id.txtcreat);

        }
        @Override
        public void onClick(View view) {}
        final protected Context getContext() {
            return itemView.getContext();
        }
    }
    @Override
    public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.product, parent, false);
        return new ProductViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(ProductViewHolder holder, int position){
        holder.mtxtId.setText(OutList.get(position).Id);
        holder.mtxtTitle.setText(OutList.get(position).Title);
        holder.mtxtDesc.setText(OutList.get(position).Desc);
        holder.mtxtImageUrl.setText(OutList.get(position).ImageUrl);
        holder.mtxtCreated.setText(OutList.get(position).Created);
    }
    @Override
    public int getItemCount() {
        return OutList.size();
    }
    public void addItems(List<Product> _OutList) {
        OutList.addAll(_OutList);
        notifyDataSetChanged();
    }
}

产品.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="false"
    android:focusable="false"
    android:foreground="?android:attr/selectableItemBackground"
    card_view:cardUseCompatPadding="true">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="10dp">

        <TextView
            android:id="@+id/txtid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Order"/>
        <TextView
            android:id="@+id/txttitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="amount"/>

        <TextView
            android:id="@+id/txtdesc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="timeout"/>
        <TextView
            android:id="@+id/txturl"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="timeout"/>
        <TextView
            android:id="@+id/txtcreat"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="timeout"/>

    </LinearLayout>
</android.support.v7.widget.CardView>

包含_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_main"
    tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/my_product_view"
        />

</LinearLayout>

推荐阅读