Populate recycle adapter from controller class - java

I'm trying to populate a recycle adapter from a controller class, to split the logic in the app. But I can't seem to get it working.. Do to the request is running on another thread, the view is not updated before it is shown. What am I doing wrong ?
FragmentClass:
package lassebjoerklund.homecontrol.views.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import lassebjoerklund.homecontrol.R;
import lassebjoerklund.homecontrol.adapters.FridgeFragmentOverViewAdapter;
import lassebjoerklund.homecontrol.controllers.FridgeController;
import lassebjoerklund.homecontrol.decorations.DividerItemDecoration;
import lassebjoerklund.homecontrol.model.Product;
import lassebjoerklund.homecontrol.utils.FragmentUtil;
/**
* Created by zigge on 29-Mar-16.
*/
public class FridgeFragmentOverView extends Fragment {
private final FridgeController fridgeController = new FridgeController();
private RecyclerView recyclerView;
private LinkedList<String> types;
private FridgeFragmentOverViewAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_overview_layout, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.productOverviewRecycleView);
recyclerView.setHasFixedSize(true);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST);
recyclerView.addItemDecoration(itemDecoration);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
adapter = new FridgeFragmentOverViewAdapter(fridgeController.getProductsTypes());
recyclerView.setAdapter(adapter);
return v;
}
#Override
public void onResume() {
super.onResume();
fridgeController.refresh(getContext(), adapter);
}
}
Controller Class:
package lassebjoerklund.homecontrol.controllers;
import android.content.Context;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
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;
import lassebjoerklund.homecontrol.adapters.FridgeFragmentOverViewAdapter;
import lassebjoerklund.homecontrol.interfaces.OnSucsess;
import lassebjoerklund.homecontrol.model.Product;
/**
* Created by zigge on 29-Mar-16.
*/
public class FridgeController implements OnSucsess {
private RequestQueue rQueue;
private ArrayList<Product> products;
private List<String> productsTypes;
public ArrayList<Product> getProducts() {
return products;
}
public List<String> getProductsTypes() {
return productsTypes;
}
public void refresh(Context context, final FridgeFragmentOverViewAdapter adapter) {
String fetchProducts = "http://87.52.28.25:900/index.php";
rQueue = Volley.newRequestQueue(context);
final JsonArrayRequest getProductsRequest = new JsonArrayRequest(fetchProducts, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
products = new ArrayList<>();
productsTypes = new ArrayList<>();
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = (JSONObject) response.get(i);
String barcode = jsonObject.getString("code");
String name = jsonObject.getString("name");
String ex_date = jsonObject.getString("ex_date");
String add_date = jsonObject.getString("add_date");
String type = jsonObject.getString("type");
Product product = new Product(barcode, name, ex_date, add_date, type);
products.add(product);
}
} catch (JSONException e) {
e.printStackTrace();
}
if (products.size() != 0) {
for (int i = 0; i < products.size(); i++) {
if (!productsTypes.contains(products.get(i).getType())) {
productsTypes.add(products.get(i).getType());
}
}
}
getProductsOnsucsess(adapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
rQueue.add(getProductsRequest);
}
#Override
public void getProductsOnsucsess(FridgeFragmentOverViewAdapter adapter) {
adapter.refreshAdapter(productsTypes);
}
}
Adapter:
package lassebjoerklund.homecontrol.adapters;
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;
import lassebjoerklund.homecontrol.R;
import lassebjoerklund.homecontrol.model.Product;
/**
* Created by zigge on 29-Mar-16.
*/
public class FridgeFragmentOverViewAdapter extends RecyclerView.Adapter {
private List<String> types;
public FridgeFragmentOverViewAdapter(List<String> types) {
this.types = types;
}
#Override
public int getItemCount() {
return 0;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_overview_card_layout, null);
return new ProductsGroupedHolder(v);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
}
public class ProductsGroupedHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView tvTypeOfProduct, tvCount, tvExpired;
public ProductsGroupedHolder(View itemView) {
super(itemView);
tvTypeOfProduct = (TextView) itemView.findViewById(R.id.tvTypeOfProduct);
tvCount = (TextView) itemView.findViewById(R.id.tvCount);
tvExpired = (TextView) itemView.findViewById(R.id.tvExpired);
}
#Override
public void onClick(View v) {
}
}
public void refreshAdapter(List<String> types) {
if(this.types != null) {
this.types.clear();
this.types = types;
notifyDataSetChanged();
}else {
this.types = types;
notifyDataSetChanged();
}
}
}

