How can I updating only new json data in fragment with swipeRefreshLayout - java

In this fragment I send a jsonRequest with volley to the server . and I'm setting the swipeRefreshLayout to this fragment , I want to load only new json data but when I use sendJsonRequest() method on the onRefresh() all of the json data is enabled to the recyclerView:
This is my fragment code:
package ghandak.ghandshekan.com.ghandak.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
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 android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import ghandak.ghandshekan.com.ghandak.R;
import ghandak.ghandshekan.com.ghandak.adapters.PostRecyclerAdapter;
import ghandak.ghandshekan.com.ghandak.app.AppController;
import ghandak.ghandshekan.com.ghandak.models.PostData;
/**
* Created by imajid on 12/19/2015.
*/
public class TabFragment3 extends Fragment implements OnRefreshListener{
private RecyclerView allContentRecyclerView;
private String url = "http://kakdo.herokuapp.com/api/news/?format=json";
private List<PostData> postDataList = new ArrayList<PostData>();
private SwipeRefreshLayout swipeRefreshLayout;
//====================================================================================== onCreateView
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_fragment_3 , container , false);
allContentRecyclerView = (RecyclerView)view.findViewById(R.id.xmlRecyclerViewtabFragment3);
allContentRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
swipeRefreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.xml_swipe_refresh_layout_tab_fragment_3);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
//swipeRefreshLayout.setColorSchemeColors();
return view;
}
//====================================================================================== onCreate
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sendJsonRequest();
}
//====================================================================================== sendjsonRequest
private void sendJsonRequest() {
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
parseJsonResponse(response);
//==========setting adapter to the recyclerview <==
allContentRecyclerView.setAdapter(new PostRecyclerAdapter(getActivity() ,postDataList));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(request);
}
//====================================================================================== parsjsonResponse()
private void parseJsonResponse(JSONArray response) {
if(response == null){
Toast.makeText(getActivity(), "ریسپانس خالی هستش", Toast.LENGTH_SHORT).show();
return;
}else {
Log.d("parsejsonresponse", "response khali nist");
for (int i = 0 ; i < response.length() ; i++ ){
try {
//Toast.makeText(getActivity(), "ریسپانس میگیرم ", Toast.LENGTH_SHORT).show();
JSONObject currentPost = response.getJSONObject(i);
//Log.d("currentPost", "currentPost ro gereftam");
PostData postData = new PostData();
postData.setTitle(currentPost.getString("title"));
//Toast.makeText(getActivity() , currentPost.getString("title") , Toast.LENGTH_SHORT).show();
postData.setCreate(currentPost.getString("create"));
postDataList.add(postData);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
#Override
public void onRefresh() {
sendJsonRequest();
swipeRefreshLayout.setRefreshing(false);
}
}
Now my question is in the OnRefresh method , what can I write to load only new json data, not all of the exists json.

Add this line in your code
postDataList.clear(); in your code given in bellow.
Updated:
#Override
public void onResponse(JSONArray response) {
if(response == null )
return;
postDataList.clear();
parseJsonResponse(response);
//==========setting adapter to the recyclerview <==
allContentRecyclerView.setAdapter(new PostRecyclerAdapter(getActivity() ,postDataList));
}
Note: when ever you create any kind of list max create adapter instance once in your code, After change list data you just need to call 'adapterInstance.notifyDataSetChange();'
This is the best practice instead of creating list every time it's better to refresh list items, Further info check here

add this code ,
private SwipeRefreshLayout mSwipeRefreshLayout;
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
}
}, SPLASH_DISPLAY_LENGTH);
}
});
when you want to refresh it call,
mSwipeRefreshLayout.setRefreshing(true);

swipeContainer = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeContainer);
swipeContainer.setOnRefreshListener(new OnRefreshListener()
{
#Override
public void onRefresh()
{
//clear your old data
callForData();
//swipeContainer.setRefreshing(false); use this while get data and set in you ui
}
});
// Configure the refreshing colors
swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light);

Related

Unable to refresh the updated data after clicking on search button (Fetching data via API)

