In my activity all tabs are created as dynamic. Each swiping json data is called. The volley error occurs after a number of swiping. After this , no data is available on fragment and any of the other pages. This is my code
fragmentParent.addPage(jsonObject.getString("name"),jsonObject.getString("cat_id"),shop_id);
public class FragmentParent extends Fragment {
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter1 adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_parent, container, false);
getIDs(view);
setEvents();
return view;
}
private void getIDs(View view) {
viewPager = (ViewPager) view.findViewById(R.id.my_viewpager);
tabLayout = (TabLayout) view.findViewById(R.id.my_tab_layout);
adapter = new ViewPagerAdapter1(getFragmentManager(), getActivity(), viewPager, tabLayout);
viewPager.setAdapter(adapter);
}
int selectedTabPosition;
private void setEvents() {
tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
viewPager.setCurrentItem(tab.getPosition());
selectedTabPosition = viewPager.getCurrentItem();
Log.d("Selected", "Selected " + tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
super.onTabUnselected(tab);
Log.d("Unselected", "Unselected " + tab.getPosition());
}
});
}
public void addPage(String pagename, String id,String shop_id) {
Bundle bundle = new Bundle();
bundle.putString("data", id);
bundle.putString("shop_id", shop_id);
FragmentChild fragmentChild = new FragmentChild();
fragmentChild.setArguments(bundle);
adapter.addFrag(fragmentChild, pagename);
adapter.notifyDataSetChanged();
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(adapter.getCount() - 1);
setupTabLayout();
}
public void setupTabLayout() {
selectedTabPosition = viewPager.getCurrentItem();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(adapter.getTabView(i));
}
}
}
public class FragmentChild extends Fragment {
String childname,shoppe_id;
RecyclerView imgflag;
CategoryItemAdapter categoryItemAdapter;
HttpStack stack;
List<ShopDetails> cat_item_list;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_child, container, false);
Bundle bundle = getArguments();
childname = bundle.getString("data");
shoppe_id=bundle.getString("shop_id");
stack = new HurlStack();
imgflag=(RecyclerView)view.findViewById(R.id.imgflag);
cat_item_list = new ArrayList<ShopDetails>();
categoryItemAdapter = new CategoryItemAdapter(getActivity(),cat_item_list);
GridLayoutManager layoutManager
= new GridLayoutManager(getActivity(),1, GridLayoutManager.VERTICAL,false);
imgflag.setLayoutManager(layoutManager);
imgflag.setAdapter(categoryItemAdapter);
getCategoryItem(childname);
return view;
}
public void getCategoryItem(String cat_id)
{
stack = new HurlStack(null, createSslSocketFactory());
final RequestQueue requestQueue = Volley.newRequestQueue(getActivity(),stack);
String url=config.api_url+"view_cat_item.php?cat_id="+cat_id;
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.equals("0 results"))
{
}
else
{
try {
JSONArray jsonArray=new JSONArray(response);
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject=jsonArray.getJSONObject(i);
ShopDetails shopDetails=new ShopDetails();
shopDetails.setItem_name(jsonObject.getString("item_name"));
shopDetails.setItem_image(jsonObject.getString("image"));
shopDetails.setItem_price(jsonObject.getString("price"));
shopDetails.setItem_desc(jsonObject.getString("ingredients"));
cat_item_list.add(shopDetails);
}
if(cat_item_list!=null)
{
categoryItemAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Unable to connect. Please check your connection.", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("shoppe_id", shoppe_id);
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
stringRequest.setShouldCache(false);
requestQueue.add(stringRequest);
}
private static SSLSocketFactory createSslSocketFactory() {
TrustManager[] byPassTrustManagers = new TrustManager[]{new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
}};
SSLContext sslContext = null;
SSLSocketFactory sslSocketFactory = null;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, byPassTrustManagers, new SecureRandom());
sslSocketFactory = sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
Log.e(TAG, StringUtils.EMPTY, e);
} catch (KeyManagementException e) {
Log.e(TAG, StringUtils.EMPTY, e);
}
return sslSocketFactory;
}
public final boolean isInternetOn() {
ConnectivityManager connec = (ConnectivityManager) getActivity().getSystemService(getActivity().getBaseContext().CONNECTIVITY_SERVICE);
if (connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED) {
return true;
} else if (
connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED) {
return false;
}
return false;
}
}
you need to use validation while receiving response from volley just use condition like that :
if(response!=null&&response.length()>10){
try {
JSONArray jsonArray=new JSONArray(response);
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject=jsonArray.getJSONObject(i);
ShopDetails shopDetails=new ShopDetails();
shopDetails.setItem_name(jsonObject.getString("item_name"));
shopDetails.setItem_image(jsonObject.getString("image"));
shopDetails.setItem_price(jsonObject.getString("price"));
shopDetails.setItem_desc(jsonObject.getString("ingredients"));
cat_item_list.add(shopDetails);
}
if(cat_item_list!=null)
{
categoryItemAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}else{
Log.e("invalid","invalide responce");
}
OR
also add condition on :
cat_id!=0 OR cat_id!=null
String url=config.api_url+"view_cat_item.php?cat_id="+cat_id;
I think it happens because when you switch fragments volley create request again and again. so you can cancel volley request when you leave from fragments by override onStop() method
#Override
public void onStop() {
super.onStop();
VolleySingleton.getInstance(getActivity()).getRequestQueue().cancelAll(VolleySingleton.TAG);
}
you can set Tag like this
jsonObjectRequest.setTag(VolleySingleton.TAG);
VolleySingleton.java
public class VolleySingleton {
private static VolleySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
public static final String TAG = "tagData";
private VolleySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized VolleySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new VolleySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
}
Related
I'm having a problem, that maybe we can solve it and help the community. I have made an Adapter for my RecyclerView and I have created a listener for the constraint layout in order to remove one element of the list. As you can see in the code the delete message works well but I don't know how to update the RecyclerView from the AccountFragment (the one that's using this adapter). Does anyone know how to notify that changes?
AccountFragment:
public class AccountFragment extends Fragment {
private TextView textViewUserProfileUsername;
private TextView textViewUserProfileDescription;
private ImageButton imageButtonAccountEdit;
private EditText editTextAccountDescription;
private RecyclerView recyclerViewUserProfileComments;
private TextView textViewUserProfileNoComments;
private ImageView imageViewUserProfileSendMessage;
private EditText editTextUserProfileSendMessage;
private final Gson gson = new Gson();
private User userLocal;
private SharedPreferences sharedPreferences;
private Context context;
private AlertDialog dialog;
private String previousDescription;
private AccountCommentsAdapter accountCommentsAdapter;
private final List<UserComments> userCommentsList = new ArrayList<>();
public AccountFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
assert context != null;
sharedPreferences = context.getSharedPreferences(Constants.sharedPreferencesDocName, Context.MODE_PRIVATE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_account, container, false);
}
#Override
public void onViewCreated(#NonNull #NotNull View view, #Nullable #org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
bindUI(view);
setListeners();
userLocal = gson.fromJson(sharedPreferences.getString("user", ""), User.class);
showUserInformation();
setAdapter();
}
private void bindUI(View view) {
textViewUserProfileUsername = view.findViewById(R.id.textViewUserProfileUsername);
textViewUserProfileDescription = view.findViewById(R.id.textViewUserProfileDescription);
imageButtonAccountEdit = view.findViewById(R.id.imageButtonAccountEdit);
recyclerViewUserProfileComments = view.findViewById(R.id.recyclerViewUserProfileComments);
textViewUserProfileNoComments = view.findViewById(R.id.textViewUserProfileNoComments);
imageViewUserProfileSendMessage = view.findViewById(R.id.imageViewUserProfileSendMessage);
editTextUserProfileSendMessage = view.findViewById(R.id.editTextUserProfileSendMessage);
}
private void setListeners() {
imageButtonAccountEdit.setOnClickListener(v -> showEditDescriptionDialog());
imageViewUserProfileSendMessage.setOnClickListener(view -> {
if (!TextUtils.isEmpty(editTextUserProfileSendMessage.getText().toString())) {
final Date currentTime = new Date();
#SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
TimeZone timeZone = simpleDateFormat.getTimeZone();
simpleDateFormat.setTimeZone(timeZone);
String date = simpleDateFormat.format(currentTime);
final UserComments userCommentsToAdd = new UserComments(userLocal.getId(), userLocal.getId(), userLocal.getUsername(), userLocal.getUsername(), editTextUserProfileSendMessage.getText().toString().trim(), date);
editTextUserProfileSendMessage.setText("");
addComment(userCommentsToAdd);
}
});
}
private void showUserInformation() {
textViewUserProfileUsername.setText(userLocal.getUsername());
textViewUserProfileDescription.setText(userLocal.getDescription());
getUserComments();
}
private void showEditDescriptionDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(getString(R.string.edit_description));
final View customLayout = getLayoutInflater().inflate(R.layout.alert_dialog_edit_account, null);
builder.setView(customLayout);
dialog = builder.create();
editTextAccountDescription = customLayout.findViewById(R.id.editTextAccountDescription);
if (userLocal.getDescription() != null) {
editTextAccountDescription.setText(userLocal.getDescription());
previousDescription = editTextAccountDescription.getText().toString();
}
Button buttonAccountCancelDescription = customLayout.findViewById(R.id.buttonAccountCancelDescription);
Button buttonAccountSaveDescription = customLayout.findViewById(R.id.buttonAccountSaveDescription);
buttonAccountSaveDescription.setOnClickListener(v -> saveUserDescription());
buttonAccountSaveDescription.setOnClickListener(v -> {
if (editTextAccountDescription.getText().toString().length() <= 150) {
saveUserDescription();
} else {
setErrors(2);
}
});
editTextAccountDescription.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 150) {
setErrors(2);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
buttonAccountCancelDescription.setOnClickListener(v -> dialog.dismiss());
dialog.setCancelable(false);
dialog.show();
}
private void saveUserDescription() {
if (!editTextAccountDescription.getText().toString().isEmpty()) {
if (!editTextAccountDescription.getText().toString().equals(previousDescription)) {
userLocal.setDescription(editTextAccountDescription.getText().toString());
sharedPreferences.edit().putString("user", gson.toJson(userLocal)).apply();
Thread thread = new Thread() {
#Override
public void run() {
Response response;
try {
response = UserRequests.editUserDescription(userLocal.getId(), userLocal.getDescription());
if (response.code() == 200) {
String responseBody = Objects.requireNonNull(response.body()).string();
responseBody = responseBody.replace("\r\n", "");
if (responseBody.contains("1")) {
updateDescription();
} else if (responseBody.contains("2")) {
updateDescription();
} else {
setErrors(1);
}
} else {
setErrors(1);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
thread.start();
} else {
setErrors(4);
}
} else {
setErrors(3);
}
}
private void updateDescription() {
Thread thread = new Thread() {
public void run() {
requireActivity().runOnUiThread(() -> {
textViewUserProfileDescription.setText(userLocal.getDescription());
dialog.dismiss();
});
}
};
thread.start();
}
private void setErrors(int error) {
switch (error) {
case 1:
Thread thread = new Thread() {
public void run() {
requireActivity().runOnUiThread(() -> Toast.makeText(context, getString(R.string.generic_error), Toast.LENGTH_SHORT).show());
}
};
thread.start();
break;
case 2:
editTextAccountDescription.setError(getString(R.string.description_length));
editTextAccountDescription.requestFocus();
break;
case 3:
editTextAccountDescription.setError(getString(R.string.required_field));
editTextAccountDescription.requestFocus();
break;
case 4:
dialog.dismiss();
break;
}
}
private void setAdapter() {
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
linearLayoutManager.setStackFromEnd(true);
recyclerViewUserProfileComments.setLayoutManager(linearLayoutManager);
recyclerViewUserProfileComments.scrollToPosition(userCommentsList.size() - 1);
}
private void displayMessages() {
if (userCommentsList.size() > 0) {
Thread thread = new Thread() {
public void run() {
requireActivity().runOnUiThread(() -> {
if (recyclerViewUserProfileComments.getVisibility() == View.GONE) {
recyclerViewUserProfileComments.setVisibility(View.VISIBLE);
}
if (textViewUserProfileNoComments.getVisibility() == View.VISIBLE) {
textViewUserProfileNoComments.setVisibility(View.GONE);
}
accountCommentsAdapter = new AccountCommentsAdapter(context, userCommentsList);
recyclerViewUserProfileComments.setAdapter(accountCommentsAdapter);
recyclerViewUserProfileComments.scrollToPosition(userCommentsList.size() - 1);
accountCommentsAdapter.notifyDataSetChanged();
});
}
};
thread.start();
} else {
Thread thread = new Thread() {
public void run() {
requireActivity().runOnUiThread(() -> {
recyclerViewUserProfileComments.setVisibility(View.GONE);
textViewUserProfileNoComments.setVisibility(View.VISIBLE);
});
}
};
thread.start();
}
}
private void addComment(UserComments userCommentsToAdd) {
Thread thread = new Thread() {
#Override
public void run() {
Response response;
try {
response = UserCommentsRequests.addUserComment(userCommentsToAdd);
if (response.code() == 200) {
String responseBody = Objects.requireNonNull(response.body()).string();
responseBody = responseBody.replace("\r\n", "");
if (responseBody.contains("1")) {
userCommentsList.add(userCommentsToAdd);
userCommentsList.clear();
getUserComments();
}
} else if (response.code() == 204) {
displayMessages();
} else {
setErrors(1);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
thread.start();
}
private void getUserComments() {
Thread thread = new Thread() {
#Override
public void run() {
Response response;
try {
response = UserCommentsRequests.getUserComments(userLocal.getId());
if (response.code() == 200) {
String responseBody = Objects.requireNonNull(response.body()).string();
responseBody = responseBody.replace("\r\n", "");
JSONArray responseArray = new JSONArray(responseBody);
for (int i = 0; i < responseArray.length(); i++) {
String jsonObjectString = responseArray.getJSONObject(i).toString();
userCommentsList.add(gson.fromJson(jsonObjectString, UserComments.class));
}
displayMessages();
} else if (response.code() == 204) {
displayMessages();
} else {
setErrors(1);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
thread.start();
}
}
AccountCommentsAdapter:
public class AccountCommentsAdapter extends RecyclerView.Adapter<AccountCommentsAdapter.AccountCommentsAdapterViewHolder> {
private final Context context;
List<UserComments> userCommentsList;
public static final int MSG_TYPE_LEFT = 0;
public static final int MSG_TYPE_RIGHT = 1;
public AccountCommentsAdapter(Context context, List<UserComments> userCommentsList) {
this.context = context;
this.userCommentsList = userCommentsList;
}
#NonNull
#NotNull
#Override
public AccountCommentsAdapterViewHolder onCreateViewHolder(#NonNull #NotNull ViewGroup parent, int viewType) {
View view;
if (viewType == MSG_TYPE_RIGHT) {
view = LayoutInflater.from(context).inflate(R.layout.fragment_chat_message_sent, parent, false);
} else {
view = LayoutInflater.from(context).inflate(R.layout.fragment_chat_message_received, parent, false);
}
return new AccountCommentsAdapterViewHolder(view);
}
#Override
public int getItemViewType(int position) {
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
assert firebaseUser != null;
if (userCommentsList.get(position).getUser_from_username().equals(firebaseUser.getDisplayName())) {
return MSG_TYPE_RIGHT;
} else {
return MSG_TYPE_LEFT;
}
}
#Override
public void onBindViewHolder(#NonNull #NotNull AccountCommentsAdapterViewHolder holder, int position) {
UserComments userComments = userCommentsList.get(position);
int viewType = holder.getItemViewType();
if (viewType == MSG_TYPE_LEFT) {
holder.textViewMessageUsername.setText(userComments.getUser_from_username());
holder.textViewMessageUsername.setOnClickListener(v -> {
Intent intent = new Intent(context, UserProfileActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle bundle = new Bundle();
bundle.putString("userId", userComments.getUser_from_id());
bundle.putString("username", userComments.getUser_from_username());
intent.putExtras(bundle);
context.startActivity(intent);
});
holder.constraintLayoutMessageRight.setOnLongClickListener(v -> {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.delete_message)
.setPositiveButton(R.string.yes, (dialogInterface, i) -> deleteMessage(position))
.setNegativeButton(R.string.no, (dialogInterface, which) -> dialogInterface.dismiss());
builder.create();
builder.show();
return false;
});
} else {
holder.constraintLayoutMessageRight.setOnLongClickListener(v -> {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.delete_message)
.setPositiveButton(R.string.yes, (dialogInterface, i) -> deleteMessage(position))
.setNegativeButton(R.string.no, (dialogInterface, which) -> dialogInterface.dismiss());
builder.create();
builder.show();
return false;
});
}
holder.textViewMessageMessage.setText(userComments.getMessage());
holder.textViewMessageTime.setText(userComments.getCreated_time());
}
#Override
public int getItemCount() {
return userCommentsList.size();
}
public static class AccountCommentsAdapterViewHolder extends RecyclerView.ViewHolder {
ConstraintLayout constraintLayoutMessageRight;
TextView textViewMessageMessage;
TextView textViewMessageTime;
TextView textViewMessageUsername;
public AccountCommentsAdapterViewHolder(#NonNull #NotNull View itemView) {
super(itemView);
textViewMessageMessage = itemView.findViewById(R.id.textViewMessageMessage);
textViewMessageTime = itemView.findViewById(R.id.textViewMessageTime);
constraintLayoutMessageRight = itemView.findViewById(R.id.constraintLayoutMessageRight);
textViewMessageUsername = itemView.findViewById(R.id.textViewMessageUsername);
}
}
private void deleteMessage(int position) {
UserComments userCommentsToRemove = userCommentsList.get(position);
Thread thread = new Thread() {
#Override
public void run() {
Response response;
try {
response = UserCommentsRequests.removeUserComments(userCommentsToRemove.getId());
if (response.code() == 200) {
String responseBody = Objects.requireNonNull(response.body()).string();
responseBody = responseBody.replace("\r\n", "");
if (responseBody.contains("1")) {
userCommentsList.remove(position);
// Here it should update the recyclerview in order to notify that element has been removed.
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
thread.start();
}
}
UPDATE:
Solved by adding this method and then call it after userCommentsList.remove(position):
private void updateUI(){
Handler mainHandler = new Handler(context.getMainLooper());
Runnable runnable = this::notifyDataSetChanged;
mainHandler.post(runnable);
}
Inside the adapter you can use notifyDataSetChanged()
I just want to load data from my localhost using recyclerview inside fragment but nothing shows and it says getApplicationContext may produce NullPointerException.
The error is on the
Volley.newRequestQueue(getActivity().getApplicationContext()).add(stringRequest);
I tried the code on main activity and it works fine.
public class UpdateFragment extends Fragment {
private static final String URL = "http://192.168.1.32/CAGELCOII_APP/api.php";
RecyclerView recyclerView;
ItemAdapter adapter;
List<Item> itemList;
public UpdateFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_update, container, false);
itemList = new ArrayList<>();
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
loadItem();
adapter = new ItemAdapter(getActivity(), itemList);
recyclerView.setAdapter(adapter);
return view;
}
private void loadItem(){
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray products = new JSONArray(response);
for(int i =0; i < products.length(); i++){
JSONObject productObject = products.getJSONObject(i);
int id = productObject.getInt("id");
String description = productObject.getString("description");
String agency = productObject.getString("agency");
String date = productObject.getString("date");
String time = productObject.getString("time");
String image = productObject.getString("image");
Item item = new Item(id, description, agency, date, time, image);
itemList.add(item);
}
adapter = new ItemAdapter(getActivity(), itemList);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(getActivity().getApplicationContext()).add(stringRequest);
}
}
You'll have to make sure your fragment isAdded() to activity when calling getActivity() otherwise you'll get a NullPointerException since getActivity() returns the activity hosting the fragment.
If you always want to use application context, due to its non-dying lifecycle you can retrieve it across the entire app using this static function:
App.java
public class App extends Application {
private static Context sAppContext;
public void onCreate() {
super.onCreate();
sAppContext = this;
}
public static Context getContext() {
return sAppContext;
}
}
AndroidManifest.xml
...
<application
android:name=".App"
...>
</application>
And you can use it in your code as:
Volley.newRequestQueue(App.getContext()).add(stringRequest);
Please Try This code
RequestQueue mRequestQueue = Volley.newRequestQueue(getActivity());
mRequestQueue.add(jsonObjReq);
There are two way to hit volley request:
First
use app controller class
AppController
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new ImageClass());
}
return this.mImageLoader;
}
public void addToRequestQueue(Request req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public void addToRequestQueue(Request req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
**ImageClass **
public class ImageClass extends LruCache<String, Bitmap> implements
ImageCache {
public static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
return cacheSize;
}
public ImageClass() {
this(getDefaultLruCacheSize());
}
public ImageClass(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}
#Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight() / 1024;
}
#Override
public Bitmap getBitmap(String url) {
return get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
}
}
manifest
<application
android:allowBackup="true"
android:name=".AppController"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
android:name=".AppController"
add in menifest
MainActivity
String url = Global.BASE_URL + "api/";
StringRequest jsonObjReq = new StringRequest(Request.Method.POST, url,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, response.toString());
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Error Log
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
//Pass the parameters to according to the API.
Map<String, String> params = new HashMap<String, String>();
params.put("API_HASH", "hasKey");
Log.e(TAG, "splash paramsTest----" + params);
return params;
}
};
/* ----Adding request to request queue----*/
AppController.getInstance().addToRequestQueue(jsonObjReq,
GlobalString.cancel_login_api);
Second
RequestQueue mRequestQueue = Volley.newRequestQueue(getActivity());
mRequestQueue.add(jsonObjReq);
I'm loading json file from online and saving it on Sqlite such that when app is offline...Then still user will be able to see the data.
It works fine in MainActivity.
But when I try to covert it into fragment, I'm getting errors of Fragment cannot be cast in to FlowerAdapter$FlowerClickListener
Here is the error file
My Fragment name is nepali.
Here is the Mainactivity
public class MainActivity extends AppCompatActivity implements FlowerAdapter.FlowerClickListener, FlowerFetchListener {
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView mRecyclerView;
private RestManager mManager;
private FlowerAdapter mFlowerAdapter;
private FlowerDatabase mDatabase;
private Button mReload;
private ProgressDialog mDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
configViews();
mManager = new RestManager();
mDatabase = new FlowerDatabase(this);
loadFlowerFeed();
mReload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadFlowerFeed();
}
});
}
private void loadFlowerFeed() {
mDialog = new ProgressDialog(MainActivity.this);
mDialog.setMessage("Loading Flower Data...");
mDialog.setCancelable(true);
mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mDialog.setIndeterminate(true);
mFlowerAdapter.reset();
mDialog.show();
if (getNetworkAvailability()) {
getFeed();
} else {
getFeedFromDatabase();
}
}
private void getFeedFromDatabase() {
mDatabase.fetchFlowers(this);
}
private void configViews() {
mReload = (Button) findViewById(R.id.reload);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
mFlowerAdapter = new FlowerAdapter(this);
mRecyclerView.setAdapter(mFlowerAdapter);
}
#Override
public void onClick(int position) {
}
public void getFeed() {
Call<List<Flower>> listCall = mManager.getFlowerService().getAllFlowers();
listCall.enqueue(new Callback<List<Flower>>() {
#Override
public void onResponse(Call<List<Flower>> call, Response<List<Flower>> response) {
if (response.isSuccessful()) {
List<Flower> flowerList = response.body();
for (int i = 0; i < flowerList.size(); i++) {
Flower flower = flowerList.get(i);
SaveIntoDatabase task = new SaveIntoDatabase();
task.execute(flower);
mFlowerAdapter.addFlower(flower);
}
} else {
int sc = response.code();
switch (sc) {
case 400:
Log.e("Error 400", "Bad Request");
break;
case 404:
Log.e("Error 404", "Not Found");
break;
default:
Log.e("Error", "Generic Error");
}
}
mDialog.dismiss();
}
#Override
public void onFailure(Call<List<Flower>> call, Throwable t) {
mDialog.dismiss();
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public boolean getNetworkAvailability() {
return Utils.isNetworkAvailable(getApplicationContext());
}
#Override
public void onDeliverAllFlowers(List<Flower> flowers) {
}
#Override
public void onDeliverFlower(Flower flower) {
mFlowerAdapter.addFlower(flower);
}
#Override
public void onHideDialog() {
mDialog.dismiss();
}
public class SaveIntoDatabase extends AsyncTask<Flower, Void, Void> {
private final String TAG = SaveIntoDatabase.class.getSimpleName();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Flower... params) {
Flower flower = params[0];
try {
} catch (Exception e) {
Log.d(TAG, e.getMessage());
}
return null;
}
}
}
and FlowerDatabase class is
public class FlowerDatabase extends SQLiteOpenHelper {
private static final String TAG = FlowerDatabase.class.getSimpleName();
public FlowerDatabase(Context context) {
super(context, Constants.DATABASE.DB_NAME, null, Constants.DATABASE.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(Constants.DATABASE.CREATE_TABLE_QUERY);
} catch (SQLException ex) {
Log.d(TAG, ex.getMessage());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(Constants.DATABASE.DROP_QUERY);
this.onCreate(db);
}
public void addFlower(Flower flower) {
Log.d(TAG, "Values Got " + flower.getName());
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Constants.DATABASE.PRODUCT_ID, flower.getProductId());
values.put(Constants.DATABASE.CATEGORY, flower.getCategory());
values.put(Constants.DATABASE.PRICE, Double.toString(flower.getPrice()));
values.put(Constants.DATABASE.INSTRUCTIONS, flower.getInstructions());
values.put(Constants.DATABASE.NAME, flower.getName());
try {
db.insert(Constants.DATABASE.TABLE_NAME, null, values);
} catch (Exception e) {
}
db.close();
}
public void fetchFlowers(FlowerFetchListener listener) {
FlowerFetcher fetcher = new FlowerFetcher(listener, this.getWritableDatabase());
fetcher.start();
}
public class FlowerFetcher extends Thread {
private final FlowerFetchListener mListener;
private final SQLiteDatabase mDb;
public FlowerFetcher(FlowerFetchListener listener, SQLiteDatabase db) {
mListener = listener;
mDb = db;
}
#Override
public void run() {
Cursor cursor = mDb.rawQuery(Constants.DATABASE.GET_FLOWERS_QUERY, null);
final List<Flower> flowerList = new ArrayList<>();
if (cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
Flower flower = new Flower();
flower.setFromDatabase(true);
flower.setName(cursor.getString(cursor.getColumnIndex(Constants.DATABASE.NAME)));
flower.setPrice(Double.parseDouble(cursor.getString(cursor.getColumnIndex(Constants.DATABASE.PRICE))));
flower.setInstructions(cursor.getString(cursor.getColumnIndex(Constants.DATABASE.INSTRUCTIONS)));
flower.setCategory(cursor.getString(cursor.getColumnIndex(Constants.DATABASE.CATEGORY)));
flower.setProductId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Constants.DATABASE.PRODUCT_ID))));
flowerList.add(flower);
publishFlower(flower);
} while (cursor.moveToNext());
}
}
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
mListener.onDeliverAllFlowers(flowerList);
mListener.onHideDialog();
}
});
}
public void publishFlower(final Flower flower) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
mListener.onDeliverFlower(flower);
}
});
}
}
}
and FlowerAdapter Class is
public class FlowerAdapter extends RecyclerView.Adapter<FlowerAdapter.Holder> {
private static final String TAG = FlowerAdapter.class.getSimpleName();
private final FlowerClickListener mListener;
private List<Flower> mFlowers;
public FlowerAdapter(FlowerClickListener listener) {
mFlowers = new ArrayList<>();
mListener = listener;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item, null, false);
return new Holder(row);
}
#Override
public void onBindViewHolder(Holder holder, int position) {
Flower currFlower = mFlowers.get(position);
holder.mName.setText(currFlower.getName());
holder.minstruction.setText(currFlower.getInstructions());
}
#Override
public int getItemCount() {
return mFlowers.size();
}
public void addFlower(Flower flower) {
mFlowers.add(flower);
notifyDataSetChanged();
}
/**
* #param position
* #return
*/
public Flower getSelectedFlower(int position) {
return mFlowers.get(position);
}
public void reset() {
mFlowers.clear();
notifyDataSetChanged();
}
public class Holder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView mName, minstruction;
public Holder(View itemView) {
super(itemView);
mName = (TextView) itemView.findViewById(R.id.flowerName);
minstruction = (TextView) itemView.findViewById(R.id.flowerPrice);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
mListener.onClick(getLayoutPosition());
}
}
public interface FlowerClickListener {
void onClick(int position);
}
}
My fragment class is that I try to convert above Mainactivity code into Frament class is
public class nepali extends Fragment {
private static final String TAG = nepali.class.getSimpleName();
private RecyclerView mRecyclerView;
private RestManager mManager;
private FlowerAdapter mFlowerAdapter;
private FlowerDatabase mDatabase;
private Button mReload;
private ProgressDialog mDialog;
View view;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_data, container, false);
configViews();
mManager = new RestManager();
mDatabase = new FlowerDatabase(getActivity());
loadFlowerFeed();
mReload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadFlowerFeed();
}
});
return view;
}
private void loadFlowerFeed() {
mDialog = new ProgressDialog(getActivity());
mDialog.setMessage("Loading Flower Data...");
mDialog.setCancelable(true);
mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mDialog.setIndeterminate(true);
mFlowerAdapter.reset();
mDialog.show();
if (getNetworkAvailability()) {
getFeed();
} else {
getFeedFromDatabase();
}
}
private void getFeedFromDatabase() {
mDatabase.fetchFlowers(this);
}
private void configViews() {
mReload = (Button) view.findViewById(R.id.reload);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
mFlowerAdapter = new FlowerAdapter((FlowerAdapter.FlowerClickListener) this);;
mRecyclerView.setAdapter(mFlowerAdapter);
}
public void getFeed() {
Call<List<Flower>> listCall = mManager.getFlowerService().getAllFlowers();
listCall.enqueue(new Callback<List<Flower>>() {
#Override
public void onResponse(Call<List<Flower>> call, Response<List<Flower>> response) {
if (response.isSuccessful()) {
List<Flower> flowerList = response.body();
for (int i = 0; i < flowerList.size(); i++) {
Flower flower = flowerList.get(i);
SaveIntoDatabase task = new SaveIntoDatabase();
task.execute(flower);
mFlowerAdapter.addFlower(flower);
}
} else {
int sc = response.code();
switch (sc) {
case 400:
Log.e("Error 400", "Bad Request");
break;
case 404:
Log.e("Error 404", "Not Found");
break;
default:
Log.e("Error", "Generic Error");
}
}
mDialog.dismiss();
}
#Override
public void onFailure(Call<List<Flower>> call, Throwable t) {
mDialog.dismiss();
Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public boolean getNetworkAvailability() {
return Utils.isNetworkAvailable(getActivity());
}
public void onDeliverFlower(Flower flower) {
mFlowerAdapter.addFlower(flower);
}
public void onHideDialog() {
mDialog.dismiss();
}
public class SaveIntoDatabase extends AsyncTask<Flower, Void, Void> {
private final String TAG = SaveIntoDatabase.class.getSimpleName();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Flower... params) {
Flower flower = params[0];
try {
} catch (Exception e) {
Log.d(TAG, e.getMessage());
}
return null;
}
}
}
Lastly the FlowerService class is
public interface FlowerService {
#GET("/routine/first.json")
Call<List<Flower>> getAllFlowers();
}
and FlowerFetchListener Class is
public interface FlowerFetchListener {
void onDeliverAllFlowers(List<Flower> flowers);
void onDeliverFlower(Flower flower);
void onHideDialog();
}
Please Help....and Thanks in advance.
You should not call db and network from activity or fragment. Try to learn MVVM architecture and use ViewModel to store the data from db or network. You may put a lot of effort making your app work but it will still lead to crashes (especially after you introduce fragment and call db and API from there). You will need to handle your data state during configuration changes. Listen to this talk and start writing clean code https://m.youtube.com/watch?v=5qlIPTDE274
The error you get is because you pass wrong parameter into adapter constructor ‘new FlowerAdapter((FlowerAdapter.FlowerClickListener) this)’. If you want to pass a listener to the adapter you need to pass the class which implements the listener: either activity - then pass getActivity(), or fragment ‘this’ - then make fragment implement implements FlowerAdapter.FlowerClickListener.Be aware that it can be null when fragment is not attached to activity, eg configuration change.
How i can pass info from recyclerView to another activity, using Array and MySQL, I was searching the different ways, but i can't do it, but i'm try to do the below way:
private void ReadDataFromDB() {
JsonObjectRequest jreq = new JsonObjectRequest(Request.Method.GET, url,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
int success = response.getInt("success");
if (success == 1) {
JSONArray ja = response.getJSONArray("rutas");
for (int i = 0; i < ja.length(); i++) {
JSONObject jobj = ja.getJSONObject(i);
HashMap<String, String> item = new HashMap<String, String>();
// item.put(ITEM_ID, jobj.getString(ITEM_ID));
item.put(ITEM_RUTA,
jobj.getString(ITEM_RUTA));
item.put(ITEM_VEH,
jobj.getString(ITEM_VEH));
Item_List.add(item);
}
String[] from = {ITEM_RUTA, ITEM_VEH};
int[] to = {R.id.i_ruta, R.id.i_veh};
adapter = new SimpleAdapter(
getApplicationContext(), Item_List,
R.layout.message_list_row, from, to);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setOnClickListener(new onMessageRowClicked() );
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(jreq);
}
I need pass the after info to the follow method
#Override
public void onMessageRowClicked (int i) {
if (mAdapter.getSelectedItemCount() > i) {
enableActionMode(i);
} else {
Message message = messages.get(i);
message.setRead(true);
messages.set(i, message);
mAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Read: hola" + message.getParadas() + message.getVehiculo(), Toast.LENGTH_SHORT).show();
Intent saag_intent = new Intent(ge_MainActivity.this,
ge_Traker_maps.class);
saag_intent.putExtra("ruta", Item_List.get(i));
saag_intent.putExtra("vehiculo", Item_List.get(i));
startActivity(saag_intent);
}
}
The problem or error this is in the follow line show me
cannot resolve symbol onMessageRowClicked
mRecyclerView.setOnClickListener(new onMessageRowClicked() );
RecyclerItemClickListener.java
public class RecyclerItemClickListener implements
RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
public void onLongItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && mListener != null) {
mListener.onLongItemClick(child, recyclerView.getChildAdapterPosition(child));
}
}
});
}
#Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
return true;
}
return false;
}
#Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }
#Override
public void onRequestDisallowInterceptTouchEvent (boolean disallowIntercept){}
}
//use Method
mRecyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(this, file_list ,new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
// write code here for single click
Message message = messages.get(i);
message.setRead(true);
messages.set(i, message);
mAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Read: hola" + message.getParadas() + message.getVehiculo(), Toast.LENGTH_SHORT).show();
Intent saag_intent = new Intent(ge_MainActivity.this,
ge_Traker_maps.class);
saag_intent.putExtra("ruta", Item_List.get(i));
saag_intent.putExtra("vehiculo", Item_List.get(i));
startActivity(saag_intent);
}
#Override public void onLongItemClick(View view, int position) {
// write code here for long click
}
})
);
I get duplicate data items in the recyclerview after the location data has been updated
I have tried some such like way
NotifyDataSetChanged () and setHasStableIds (true)
But still has not succeeded
public class FragmentPetaniTerdekat extends Fragment {
Context context;
View view;
Dialog dialog;
Session session;
RecyclerView recyclerView;
ArrayList<String> nama = new ArrayList<>();
ArrayList<String> jenis = new ArrayList<>();
ArrayList<String> jarak = new ArrayList<>();
ArrayList<String> durasi = new ArrayList<>();
String my_location;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getContext();
dialog = new Dialog(context);
session = new Session(context);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_petani, container, false);
location();
return view;
}
// get adddres name current location
private void location() {
LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// get lat and lng
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
my_location = String.valueOf(lat+","+lng);
session.setSession(my_location);
getApi(session.getSesssion());
}else{
getApi(session.getSesssion());
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
LocationManager mLocationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return ;
}
// check alternative get location
boolean GPS_ENABLE, NETWORK_ENABLE;
GPS_ENABLE = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
NETWORK_ENABLE = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (GPS_ENABLE){
dialog.showDialog("Pesan","memuat data...",true);
Toast.makeText(getActivity(),"GPS state",Toast.LENGTH_LONG).show();
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000 * 5 * 1 , 1, mLocationListener);
}else if(NETWORK_ENABLE){
Toast.makeText(getActivity(),"network state",Toast.LENGTH_LONG).show();
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1,mLocationListener);
}else{
Toast.makeText(getActivity(),"ganok seng kepilih cak",Toast.LENGTH_LONG).show();
showSettingsAlert();
}
}
// show alert setting if gps non aktif
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
getActivity().startActivity(intent);
}
});
// Showing Alert Message
alertDialog.show();
}
public void initRecylerView(View v){
recyclerView = (RecyclerView)v.findViewById(R.id.recylerview_petani_terdekat);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(layoutManager);
RecyclerView.Adapter adapter = new AdapterPetaniTerdekat(context,nama,jarak,durasi);
// adapter.notifyDataSetChanged();
// adapter.setHasStableIds(true);
recyclerView.setAdapter(adapter);
}
public void getApi(final String my_location){
dialog.message("lokasi : "+my_location);
StringRequest request = new StringRequest(Request.Method.POST, URL_PETANI_TERDEKAT, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response != null) {
try {
JSONObject get_respone = new JSONObject(response);
JSONArray get_result = get_respone.getJSONArray("result_petani_terdekat");
for (int i=0; i<get_result.length(); i++){
JSONObject result = get_result.getJSONObject(i);
ModelPetaniTerdekat petaniTerdekat = new ModelPetaniTerdekat();
petaniTerdekat.setNama(result.getString("nama"));
JSONObject kriteria = result.getJSONObject("jarak");
for (int z=0; z<kriteria.length(); z++){
petaniTerdekat.setJarak(kriteria.getString("distance"));
petaniTerdekat.setDurasi(kriteria.getString("duration"));
}
nama.add(petaniTerdekat.getNama());
jarak.add(petaniTerdekat.getJarak());
durasi.add(petaniTerdekat.getDurasi());
dialog.closeDialog();
}
initRecylerView(view);
} catch (JSONException e) {
dialog.message("Error : "+e.toString());
e.printStackTrace();
}
}else{
dialog.message("Error : Tidak ada data !");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
dialog.message("Error : TimeoutError");
} else if (error instanceof AuthFailureError) {
dialog.message("Error : AuthFailureError");
} else if (error instanceof ServerError) {
dialog.message("Error : ServerError");
} else if (error instanceof NetworkError) {
dialog.message("Error : NetworkError");
} else if (error instanceof ParseError) {
error.printStackTrace();
dialog.message("Error : ParseError");
}
dialog.closeDialog();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> map = new HashMap<>();
map.put("lokasi_saya",my_location);
return map;
}
};
AppSingleton.getInstance(context).addToRequestQueue(request);
request.setRetryPolicy(new DefaultRetryPolicy(
60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
}
and this my adapter
public class AdapterPetaniTerdekat extends RecyclerView.Adapter<AdapterPetaniTerdekat.ViewHolderCabe> {
Context context;
ArrayList<String> nama = new ArrayList<>();
ArrayList<String> jarak = new ArrayList<>();
ArrayList<String> durasi = new ArrayList<>();
public AdapterPetaniTerdekat(Context context, ArrayList<String> nama, ArrayList<String> jarak, ArrayList<String> durasi) {
this.context = context;
this.nama = nama;
this.jarak = jarak;
this.durasi = durasi;
}
#Override
public ViewHolderCabe onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rows_petani_terdekat,parent,false);
return new ViewHolderCabe(view);
}
#Override
public void onBindViewHolder(ViewHolderCabe holder, int position) {
holder.tv_nama.setText(nama.get(position));
holder.tv_jarak.setText(jarak.get(position));
holder.tv_durasi.setText(durasi.get(position));
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemCount() {
return nama.size();
}
public class ViewHolderCabe extends RecyclerView.ViewHolder{
TextView tv_nama, tv_jarak, tv_durasi;
public ViewHolderCabe(View itemView) {
super(itemView);
tv_nama = (TextView)itemView.findViewById(R.id.tv_nama_petani);
tv_jarak = (TextView)itemView.findViewById(R.id.tv_jarak);
tv_durasi = (TextView)itemView.findViewById(R.id.tv_durasi);
}
}
}
Add below method in your FragmentPetaniTerdekat to check the duplicate entry:
public boolean isExist(String strNama) {
for (int i = 0; i < nama.size(); i++) {
if (nama.get(i).equals(strNama)) {
return true;
}
}
return false;
}
Use this method inside onResponse(), before adding string into lists(nama, jarak, durasi):
#Override
public void onResponse(String response) {
if (response != null) {
try {
..............
..................
for (int i = 0; i < get_result.length(); i++){
JSONObject result = get_result.getJSONObject(i);
ModelPetaniTerdekat petaniTerdekat = new ModelPetaniTerdekat();
petaniTerdekat.setNama(result.getString("nama"));
JSONObject kriteria = result.getJSONObject("jarak");
for (int z=0; z<kriteria.length(); z++){
petaniTerdekat.setJarak(kriteria.getString("distance"));
petaniTerdekat.setDurasi(kriteria.getString("duration"));
}
boolean isExist = isExist(petaniTerdekat.getNama());
if (!isExist) { // Not exist, Add now
nama.add(petaniTerdekat.getNama());
jarak.add(petaniTerdekat.getJarak());
durasi.add(petaniTerdekat.getDurasi());
}
dialog.closeDialog();
}
initRecylerView(view);
} catch (JSONException e) {
dialog.message("Error : "+e.toString());
e.printStackTrace();
}
}else{
dialog.message("Error : Tidak ada data !");
}
}
Hope this will help~