Try calling:
adapter.notifyDataSetChanged();
after updating it.
Edit 1:
Return actual size of adapter items in getItemCount() as #prathamkesarkar said.

Simple looks like you have set the getItemType() method return 0.
That method determines how much item your RecyclerView have.
#Override
public int getItemCount() {
return type.size();
}

Related

Failed to parse Json data from the Api

I am trying to get the data (List of Images and Names) from an Api using Volley into a recycler View but due to some reason I am only getting the list of names but unable to fetch the images corresponding to that name, and getting File Not Found Exception
This is the Main Activity
package com.example.bks;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
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.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
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.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private static final String TAG ="tag";
RecyclerView recyclerView;
ProgressBar progressBar;
private List<CropModel> mList;
private cropAdapter cropAdapter;
private RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView=findViewById(R.id.recycleView);
progressBar=findViewById(R.id.progressBar);
cropAdapter= new cropAdapter(this, mList );
recyclerView.setLayoutManager(new LinearLayoutManager(this));
requestQueue=volleySingleton.getmInstance(this).getRequestQueue();
mList= new ArrayList<>();
fetchData();
}
private void fetchData() {
progressBar.setVisibility(View.VISIBLE);
String url= "http://bharatkrushiseva.in/api_user/getCropType";
JsonObjectRequest jsonObjectRequest= new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressBar.setVisibility(View.GONE);
try {
JSONArray jsonArray= response.getJSONArray("crop");
for(int i=0; i<jsonArray.length();i++){
JSONObject jsonObject= jsonArray.getJSONObject(i);
String name= jsonObject.getString("crop_name");
String image= jsonObject.getString("crop_image");
CropModel post = new CropModel(name,image);
mList.add(post);
}
cropAdapter adapter = new cropAdapter(MainActivity.this,mList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
#Override
public Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> params= new HashMap<>();
params.put("language","en");
return params;
}
};
requestQueue.add(jsonObjectRequest);
}
}
This is the Adapter Class
package com.example.bks;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
public class cropAdapter extends RecyclerView.Adapter<cropAdapter.Viewholder> {
private Context context;
private List<CropModel> cropModels;
public cropAdapter(Context context, List<CropModel> cropModels) {
this.context = context;
this.cropModels = cropModels;
}
#NonNull
#Override
public Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(context).inflate(R.layout.crop_view,parent,false);
return new cropAdapter.Viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull Viewholder holder, int position) {
CropModel cropModel= cropModels.get(position);
holder.cropName.setText(cropModel.getCrop_name());
Glide.with(context).load(cropModel.getCrop_image()).into(holder.cropImage);
}
#Override
public int getItemCount() {
return cropModels.size() ;
}
public class Viewholder extends RecyclerView.ViewHolder {
TextView cropName;
ImageView cropImage;
public Viewholder(#NonNull View itemView) {
super(itemView);
cropImage=itemView.findViewById(R.id.Cropimage);
cropName=itemView.findViewById(R.id.cropName);
}
}
}
This is my Model Class
package com.example.bks;
public class CropModel {
private String crop_name;
private String crop_image;
public CropModel(String crop_name, String crop_image) {
this.crop_name = crop_name;
this.crop_image = crop_image;
}
public String getCrop_name() {
return crop_name;
}
public void setCrop_name(String crop_name) {
this.crop_name = crop_name;
}
public String getCrop_image() {
return crop_image;
}
public void setCrop_image(String crop_image) {
this.crop_image = crop_image;
}
}
This is the Volley Singleton Class
package com.example.bks;
import android.content.Context;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class volleySingleton {
private RequestQueue requestQueue;
private static volleySingleton mInstance;
private volleySingleton(Context context) {
requestQueue= Volley.newRequestQueue(context.getApplicationContext());
}
public static synchronized volleySingleton getmInstance(Context context){
if(mInstance==null){
mInstance=new volleySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue(){
return requestQueue;
}
}

Getting wrong position on RecyclerView

I am trying to get the position of the item in a recycler view in order to pass it down to other activities, but after actually managing to get the item id, I found out that I'm getting a -1, therefore not getting a correct id there. What could be causing this?
The activity:
package com.gmproxy.pastilarma;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.SearchView;
import android.widget.Toast;
import androidx.recyclerview.*;
import com.gmproxy.Adapters.PathologyListAdapter;
import com.gmproxy.Adapters.PathologyViewHolder;
import com.gmproxy.DAO.PathologyDAO;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.Util.PathologyViewModel;
public class PathologiesSearchScreen extends AppCompatActivity {
private PathologyViewModel viewModel;
SearchView searchView;
RecyclerView recyclerView;
private PathologyDAO pathDao;
private Pathology pathology;
private PathologyViewHolder holder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pathology_search_list);
searchView = findViewById(R.id.SearchView);
recyclerView = findViewById(R.id.recyclerview);
final PathologyListAdapter adapter = new PathologyListAdapter(new PathologyListAdapter.UserDiff());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
viewModel = new ViewModelProvider(this).get(PathologyViewModel.class);
viewModel.pathologies.observe(this, adapter::submitList);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
viewModel.setFilter(searchView.getQuery().toString());
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
long start;
start = System.currentTimeMillis();
if ((newText.length() > 3) && (System.currentTimeMillis() - start > 500)) {
viewModel.setFilter(searchView.getQuery().toString());
}
return false;
}
});
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(#NonNull #org.jetbrains.annotations.NotNull RecyclerView rv, #NonNull #org.jetbrains.annotations.NotNull MotionEvent e) {
pathology = getSelectedPathology(findViewById(R.id.recyclerview));
Log.println(Log.INFO, "PathologyTest", pathology.toString());
final CharSequence[] options = {"Si", "No"};
AlertDialog.Builder builder = new AlertDialog.Builder(PathologiesSearchScreen.this);
builder.setTitle("¿Añadir la patología " + pathology.getPathologyName() + "?");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Si")) {
Toast.makeText(PathologiesSearchScreen.this, "Has añadido la patología " + pathology.getPathologyName() + ".", Toast.LENGTH_SHORT).show();
Intent mainAct = new Intent(PathologiesSearchScreen.this, UserAddScreen.class);
mainAct.putExtra("path", pathology);
} else if (options[item].equals("No")) {
dialog.dismiss();
}
}
});
builder.show();
return true;
}
#Override
public void onTouchEvent(#NonNull #org.jetbrains.annotations.NotNull RecyclerView rv, #NonNull #org.jetbrains.annotations.NotNull MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
public Pathology getSelectedPathology(View v){
holder = new PathologyViewHolder(v);
long idlongo = recyclerView.getAdapter().getItemId(holder.getAdapterPosition());
Log.println(Log.INFO, "PathologyTest", String.valueOf(idlongo));
int id = (int) idlongo;
Pathology path = pathDao.findObjectbyId(id);
return path;
}
}
The view holder:
package com.gmproxy.Adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import com.gmproxy.DAO.PathologyDAO;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.pastilarma.PathologiesSearchScreen;
import com.gmproxy.pastilarma.R;
import java.nio.file.Path;
public class PathologyViewHolder extends RecyclerView.ViewHolder {
public final TextView objItemView;
public PathologyViewHolder(View itemView) {
super(itemView);
objItemView = itemView.findViewById(R.id.textView);
}
public void bind(String text) {
objItemView.setText(text);
}
static PathologyViewHolder create(ViewGroup parent) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.pathologies_item, parent, false);
return new PathologyViewHolder(view);
}
}
The list adapter:
package com.gmproxy.Adapters;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.pastilarma.PathologiesSearchScreen;
import com.gmproxy.pastilarma.UserAddScreen;
public class PathologyListAdapter extends ListAdapter<Pathology, PathologyViewHolder> {
public PathologyListAdapter(#NonNull DiffUtil.ItemCallback<Pathology> diffCallback) {
super(diffCallback);
}
#Override
public PathologyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return PathologyViewHolder.create(parent);
}
#Override
public void onBindViewHolder(PathologyViewHolder holder, int position) {
Pathology current = getItem(position);
holder.bind(current.getPathologyName());
}
public static class UserDiff extends DiffUtil.ItemCallback<Pathology> {
#Override
public boolean areItemsTheSame(#NonNull Pathology oldItem, #NonNull Pathology newItem) {
return oldItem == newItem;
}
#Override
public boolean areContentsTheSame(#NonNull Pathology oldItem, #NonNull Pathology newItem) {
return oldItem.getPathologyName().equals(newItem.getPathologyName());
}
}
}
The entity DAO:
package com.gmproxy.DAO;
import androidx.lifecycle.LiveData;
import androidx.room.*;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.Entities.User;
import java.util.List;
#Dao
public interface PathologyDAO {
#Query("SELECT * FROM condiciones")
LiveData<List<Pathology>> getAllObjects();
//This will come in handy for getting all those pathologies, will need to get them on a for loop since I'm not completely sure
//that the query will handle int[]
#Query("SELECT id_condiciones FROM condiciones WHERE id_condiciones LIKE :id_condiciones")
int getPathologiesForUser(int id_condiciones);
#Query("SELECT nombreCondicion FROM condiciones WHERE nombreCondicion LIKE :pathologyName")
String getPathologiesForName(String pathologyName);
#Query("SELECT * FROM condiciones WHERE nombreCondicion LIKE :pathologyName")
Pathology getPathologiesCompleteForName(String pathologyName);
#Query("SELECT * FROM condiciones WHERE id_condiciones = :id")
Pathology findObjectbyId(int id);
#Query("SELECT * FROM condiciones WHERE nombreCondicion LIKE '%' || :filter || '%'")
LiveData<List<Pathology>> filterText(String filter);
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAllObjects(List<Pathology> listObjects);
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insertObject(Pathology object);
#Update
void updateObject(Pathology object);
#Delete
void delete(Pathology obj);
}
The entity repository:
package com.gmproxy.DAO;
import android.app.Application;
import android.os.AsyncTask;
import androidx.lifecycle.LiveData;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.Entities.User;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class PathologyRepository {
private PathologyDAO concerningDao;
private LiveData<List<Pathology>> pathologyList;
public PathologyRepository(Application application) {
DatabaseHelper db = DatabaseHelper.getDatabase(application);
concerningDao = db.pathologyDao();
pathologyList = concerningDao.getAllObjects();
}
public LiveData<List<Pathology>> getAllObjects() {
return concerningDao.getAllObjects();
}
void insertAllObjects(List<Pathology> objectsList) {
DatabaseHelper.databaseWriteExecutor.execute(() ->{
concerningDao.insertAllObjects(objectsList);
});
}
public void insertObject(Pathology obj){
DatabaseHelper.databaseWriteExecutor.execute(() ->{
concerningDao.insertObject(obj);
});
}
public void deleteObject(Pathology obj) {
concerningDao.delete(obj);
}
public LiveData<List<Pathology>> filter(String input){
try{
return new FilterNoteAsyncTask(concerningDao).execute(input).get();
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
return null;
}
private static class FilterNoteAsyncTask extends AsyncTask<String, Void, LiveData<List<Pathology>>> {
private PathologyDAO pathologyDAO;
private FilterNoteAsyncTask(PathologyDAO pathologyDAO) {
this.pathologyDAO = pathologyDAO;
}
#Override
protected LiveData<List<Pathology>> doInBackground(String... strings) {
return pathologyDAO.filterText(strings[0]);
}
}
}
Move your PathologyListAdapter to global, and get adapter position using adapter object instead of getting adapter from recyclerview.
public Pathology getSelectedPathology(){
long idlongo = adapter.getAdapterPosition();
Log.println(Log.INFO, "PathologyTest", String.valueOf(idlongo));
int id = (int) idlongo;
Pathology path = pathDao.findObjectbyId(id);
return path;
}

Get an error : com.android.volley.ParseError: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray

I try to get data from the database via API but the recyclerview doesn't display anything and the log displays an error.
This is my code
Fragment
package com.example.hp.retailmakanan;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.example.hp.retailmakanan.Model.MenuModel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class FragHome extends Fragment {
RecyclerView recV;
BottomNavigationView top_navigation;
HomeAdapter listAdapter;
List<MenuModel> listMenu= new ArrayList<>();
private BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment sfragment = null;
switch (menuItem.getItemId()) {
case R.id.nav_noodle:
recV.setAdapter(listAdapter);
break;
case R.id.nav_beverage:
recV.setAdapter(listAdapter);
break;
case R.id.nav_toping:
recV.setAdapter(listAdapter);
break;
case R.id.nav_cari:
recV.setAdapter(listAdapter);
break;
}
return false;
}
};
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.act_home, container, false);
recV = (RecyclerView) v.findViewById(R.id.rec_ramen);
getData();
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recV.setLayoutManager(layoutManager);
listAdapter = new HomeAdapter(listMenu, getActivity());
recV.setAdapter(listAdapter);
top_navigation = (BottomNavigationView) v.findViewById(R.id.top_nav);
top_navigation.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener);
return v;
}
this is the code that i used to get data
private void getData() {
String url ="https://waggish-requisition.000webhostapp.com/GetAllMenu.php";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
listMenu.clear();
for (int i = 0; i < response.length(); i++) {
try {
Log.d("menu",response.toString());
JSONObject jsonObject = response.getJSONObject(i);
String id_menu = jsonObject.getString("id");
String nama_menu = jsonObject.getString("nama_menu");
String deskripsi = jsonObject.getString("deskripsi");
int harga = jsonObject.getInt("harga");
MenuModel menus = new MenuModel(id_menu,nama_menu,deskripsi,harga);
listMenu.add(menus);
System.out.println(menus);
//Toast.makeText(this,"Download data "+i,Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
Log.d("menu",e.toString());
}
listAdapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(jsonArrayRequest);
}
}
Adapter
package com.example.hp.retailmakanan;
import android.content.Context;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.hp.retailmakanan.Model.MenuModel;
import java.util.Arrays;
import java.util.List;
public class HomeAdapter extends RecyclerView.Adapter {
private List<MenuModel> menus;
private Context context;
public HomeAdapter(List<MenuModel> menus, Context context) {
this.context = context;
this.menus = menus;
//System.out.println(menus);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recv_desain, viewGroup, false);
return new ListViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int pos) {
}
#Override
public int getItemCount() {
return menus.size();
}
public class ListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView mText,txt2, txt3, txtQty;
ImageView img;
Button btnMin, btnPlus;
int x;
public ListViewHolder(View itemView){
super(itemView);
mText = itemView.findViewById(R.id.text_item);
txt2 = itemView.findViewById(R.id.text_item2);
txt3 = itemView.findViewById(R.id.textView3);
img = itemView.findViewById(R.id.image_item);
btnMin = itemView.findViewById(R.id.buttonMinMenu);
btnPlus = itemView.findViewById(R.id.buttonPlusMenu);
txtQty = itemView.findViewById(R.id.textQtyMenu);
itemView.setOnClickListener(this);
}
public void bindView (int pos){
x=0;
MenuModel model = menus.get(pos);
mText.setText(model.getNama_menu());
txt2.setText(model.getDeskripsi());
txt3.setText(model.getHarga());
//img.setImageResource(DataMenu.picture[pos]);
txtQty.setText(String.valueOf(x));
btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x++;
txtQty.setText(String.valueOf(x));
}
});
btnMin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x--;
if (x<=0){
x=0;
txtQty.setText(String.valueOf(x));
}else if (x>0){
txtQty.setText(String.valueOf(x));
}
}
});
}
#Override
public void onClick(View v) {
}
}
}
And this is my php code
<?php
require_once('connection.php');
//public $mServerName;
//public $mConnectionInfo;
//public $conn;
//Create query to retrieve all contacts
$query = "SELECT * FROM menu";
$stmt = mysqli_query($conn, $query);
if (!$stmt)
{
//Query failed
echo 'Query failed';
}
else
{
$menus= array(); //Create an array to hold all of the contacts
//Query successful, begin putting each contact into an array of contacts
while ($row = mysqli_fetch_array($stmt)) //While there are still contacts
{
//Create an associative array to hold the current contact
//the names must match exactly the property names in the contact class in our C# code.
$menu= array("id" => $row['id_menu'],
"deskripsi" => $row['Deskripsi'],
"nama_menu" => $row['nm_menu'],
"harga" => $row['harga_menu'],
"ImageUrl" =>$row['gambar']
);
//Add the contact to the contacts array
array_push($menus, $menu);
}
//Echo out the contacts array in JSON format
echo json_encode($menus);
}
?>
I changed JSONObject to JSONArray, but that caused many other errors. I am a beginner please help me. I really don't know what to do :(