I am not able to update the values when i click on the search button, The data is fetched but the old fetched data is not getting discards, the fetched data is overlapping over each other
SearchFragment.java
package com.example.recipeappandroid.Fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.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.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.recipeappandroid.Adapter.RecipeAdapter;
import com.example.recipeappandroid.Model.Recipe;
import com.example.recipeappandroid.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class SearchFragment extends Fragment {
Button click;
//public static TextView fetchedText;
ImageView searching_logo;
TextView searching_text;
SearchView searchbar;
String query="";
RecyclerView recyclerView;
public static ArrayList<Recipe> recipeList;
public static RecipeAdapter recipeAdapter;
private RequestQueue mRequestQueue;
private String Api_id= "3f335994";
private String Api_key = "8e99e327d1f2130dc6ab3422e26a95e8";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search, container, false);
click = (Button) view.findViewById(R.id.button1);
//fetchedText = (TextView) view.findViewById(R.id.fetcheddata);
searchbar = (SearchView) view.findViewById(R.id.searchbar);
searching_logo = view.findViewById(R.id.searching_logo);
searching_text = view.findViewById(R.id.searching_text);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
//recipeAdapter = new RecipeAdapter();
recipeList = new ArrayList<>();
//getData();
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
query = searchbar.getQuery().toString();
String url = "https://api.edamam.com/search?q=" + query + "&app_id=" + Api_id + "&app_key=" + Api_key;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray hits = response.getJSONArray("hits");
for (int i =0;i<hits.length();i++) {
JSONObject jsonObject = hits.getJSONObject(i);
JSONObject recipe = jsonObject.getJSONObject("recipe");
String recipe_img = recipe.getString("image");
String recipe_title = recipe.getString("label");
String recipe_data = recipe.getString("source");
recipeList.add(new Recipe(recipe_img,recipe_title,recipe_data));
}
recipeAdapter = new RecipeAdapter(getContext(),recipeList);
recyclerView.setAdapter(recipeAdapter);
recipeAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue = Volley.newRequestQueue(getContext());
mRequestQueue.add(jsonObjectRequest);
/*JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
JSONObject recipes = jsonObject.getJSONObject("recipe");
//Recipe recipe = new Recipe();
String recipe_img = recipes.getString("image");
String recipe_title = recipes.getString("label");
String recipe_data = recipes.getString("source");
recipeList.add(new Recipe(recipe_img,recipe_title,recipe_data));
Log.d("data",recipe_title);
}
//recipeAdapter = new RecipeAdapter(getContext(), recipeList);
//recyclerView.setAdapter(recipeAdapter);
recipeAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(SearchFragment.this,"Error Occured",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});*/
/*jsonArrayRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 3000;
}
#Override
public int getCurrentRetryCount() {
return 3000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
});*/
/* Log.d("QUEEEERRRYYYY",query);
ApiCall process = new ApiCall(searching_logo,searching_text);
process.execute(query);*/
}
});
return view;
}
}
I want to get rid of the old data after the new data is fetched and don't want to display it after the new one is called
looks like you are only adding items to your ArrayList<Recipe> recipeList;, so they may duplicate
maybe try to recipeList.clear(); it in first line of onResponse method
also notifyDataSetChanged isn't needed, setAdapter does it itself (and a lot more in fact)

No view found for id for fragment when replacing from Adapter

