заполнить обзор повторов из ответа API - PullRequest
0 голосов
/ 08 апреля 2019

Я хочу подключить свой RecyclerView к моему ответу API ... так как слишком много устаревшего кода мне пришлось сделать два отдельно, но я до сих пор не могу понять, как их соединить, я пишу код, если кто-то захочет увидеть это или иметь проблему с RecyclerView .. что я действительно хочу, так это дать мне информацию или поток, или даже учебник, или как объединить оба с последним методом, так как большинство кодов в сети имеют проблемы, не рекомендуется, недостаточно подробно, чтобы показать вам точный способ учиться у него


код для подключения к базе данных с использованием httpUrlConnect


     public class MainActivity extends AppCompatActivity {


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

    new GetMethodDemo().execute("http://YourIPAddress/android/search.php");


}

public class GetMethodDemo extends AsyncTask<String, Void, String> {
    String server_response;

    @Override
    protected String doInBackground(String... strings) {

        URL url;
        HttpURLConnection urlConnection = null;

        try {
            url = new URL(strings[0]);
            urlConnection = (HttpURLConnection) url.openConnection();

            int responseCode = urlConnection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                server_response = readStream(urlConnection.getInputStream());
                Log.v("CatalogClient", server_response);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        Log.e("Response", "" + server_response);


    }
}

  // Converting InputStream to String

private String readStream(InputStream in) {
    BufferedReader reader = null;
    StringBuffer response = new StringBuffer();
    try {
        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return response.toString();
}

код для RecyclerView


  public class MainActivity extends AppCompatActivity {

private RecyclerView recyclerView;

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

    recyclerView = findViewById(R.id.recyclerView);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

    recyclerView.setLayoutManager(layoutManager);

    List<ModelClass> modelClassList = new ArrayList<>();
    modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"1","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna asdoibasidoasbd asodasidou asidua sdiuas dgpasidu agspiudasdiuasidgasiodgasiudgasoidugasdoiuasgdoiusagdasoiudgsaiudgasiodgasidgasiudgasiudgasoiudgasoidgasoiudasgdoiausdgaouisgduiasg uisag aisoug asiug aosiugdasiudgsauio gasuio gsaiodgasiud gasiug aosi","11/4/2019","20/4/2019","1000EGP"));
    modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"2","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
    modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"3","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
    modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"4","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
    modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"5","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
    modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"6","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
    modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"7","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
    modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"8","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
    modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"9","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
    modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"10","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
    modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"11","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));

    Adapter adapter = new Adapter(modelClassList);
    recyclerView.setAdapter(adapter);
    adapter.notifyDataSetChanged();
}
}

код для адаптера


   public class Adapter extends RecyclerView.Adapter<Adapter.Viewholder> {

private List<ModelClass> modelClassList;

public Adapter(List<ModelClass> modelClassList) {
    this.modelClassList = modelClassList;
}


@NonNull
@Override
public Viewholder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_layout,viewGroup,false);
    return new Viewholder(view);
}

@Override
public void onBindViewHolder(@NonNull Viewholder viewholder, int position) {
    int resource = modelClassList.get(position).getImageResource();
    String search_id = modelClassList.get(position).getSearch_id();
    String activity = modelClassList.get(position).getActivity();
    String origin = modelClassList.get(position).getOrigin();
    String destination = modelClassList.get(position).getDestination();
    String description = modelClassList.get(position).getDescription();
    String date_from = modelClassList.get(position).getDate_from();
    String date_to = modelClassList.get(position).getDate_to();
    String price = modelClassList.get(position).getPrice();


    viewholder.setData( resource, search_id,activity,origin,destination,description,date_from,date_to,price);


}

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

public class Viewholder extends RecyclerView.ViewHolder{

    private ImageView imageView;
    private TextView search;
    private TextView mactivity;
    private TextView morigin;
    private TextView mdestination;
    private TextView mdescription;
    private TextView mdate_from;
    private TextView mdate_to;
    private TextView mprice;

    public Viewholder(@NonNull View itemView) {
        super(itemView);

        imageView =itemView.findViewById(R.id.image_view);
        search= itemView.findViewById(R.id.search_id);
        mactivity= itemView.findViewById(R.id.activity);
        morigin= itemView.findViewById(R.id.origin);
        mdestination= itemView.findViewById(R.id.destination);
        mdescription= itemView.findViewById(R.id.description);
        mdate_from= itemView.findViewById(R.id.date_from);
        mdate_to= itemView.findViewById(R.id.date_to);
        mprice =itemView.findViewById(R.id.price);



    }
    private void setData(int resource, String search_id,String activity,String origin,String destination,String description,String date_from,String date_to,String price){


     imageView.setImageResource(resource);
     search.setText(search_id);
     mactivity.setText(activity);
     morigin.setText(origin);
     mdestination.setText(destination);
     mdescription.setText(description);
     mdate_from.setText(date_from);
     mdate_to.setText(date_to);
     mprice.setText(price);


    }
}
}