Blank Screen Shows after search from database (Android)

When i tap search donor then it shows blank screen in listview i don't know why This is the response that i get back from server
This is my custom adapter code:
package com.example.kamran.ebloodbank;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by Kamran on 4/12/2017.
*/
public class DonorAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<DataSet> donorItems;
public DonorAdapter(Activity activity,List<DataSet> donorItems) {
this.activity = activity;
this.donorItems = donorItems;
}
#Override
public int getCount() {
return donorItems.size();
}
#Override
public Object getItem(int location) {
return donorItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.donor_search_list_theme, null);
TextView nameTextView = (TextView) convertView.findViewById(R.id.donor_name);
TextView areaTextView = (TextView) convertView.findViewById(R.id.donor_area);
DataSet d = donorItems.get(position);
nameTextView.setText(d.getName());
areaTextView.setText(d.getArea());
return convertView;
}
}
This is my model code:
package com.example.kamran.ebloodbank;
import android.widget.ArrayAdapter;
import java.util.ArrayList;
/**
* Created by Kamran on 4/12/2017.
*/
public class DataSet {
private String name;
private int area;
public void setArea(int area) {
this.area = area;
}
public void setName(String name) {
this.name = name;
}
public int getArea() {
return area;
}
public String getName() {
return name;
}
}
This is my first activity code:
package com.example.kamran.ebloodbank;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import com.android.volley.AuthFailureError;
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 com.example.kamran.ebloodbank.data.BloodContract.BloodEntry;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FindDonor extends AppCompatActivity {
Spinner bloodgroup;
Spinner area;
String findDonorUrl = "https://wwwkamranalitk.000webhostapp.com/findDonor.php";
int mBlood = BloodEntry.BLOOD_GROUP_A_POS;
int mArea = BloodEntry.DONOR_AREA_MALIR;
Button searchButton;
RequestQueue requestQueue;
StringRequest request;
JSONObject jsonObject;
JSONArray result;
private List<DataSet> donorList = new ArrayList<DataSet>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_donor);
bloodgroup = (Spinner) findViewById(R.id.bloodspinnerfinddonor);
area = (Spinner) findViewById(R.id.areaSpinner);
searchButton = (Button) findViewById(R.id.searchDonor);
setupSpinnerBlood();
setupSpinnerArea();
requestQueue = Volley.newRequestQueue(getApplicationContext());
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
request = new StringRequest(Request.Method.POST, findDonorUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
jsonObject = new JSONObject(response);
result = jsonObject.getJSONArray("result");
JSONObject donorData = result.getJSONObject(0);
DataSet donorSet = new DataSet();
donorSet.setName(donorData.getString("name"));
donorSet.setArea(donorData.getInt("area"));
donorList.add(donorSet);
Intent intent = new Intent(FindDonor.this, DonorSearchList.class);
startActivity(intent);
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> parameters = new HashMap<String, String>();
parameters.put("bloodgroup", String.valueOf(mBlood));
parameters.put("area", String.valueOf(mArea));
return parameters;
}
};
requestQueue.add(request);
}
});
}
private void setupSpinnerBlood() {
ArrayAdapter bloodGroupSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.blood_group, android.R.layout.simple_spinner_item);
bloodGroupSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
bloodgroup.setAdapter(bloodGroupSpinnerAdapter);
bloodgroup.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if (!TextUtils.isEmpty(selection)) {
if (selection.equals(getString(R.string.blood_apos))) {
mBlood = BloodEntry.BLOOD_GROUP_A_POS;
} else if (selection.equals((getString(R.string.blood_bpos)))) {
mBlood = BloodEntry.BLOOD_GROUP_B_POS;
} else if (selection.equals(getString(R.string.blood_opos))) {
mBlood = BloodEntry.BLOOD_GROUP_O_POS;
} else if (selection.equals((getString(R.string.blood_oneg)))) {
mBlood = BloodEntry.BLOOD_GROUP_O_NEG;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
mBlood = BloodEntry.BLOOD_GROUP_A_POS;
}
});
}
private void setupSpinnerArea() {
ArrayAdapter areaSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.area, android.R.layout.simple_spinner_item);
areaSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
area.setAdapter(areaSpinnerAdapter);
area.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if (!TextUtils.isEmpty(selection)) {
if (selection.equals(getString(R.string.donor_area_malir))) {
mArea = BloodEntry.DONOR_AREA_MALIR;
} else if (selection.equals(getString(R.string.donor_area_defence))) {
mArea = BloodEntry.DONOR_AREA_DEFENCE;
} else if (selection.equals(getString(R.string.donor_area_korangi))) {
mArea = BloodEntry.DONOR_AREA_KORANGI;
} else if (selection.equals(getString(R.string.donor_area_johar))) {
mArea = BloodEntry.DONOR_AREA_JOHAR;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
mArea = BloodEntry.DONOR_AREA_MALIR;
}
});
}
}
and This is the code in which data will be shown:
package com.example.kamran.ebloodbank;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DonorSearchList extends AppCompatActivity {
private String mArea;
private List<DataSet> donorList = new ArrayList<DataSet>();
private ListView listView;
private DonorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_donor_search_list);
listView = (ListView) findViewById(R.id.donorListView);
adapter = new DonorAdapter(this, donorList);
listView.setAdapter(adapter);
}
}
You need to transfer data from the search to list activity.
Try something like this:
public class bridge {
public static List<DataSet> donorList = new ArrayList<DataSet>();
}
Then, in the class FindDonor:
donorSet.setName(donorData.getString("name"));
donorSet.setArea(donorData.getInt("area"));
donorList.add(donorSet);
//here put this line
bridge.donarList = donarList;
//rest code
Intent intent = new Intent(FindDonor.this, DonorSearchList.class);
Then, in the DonorSearchList class:
adapter = new DonorAdapter(this, bridge.donorList);