I'm trying to replace my current fragment with another one. I'm doing this from the Adapter, since I wanna do it when clicking on a Card. This is my code into the adapter:
itemView.setOnClickListener(v -> {
if (mMovieCategory.getImageUrl() != null) {
try {
//TODO
FragmentTransaction ft = ((AppCompatActivity) v.getContext()).getSupportFragmentManager()
.beginTransaction();
ft.replace(R.id.movie_container, new Fragment_Movie());
ft.addToBackStack(null);
ft.commit();
} catch (Exception e) {
Log.e(TAG, "onClick: Image url is not correct");
}
}
});
In the replace function I used the id assigned to the fragment I want to invoke. This is the XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/movie_container"
tools:context=".MainActivity" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_row_selector"/>
</RelativeLayout>
This is the fragment I want to invoke:
package com.lab.movietime;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import static com.android.volley.VolleyLog.TAG;
public class Fragment_Movie extends Fragment {
private static final String url = "https://api.androidhive.info/json/movies.json";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
public Fragment_Movie() {
// Required empty public constructor
}
public static Fragment_Movie newInstance() {
Fragment_Movie fragment = new Fragment_Movie();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_movie, container, false);
listView = (ListView) view.findViewById(R.id.list);
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getContext());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating"))
.doubleValue());
movie.setYear(obj.getInt("releaseYear"));
// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
return view;
}
}
The error I get is:
No view found for id 0x7f0900ab (com.lab.movietime:id/movie_container) for fragment Fragment_Movie{1f8531a}
Why? Is the id: container_movie incorrect?
Assuming that movie_container is within the Fragment: You need to pass the ID of the container view in the Activity's layout, not the ID of the Fragment's view.
This will be the ID of the View containing the Fragment, as opposed to the View contained within the Fragment.

I keep getting com.android.volley.RequestQueue.add on a null object reference error

I need to display a a list of products from a JSON file, but I keep getting this error:
https://i.imgur.com/WEu4DzV.png
I tried moving everything in my code (so maybe I messed it up a little) and I can't get it to work. I'm a beginner, so errors like this are very hard to fix for me.
This is the fragment that produces the error:
package com.example.app;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
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.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class ListFragment extends Fragment {
private RecyclerView mRecyclerView;
private ListAdapter mListAdapter;
private ArrayList<Item> mList;
private RequestQueue mRequestQueue;
Context context;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView = view.findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mRecyclerView.setAdapter(mListAdapter);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
parseJSON();
super.onActivityCreated(savedInstanceState);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mList = new ArrayList<>();
mListAdapter = new ListAdapter(context, mList);
}
private void parseJSON() {
String url = "http://my_ip_adress/sestavsisvujsvetweb/api/seznammagnetek";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
int number = 0;
try {
number = response.getInt("monumentid1");
} catch (JSONException e) {
e.printStackTrace();
}
String name = null;
try {
name = response.getString("name1");
} catch (JSONException e) {
e.printStackTrace();
}
String region = null;
try {
region = response.getString("region1");
} catch (JSONException e) {
e.printStackTrace();
}
mRequestQueue = Volley.newRequestQueue(context);
mList.add(new Item(number, name, region));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request); //this causes the problem, why? :(
}
}
The problem occurs because you are trying to add request into the requestQueue before knowing that it successfully retrieved your information. First, check if JsonObjectRequest has a onSuccess function, if not, then you need to add to requestQueue inside of the onResponse. Otherwise, android is synchronous so it will execute your line before actually retrieving the Json.
So the quick fix will be this:
if(request != null) {
mRequestQueue.add(request);
}
This will make sure to not add if its null. Add this in your onCreate:
mRequestQueue = Volley.newRequestQueue(context);

How to pass data from one activity to another activity