код залпа не работает


     public class redirectFragment extends Fragment {

private static final String URL_PRODUCTS = "http://ipAddress/android/search.php";

private RecyclerView recyclerView;
private List<ModelClass> modelClassList;


public redirectFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_redirect, container, false);

    recyclerView = v.findViewById(R.id.recyclerView);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this.getActivity());
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

    recyclerView.setLayoutManager(layoutManager);

    List<ModelClass> modelClassList = new ArrayList<>();

    loadModelClass();

    Adapter adapter = new Adapter(modelClassList);
    recyclerView.setAdapter(adapter);
    adapter.notifyDataSetChanged();

    return v ;
}

private void loadModelClass() {


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 object
                    JSONArray array = new JSONArray(response);

                    //traversing through all the object
                    for (int i = 0; i < array.length(); i++) {

                        //getting product object from json array
                        JSONObject product = array.getJSONObject(i);

                        //adding the product to product list
                        modelClassList.add(new ModelClass(
                                product.getInt("activity_img"),
                                product.getString("search_id"),
                                product.getString("activity"),
                                product.getString("description"),
                                product.getString("origin"),
                                product.getString("destination"),
                                product.getString("date_from"),
                                product.getString("date_to"),
                                product.getString("price")
                        ));
                    }

                    //creating adapter object and setting it to RecyclerView
                       Adapter adapter = new Adapter(modelClassList);
    recyclerView.setAdapter(adapter);
    adapter.notifyDataSetChanged();


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

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

код для модернизации и до сих пор не работает


private Adapter adapter;
private RecyclerView recyclerView;

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

    /*Create handle for the RetrofitInstance interface*/
    RetrofitInstance.GetEmployeeDataService service = RetrofitInstance.getRetrofitInstance().create(RetrofitInstance.GetEmployeeDataService.class);

    /*Call the method with parameter in the interface to get the employee data*/
    Call<SearchList> call = service.getSearchData(100);

    /*Log the URL called*/
    Log.wtf("URL Called", call.request().url() + "");

    call.enqueue(new Callback<SearchList>() {
        @Override
        public void onResponse(Call<SearchList> call, Response<SearchList> response) {
            generateEmployeeList(response.body().getSearchArrayList());
        }

        @Override
        public void onFailure(Call<SearchList> call, Throwable t) {
            Toast.makeText(MainActivity.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
        }
    });
}

/*Method to generate List of employees using RecyclerView with custom adapter*/
private void generateEmployeeList(ArrayList<search> modelClassList) {
    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

    adapter = new Adapter(modelClassList);

    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);

    recyclerView.setLayoutManager(layoutManager);

    recyclerView.setAdapter(adapter);

    adapter.notifyDataSetChanged();
}

}

Я попробовал оба кода, и они отлично работают для RecyclerView и для HTTPURLCONNECTION .. Я надеюсь, что кто-то поможет мне с объединением двух из них

Я попробовал залп, но в результате получил нулевое возвращение, поэтому кто-то предложил мне работать с HTTPURLCONNECTION, и с тех пор я не знаю, как объединить их вместе. Я добавлю залп, с которым я работал

1 Ответ

1 голос
/ 09 апреля 2019

Попробуйте это @ diaa,

public class redirectFragment extends Fragment {

private static final String URL_PRODUCTS = 
"http://IPADDRESS/android/search.php";

private RecyclerView recyclerView;
List<ModelClass> modelClassList;

private RecyclerView.Adapter adapter; //new line

public redirectFragment() {
// Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                 Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_redirect, container, false);

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

   //initializing the productlist
   List<ModelClass> modelClassList = new ArrayList<>();

  adapter = new Adapter(modelClassList); //new line
  recyclerView.setAdapter(adapter);  //new line

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


  return v;
  }

    private void loadModelClass() {


  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 object
                JSONArray array = new JSONArray(response);

                //traversing through all the object
                for (int i = 0; i < array.length(); i++) {

                    //getting product object from json array
                    JSONObject product = array.getJSONObject(i);


                    int search_id = product.getInt("search_id");
                    String activity = product.getString("activity");
                    String descp = product.getString("description");
                    String image = product.getString("activity_img");
                    String origin = product.getString("origin");
                    String destination =
                            product.getString("destination");
                    String date_from = product.getString("date_from");
                    String date_to = product.getString("date_to");
                    String price = product.getString("price");

                    ModelClass list = new ModelClass(search_id, 
                   activity, 
                        descp,image,
                            origin, destination, date_from, date_to, 
                      price);
                    modelClassList.add(list);

                }

                adapter = new Adapter(list); //new line
                recyclerView.setAdapter(adapter);  //new line

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    },
    new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });

// добавление нашего stringrequest в очередь Volley.newRequestQueue (this.getActivity ()). Add (stringRequest);}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...