Parsing JSON data & Load it in Fragments

Excuse me i already had an Application which Display my Sites articles and Novels in Android the codes in Main Activity to display only one Section
i create in the site 5 sections every section had a different content
i Added items to Navigation Drawers and i defined the fragment and its connectivity but the Problem in the Code i failed so
i want to know how to load Data in 4 Fragments
RecyclerViewAdapter.class
import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private int previousPosition = 0;
private List<com.salim3dd.recyclerview_moredata.List_Item> List_Item;
private Context context;
public RecyclerViewAdapter(List<List_Item> list_Item, Context context) {
List_Item = list_Item;
this.context = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View menu1 = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.row_item, viewGroup, false);
return new MenuItemViewHolder(menu1);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
MenuItemViewHolder menuItemHolder = (MenuItemViewHolder) holder;
menuItemHolder.TextName.setText(List_Item.get(position).getStory());
Picasso.with(context).load(List_Item.get(position).getImg_link()).into(menuItemHolder.imageView);
menuItemHolder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, List_Item.get(position).getStory(), Toast.LENGTH_SHORT).show();
}
});
if (position > previousPosition) { //scrolling DOWN
AnimationUtil.animate(menuItemHolder, true);
} else { // scrolling UP
AnimationUtil.animate(menuItemHolder, false);
}
previousPosition = position;
}
#Override
public int getItemCount() {
return (null != List_Item ? List_Item.size() : 0);
}
protected class MenuItemViewHolder extends RecyclerView.ViewHolder {
private CardView cardView;
private ImageView imageView;
private TextView TextName;
public MenuItemViewHolder(View view) {
super(view);
cardView = (CardView) view.findViewById(R.id.cardView);
imageView = (ImageView) view.findViewById(R.id.imageView);
TextName = (TextView) view.findViewById(R.id.TextName);
}
}
}
MainActivity
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;
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 com.salim3dd.recyclerview_moredata.CheckInternetConnection;
import com.salim3dd.recyclerview_moredata.List_Item;
import com.salim3dd.recyclerview_moredata.R;
import com.salim3dd.recyclerview_moredata.RecyclerViewAdapter;
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 RecyclerView recyclerView;
private RecyclerViewAdapter recyclerView_dAdapter;
public List<List_Item> listItem = new ArrayList<>();
private GridLayoutManager gridLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.m_RecyclerView);
recyclerView.setHasFixedSize(true);
gridLayoutManager = new GridLayoutManager(this, 1);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView_dAdapter = new RecyclerViewAdapter(listItem, this);
recyclerView.setAdapter(recyclerView_dAdapter);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (gridLayoutManager.findLastCompletelyVisibleItemPosition() == listItem.size() - 1) {
Get_All_Users(listItem.get(listItem.size()-1).getId());
}
}
});
Get_All_Users(0);
}
public void Get_All_Users(int limit) {
CheckInternetConnection cic = new CheckInternetConnection(getApplicationContext());
Boolean Ch = cic.isConnectingToInternet();
if (!Ch) {
Toast.makeText(this, R.string.no_internet_connection, Toast.LENGTH_SHORT).show();
} else {
StringRequest stringRequest = new StringRequest(Request.Method.GET,
"Data Link" + limit
,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonResponse = jsonArray.getJSONObject(0);
JSONArray jsonArray_usersS = jsonResponse.getJSONArray("All_storys");
for (int i = 0; i < jsonArray_usersS.length(); i++) {
JSONObject responsS = jsonArray_usersS.getJSONObject(i);
int id = responsS.getInt("id");
String story = responsS.getString("story_name");
String img_link = responsS.getString("img_link");
listItem.add(new List_Item(id, story, img_link));
}
recyclerView_dAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(stringRequest);
stringRequest.setShouldCache(false);
}
}
}
List Items.class
public class List_Item {
public int id;
public String story;
public String img_link;
public List_Item(int id, String story, String img_link) {
this.id = id;
this.story = story;
this.img_link = img_link;
}
public int getId() {
return id;
}
public String getStory() {
return story;
}
public String getImg_link() {
return img_link;
}
public void setId(int id) {
this.id = id;
}
}

Categories

Resources