I'm creating an event app which contains a list of events in recyclerview.
The events recyclerview consists of the event name, image, date and time, heart image (example: heart shape like button on Instagram) which will change its color when the user clicks on the 'interested' button.
After clicking on any event its description appears and there are two buttons: 'interested' and 'going'. If the user clicks on 'interested' that heart color in the recyclerview will become yellow. The event will also get saved in another list where it will remain until that event is removed from the saved list.
So far I've completed saving that event in the saved list on clicking the 'interested' button. But I don't know how to change the heart color simultaneously and how to make it remain until the event is deleted from saved list.
First Activity calling recyclerview adapter
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class EventActivity extends AppCompatActivity {
//this is the JSON Data URL
//make sure you are using the correct ip else it will not work
private static final String URL_PRODUCTS = "https://www.test.magicalballoons.co.in/priyanka/event.php?";
//a list to store all the products
List<Product> productList;
//the recyclerview
RecyclerView recyclerView;
ImageView homemenu;
//SwipeRefreshLayout swiper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
getSupportActionBar().hide();
homemenu = findViewById(R.id.homemenu);
// swiper = findViewById(R.id.swiper);
//getting the recyclerview from xml
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//initializing the productlist
productList = new ArrayList<>();
homemenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(EventActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
});
//this method will fetch and parse json
//to display it in recyclerview
loadProducts();
}
private void loadProducts() {
/*
* Creating a String Request
* The request type is GET defined by first parameter
* The URL is defined in the second parameter
* Then we have a Response Listener and a Error Listener
* In response listener we will get the JSON response as a String
* */
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject product = array.getJSONObject(i);
//adding the product to product list
productList.add(new Product(
product.getString("id"),
product.getString("name"),
product.getString("date"),
product.getString("location"),
product.getString("image"),
product.getString("details")
));
}
//creating adapter object and setting it to recyclerview
RecyclerViewAdapter adapter = new RecyclerViewAdapter(EventActivity.this, productList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(EventActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
public void onBackPressed() {
Intent intent = new Intent(EventActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
Recyclerview Adapter
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
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.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
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.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.BreakIterator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import static com.example.priyankaregistration.URLs.URL_EVENT;
/**
* Created by Aws on 11/03/2018.
*/
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private RequestQueue requestQueue;
private JsonArrayRequest request;
private Context mContext;
private List<Product> mData;
RequestOptions option;
TextView total;
ImageView colorheart,heart;
// Dialog myDailog;
private Dialog myDialog;
public RecyclerViewAdapter(Context mContext, List<Product> mData) {
this.mContext = mContext;
this.mData = mData;
//this.swiper = swiper;
option=new RequestOptions().fitCenter().placeholder(R.drawable.background).error(R.drawable.background);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater inflater = LayoutInflater.from(mContext);
view = inflater.inflate(R.layout.fragment_conferences, parent, false);
final MyViewHolder viewHolder = new MyViewHolder(view);
myDialog = new Dialog(mContext);
colorheart = (ImageView) view.findViewById(R.id.colorheart);
heart = (ImageView) view.findViewById(R.id.heart);
total = (TextView) view.findViewById(R.id.count);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_COUNT,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
total.setText(jsonObject.getString("countid"));
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("eventid", mData.get(viewHolder.getAdapterPosition()).getId());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
requestQueue.add(stringRequest);
viewHolder.view_container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, Description.class);
intent.putExtra("eventname",mData.get(viewHolder.getAdapterPosition()).getName());
intent.putExtra("eventid",mData.get(viewHolder.getAdapterPosition()).getId());
intent.putExtra("eventdate",mData.get(viewHolder.getAdapterPosition()).getDate());
intent.putExtra("eventloc",mData.get(viewHolder.getAdapterPosition()).getLocation());
intent.putExtra("eventimg",mData.get(viewHolder.getAdapterPosition()).getImage());
intent.putExtra("details",mData.get(viewHolder.getAdapterPosition()).getDetails());
mContext.startActivity(intent);
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.textViewName.setText(mData.get(position).getName());
holder.textViewDate.setText("Date : " + mData.get(position).getDate());
holder.textViewLocation.setText("Time : " + mData.get(position).getLocation());
Glide.with(mContext).load(mData.get(position).getImage()).apply(option).into(holder.img_thumbnail);
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView textViewName,textViewDate, textViewLocation,total;
ImageView img_thumbnail;
//LinearLayout view_container;
CardView view_container;
public MyViewHolder(View itemView) {
super(itemView);
view_container = itemView.findViewById(R.id.container);
textViewName = itemView.findViewById(R.id.textViewName);
textViewDate = itemView.findViewById(R.id.textViewDate);
textViewLocation = itemView.findViewById(R.id.textViewLocation);
total = itemView.findViewById(R.id.count);
img_thumbnail=itemView.findViewById(R.id.imageView);
}
}
}
This is second activity
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.support.design.widget.Snackbar;
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.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class Description extends AppCompatActivity {
TextView textViewName,textViewDate, textViewLocation, details;
ImageView evimg,going,interest;
RequestOptions option;
ImageView homemenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
getSupportActionBar().hide();
option=new RequestOptions().fitCenter().placeholder(R.drawable.background).error(R.drawable.background);
textViewName = findViewById(R.id.textViewName);
evimg = findViewById(R.id.evimg);
details = findViewById(R.id.details);
going = findViewById(R.id.going);
interest = findViewById(R.id.interest);
homemenu = findViewById(R.id.homemenu);
textViewName.setText(getIntent().getStringExtra("eventname"));
//textViewDate.setText(getIntent().getStringExtra("eventdate"));
//textViewLocation.setText(getIntent().getStringExtra("eventloc"));
details.setText(getIntent().getStringExtra("details"));
details.setMovementMethod(new ScrollingMovementMethod());
Glide.with(this).load(getIntent().getStringExtra("eventimg")).apply(option).into(evimg);
going.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URLs.URL_EVENT+"?userid=" + SharedPrefManager.getInstance(getApplicationContext()).getUserId() + "&eventid="+ getIntent().getStringExtra("eventid"),
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String message = jsonObject.getString("name");
Intent intent = new Intent(Description.this,Ticket.class);
intent.putExtra("code",message);
intent.putExtra("eventimg",getIntent().getStringExtra("eventimg"));
intent.putExtra("activity","NO");
// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
jsonrequest();
startActivity(intent);
finish();
//Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
//params.put("userid",SharedPrefManager.getInstance(getApplicationContext()).getUserId());
//params.put("eventid",getIntent().getStringExtra("eventid"));
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
});
interest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_EVENTSAVED ,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
//String message = jsonObject.getString("name")
Toast.makeText(getApplicationContext(),jsonObject.getString("message"),Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("userid",SharedPrefManager.getInstance(getApplicationContext()).getUserId());
params.put("eventid",getIntent().getStringExtra("eventid"));
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
});
homemenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Description.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
});
}
private void jsonrequest() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_EVENTDELETED,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
Toast.makeText(getApplicationContext(),jsonObject.getString("Event removed from saved list"),Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
//progressDialog.dismiss();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("userid",SharedPrefManager.getInstance(getApplicationContext()).getUserId());
params.put("eventid",getIntent().getStringExtra("eventid"));
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}
I'm having heart image in my recyclerview . And when i click on interest buttton in Description activity the heart image in recyclerview get change.
Assuming you are saving the events in some model class, what you can do is when calling the onBindViewHolder method of your adapter, check if the event is marked as save. If it is, then you either need to change the heart image to another heart image which is yellow, or you can apply a tint on the heart image to make it yellow.
You can change drawable by using this code
heartImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.yellow_heart));
You can apply tint by using this code
heartImageView.setColorFilter(Color.argb(255, 255, 255, 0))
EDIT (Based on comment)
If the heart is in the first activity and the interested button is in the second activity what you need to do is to save the state of the event when you click on the interested button. Once you go back to the the first activity, you can check the state of the event and then update the image by using any of the above two methods.
EDIT 2 (Based on new code shared)
After you get the response from your Volley call, you should save the event id somewhere to keep track of which events you are interested in (this can be in either a model class or some global list). When you go back to your first activity (which contains the recyclerview), you need to check each event id with the stored event id list that you have and change the heart for each event that matches.
You can do this with the help for startActivityforresult
In Activity1, start Activity2 as:
Intent i = new Intent(this, Activity2.class);
startActivityForResult(i, 1);
In Activity2, use setResult for sending data back:
Intent intent = new Intent();
intent.putExtra("updatedArraylist", "arraylist")
setResult(RESULT_OK, intent);
finish();
And in Activity1, receive data with onActivityResult:
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
String strArrayList =
data.getStringExtra("updatedArraylist");
Gson gson = new Gson();
Type youListType = new TypeToken<List<Model>>() {
}.getType();
List<Model> yourTypeList = gson.fromJson(strArrayList,
yourListType);
ArrayList finalArraylist = new ArrayList<>(yourTypeList);
yourArraylist.addAll(finalArraylist);
youtAdapter.notifyDataSetChanged();
}
}
}
You can apply color onclick event to heart button like following code :
your_image_id.setBackgroundColor(getResources().getColor(R.color.yellow));
In first activity
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivityForResult(intent, 100);
From second activity, you have to execute the below code before the activity getting destroyed by finish() or back press (For this you can override onBackPressed of second activity and remove the super class call and call the below method).
private void exitWithResult(){
Intent returnIntent = new Intent();
returnIntent.putExtra("result", "Id of selected item");
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
Again in first activity you have to handle the result inside onActivityResult method.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == 100) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
Log.e("DATA", "" + result);
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
Log.e("DATA", "No result");
}
}
}
Update
You can use an interface as callback from adapter to activity. startActivityForResult canbe called inside the callback method of interface. You have to pass callback interface to adapter through adapter constructor along with data set.
declare this interface inside adapter
public interface AdapterCallback{
void onAdapterSelected(int pos);
}
And in first activity implement the interface like this.
MyAdapter.AdapterCallback callback = new MyAdapter.AdapterCallback() {
#Override
public void onAdapterSelected(int pos) {
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
startActivityForResult(intent, 100);
}
};
Then set adapter like this.
RecyclerView rv = findViewById(R.id.rv_list);
rv.setHasFixedSize(true);
rv.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
MyAdapter adapter = new MyAdapter(callback); //This is the only change
rv.setAdapter(adapter);
Changes in adapter below. (You should pass list data along with call back as you already does)
private AdapterCallback callback;
public MyAdapter(AdapterCallback callback) {
this.callback = callback;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, final int i) {
viewHolder.mBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callback.onAdapterSelected(i);
}
});
}
Interface also come inside adapter. I am not repeating it here as i already mentioned at first

