Android 从API响应填充recyclerview
我想将我的RecyclerView连接到我的API响应。。由于有太多被贬低的代码,我不得不将这两个代码分开制作,但我仍然不知道如何将它们组合在一起。如果有人想看,或者对RecyclerView有问题,我会将代码放在一起。。我真正想要的是给我信息或一个线程,甚至是一个教程,或者如何将这两者与最新的方法结合起来,因为大多数在线代码都有问题,没有足够详细地向您展示从中学习的确切方法Android 从API响应填充recyclerview,android,android-recyclerview,android-volley,httpconnection,Android,Android Recyclerview,Android Volley,Httpconnection,我想将我的RecyclerView连接到我的API响应。。由于有太多被贬低的代码,我不得不将这两个代码分开制作,但我仍然不知道如何将它们组合在一起。如果有人想看,或者对RecyclerView有问题,我会将代码放在一起。。我真正想要的是给我信息或一个线程,甚至是一个教程,或者如何将这两者与最新的方法结合起来,因为大多数在线代码都有问题,没有足够详细地向您展示从中学习的确切方法 使用httpUrlConnect连接到数据库的代码 public类MainActivity扩展了AppCompatA
使用httpUrlConnect连接到数据库的代码
public类MainActivity扩展了AppCompatActivity{
@凌驾
创建时受保护的void(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_main);
新建GetMethodDemo()。执行(“http://YourIPAddress/android/search.php");
}
公共类GetMethodDemo扩展了AsyncTask{
字符串服务器响应;
@凌驾
受保护的字符串背景(字符串…字符串){
网址;
HttpURLConnection-urlConnection=null;
试一试{
url=新url(字符串[0]);
urlConnection=(HttpURLConnection)url.openConnection();
int responseCode=urlConnection.getResponseCode();
if(responseCode==HttpURLConnection.HTTP\u确定){
server_response=readStream(urlConnection.getInputStream());
Log.v(“CatalogClient”,服务器响应);
}
}捕获(格式错误){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
返回null;
}
@凌驾
受保护的void onPostExecute(字符串s){
super.onPostExecute(s);
Log.e(“响应”,“服务器+响应”);
}
}
//将InputStream转换为字符串
私有字符串读取流(输入流输入){
BufferedReader reader=null;
StringBuffer响应=新的StringBuffer();
试一试{
reader=新的BufferedReader(新的InputStreamReader(in));
字符串行=”;
而((line=reader.readLine())!=null){
响应。追加(行);
}
}捕获(IOE异常){
e、 printStackTrace();
}最后{
if(读卡器!=null){
试一试{
reader.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
返回response.toString();
}
RecyclerView代码
public类MainActivity扩展了AppCompatActivity{
私人回收站;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView=findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager=新的LinearLayoutManager(此);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
List modelClassList=新建ArrayList();
添加(新的模型类(R.drawable.ic_launcher_background,“1”,“day use”,“cairo”,“ain shokhna”,“从开罗到ain sokhna Asdoibasidoasb和asodasidou sdiuas dgpasidu AgspiudasdiuasidGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGasIdGa;
modelClassList.add(新的ModelClass(R.drawable.ic_launcher_背景,“2”,“日间使用”,“开罗”,“艾因肖赫纳”,“从开罗到艾因索赫纳的日间使用”,“2019年4月11日”,“2019年4月20日”,“1000EGP”);
modelClassList.add(新的ModelClass(R.drawable.ic_launcher_背景,“3”,“日间使用”,“开罗”,“艾因肖赫纳”,“从开罗到艾因索赫纳的日间使用”,“2019年4月11日”,“2019年4月20日”,“1000EGP”);
modelClassList.add(新的ModelClass(R.drawable.ic_launcher_背景,“4”,“日间使用”,“开罗”,“艾因肖赫纳”,“从开罗到艾因索赫纳的日间使用”,“2019年4月11日”,“2019年4月20日”,“1000EGP”);
modelClassList.add(新的ModelClass(R.drawable.ic_launcher_背景,“5”,“日间使用”,“开罗”,“艾因肖赫纳”,“从开罗到艾因索赫纳的日间使用”,“2019年4月11日”,“2019年4月20日”,“1000EGP”);
modelClassList.add(新的ModelClass(R.drawable.ic_launcher_背景,“6”,“日间使用”,“开罗”,“艾因肖赫纳”,“从开罗到艾因索赫纳的日间使用”,“2019年4月11日”,“2019年4月20日”,“1000EGP”);
modelClassList.add(新的ModelClass(R.drawable.ic_launcher_背景,“7”,“日间使用”,“开罗”,“艾因肖赫纳”,“从开罗到艾因索赫纳的日间使用”,“2019年4月11日”,“2019年4月20日”,“1000EGP”);
modelClassList.add(新的ModelClass(R.drawable.ic_launcher_背景,“8”,“日间使用”,“开罗”,“艾因肖赫纳”,“从开罗到艾因索赫纳的日间使用”,“2019年4月11日”,“2019年4月20日”,“1000EGP”);
modelClassList.add(新的ModelClass(R.drawable.ic_launcher_背景,“9”,“日间使用”,“开罗”,“艾因肖赫纳”,“从开罗到艾因索赫纳的日间使用”,“2019年4月11日”,“2019年4月20日”,“1000EGP”);
modelClassList.add(新的ModelClass(R.drawable.ic_launcher_背景,“10”,“日间使用”,“开罗”,“艾因肖赫纳”,“从开罗到艾因索赫纳的日间使用”,“2019年4月11日”,“2019年4月20日”,“1000EGP”);
modelClassList.add(新的ModelClass(R.drawable.ic_launcher_背景,“11”、“日间使用”、“开罗”、“艾因肖赫纳”、“从开罗到艾因索赫纳的日间使用”、“2019年4月11日”、“2019年4月20日”、“1000EGP”);
适配器=新适配器(modelClassList);
recyclerView.setAdapter(适配器);
adapter.notifyDataSetChanged();
}
}
适配器的代码
公共类适配器扩展了RecyclerView.Adapter{
私有列表模型类列表;
公共适配器(列表modelClassList){
this.modelClassList=modelClassList;
}
@非空
@凌驾
public Viewholder onCreateViewHolder(@NonNull ViewGroup ViewGroup,int i){
View-View=LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item\u布局,viewGroup,false);
返回新的Viewholder(视图);
}
@凌驾
BindViewHolder(@N)上的公共无效
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();
}
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();
}
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) {
}
});