BaseAdapter crashes on notifyDataSetChanged update?

When trying to update my array adapter upon a network request, the program crashes with Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference, I have seen other posts with the same time but every method I try seems to just result in an error, the same crashing bug most likely.
Of course the title says, I am using notifyDataSetChanged() to update my lists.
Here is my code that I am using
import android.app.DownloadManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MyActivity";
public ArrayList<String> aContacts = new ArrayList<String>();
public ListView contacts;
public CustomAdapter customAdapter;
// User Setup Defaults
String server = "https://xxxxxxxx";
String suser = "xxxxxx";
String spass = "xxxxxx";
String sreq;
public void getContacts() {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url = server+"/xxxxxx/?username="+suser+"&password="+spass+"&getcontacts=yes";
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Log.v(TAG, "I recieved: " + response);
try {
JSONArray parseContacts = new JSONArray(response);
for (int x = 0; x < parseContacts.length(); x++) {
JSONArray array = (JSONArray) parseContacts.get(x);
for (int j = 0; j < array.length(); j++){
// print: array.get(j).toString();
}
aContacts.add(array.get(0).toString());
customAdapter.notifyDataSetChanged(); // ERROR IS HERE
}
}catch(JSONException e) {
Log.v(TAG, "Error: "+e);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v(TAG, "Oops, an error occurred");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView contacts = (ListView)findViewById(R.id.contacts);
getContacts();
CustomAdapter customAdapter = new CustomAdapter();
contacts.setAdapter(customAdapter);
contacts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object o = contacts.getItemAtPosition(position);
Toast.makeText(getBaseContext(),aContacts.get(position),Toast.LENGTH_SHORT).show();
}
});
}
class CustomAdapter extends BaseAdapter {
#Override
public int getCount() {
return aContacts.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.row,null);
TextView username = (TextView) convertView.findViewById(R.id.username);
username.setText(aContacts.get(position));
return convertView;
}
}
}
Im trying to parse JSON data and that works fine, and I add the results to an array and it would appear something like this {"one", "two", "three"}, but it doesnt seem to have to do with that and just crashes with that error on runtime. I have struggled at this forever now, if someone could give me some code that is the working version would be really nice but probably wouldnt happen, so just reference the issue please, or whatever you can do to help, thanks!

Categories