How putExtra in RecyclerView with arraylist from JSON - java

I'm try to go another activity, from RecyclerView with determined position, and i need putExtra for load info in the destin activity.
I'm based in this example, but i have problem when I call JSON file.
The Sample code is this:
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("infoRecy");
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);
} // for loop ends
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);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new ListitemClickListener());
} // if ends
} catch (JSONException e) {…
I have problema in this line, I not know like fix
listview.setOnItemClickListener(new ListitemClickListener());
Show me this error:
Cannot resol symbol 'ListitemClickListener'
since my click method is different
#Override
public void onMessageRowClicked (int i) {
// verify whether action mode is enabled or not
// if enabled, change the row state to activated
if (mAdapter.getSelectedItemCount() > i) {
enableActionMode(i);
} else {
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);
}
}
how could putExtra in my recyclerView, with this code for sample that i use

try this
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// do on item click
}
});
it will fix below issue
Cannot resol symbol 'ListitemClickListener'

Related

RecyclerView not loading

I have created a Recycler view that is supposed to be created when the activity is created. Currently, when I click a button on my MainActivity, an intent launches the ListActivity which has my recyclerview but it doesn't load. I have used toast message to confirm that each method is getting called, and that I am getting the correct data from the API. If I reset the activity using the restart activity option in Android Studio the Recycler shows up and functions correctly. I don't know what I'm doing wrong.
Here is my ListActivity:
private RecyclerView myrecyclerview;
private RecyclerView.Adapter myadapter;
private RecyclerView.LayoutManager mylayoutmanager;
static RequestQueue listqueue;
static final private String url = "https://swapi.dev/api/people/";
static ArrayList<RecyclerItem> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
getSupportActionBar().hide();
listqueue = Volley.newRequestQueue(this);
myrecyclerview = findViewById(R.id.characterlist);
myadapter = new MyAdapter(list, this);
myrecyclerview.setAdapter(myadapter);
myrecyclerview.setHasFixedSize(true);
mylayoutmanager = new LinearLayoutManager(getApplicationContext());
myrecyclerview.setLayoutManager(mylayoutmanager);
parseJsonData();
}
public void parseJsonData(){
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
try {
JSONArray jsonarray = response.getJSONArray("results");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String height = jsonobject.getString("height");
String mass = jsonobject.getString("mass");
String eyecolor = jsonobject.getString("eye_color");
String birthyear = jsonobject.getString("birth_year");
//list.add(new RecyclerItem("darth vader", "200", "128", "1950", "red"));
list.add(new RecyclerItem(name, "Height: " + height, "Mass: " + mass, "Birth Year: " + birthyear, eyecolor));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
listqueue.add(request);
}
#Override
public void onCharacterClick(int position) {
String color = list.get(position).getEyecolor();
Toast.makeText(getApplicationContext(), color, Toast.LENGTH_SHORT).show();
}
} ```
Like I mentioned, once I reload the activity, it works correctly. But I want the recycler view to show when I navigate to the activity.
The problem is that the first time that the activity is create, list is empty and parseJsonData() is running on the background filling that list.
Once you reload the activiy, the list and adapter are filled therefore when you call
myadapter = new MyAdapter(list, this);
myrecyclerview.setAdapter(myadapter);
myrecyclerview.setHasFixedSize(true);
mylayoutmanager = new LinearLayoutManager(getApplicationContext());
myrecyclerview.setLayoutManager(mylayoutmanager);
the recycler view is show. Try to do this on your parseJsonData(); after the loop ends, then create the adapter and show the rv
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
....
}
myadapter = new MyAdapter(list, this);
....
myrecyclerview.setLayoutManager(mylayoutmanager);
I hope it help for u
Creat a List
private List< TipsList > tipsLists = new ArrayList<>();
SET UP RECYCLERVIEW LIKE THIS
RecyclerView tipsRv = findViewById(R.id.tips_rv);
TipsAdapter adapter = new TipsAdapter(tipsLists, this);
tipsRv.setAdapter(adapter);
tipsRv.setHasFixedSize(true);
tipsRv.setLayoutManager(new LinearLayoutManager(this));
getDATA
public void getWallis() {
String myJSONStr = method.loadJSON();
try {
JSONObject ROOT_OBJ = new JSONObject(myJSONStr);
JSONArray MAIN_ARRAY = ROOT_OBJ.getJSONArray("ff_api");
JSONObject TIPS_OBJ = MAIN_ARRAY.getJSONObject(3);
JSONArray TIPS_ARRAY = TIPS_OBJ.getJSONArray("Tips");
for (int i = 0; i < TIPS_ARRAY.length(); i++) {
TipsList tipsList = new TipsList();
JSONObject jsonObject = TIPS_ARRAY.getJSONObject(i);
tipsList.setId(jsonObject.getInt("id"));
tipsList.setTipsTitle(jsonObject.getString("tipsTitle"));
tipsList.setTipsDec(jsonObject.getString("tipsDec"));
tipsLists.add(tipsList);
}
} catch (JSONException e) {
e.printStackTrace();
}
}

How to send array of Hashmap from one activity to another activity in android

I have a list view in Main activity, I have fill some values in it by using Array Adapter
String[] arr = new String[]{"Android ListView Item 1", "Android ListView Item 2",
"Simple List View In Android", "List View onClick Event","Android List View OnItemClickListener",
"Open New Activity When ListView item Clicked", "List View onClick Source Code", "List View Array Adapter Item Click",
};
Now I want to set onclickListener to each item of the list. I am requesting an api which gives me jsonresponse and I want to iterate over jsonresponse and send required data to another activity when click item of the list.
I tried with following:
ArrayAdapter<String> arrayadapter = new ArrayAdapter<String>(this,
R.layout.activity_main2, R.id.textview, arr);
listview.setAdapter(arrayadapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String textToPass = "hello";
if (position == 0) {
Bundle passData = new Bundle();
passData.putString("data",textToPass);
Intent myIntent = new Intent(view.getContext(), Main2Activity.class);
myIntent.putExtras(passData);
startActivity(myIntent);
}
}
});
}
private String jsonParse(){
String url = "//testing/api.php"; //get json response locally
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray jsonArray = null;
try {
jsonArray = response.getJSONArray("Item");
for(int i=0; i<=jsonArray.length();i++){
HashMap<String,String> dict = new HashMap<String,String>();
JSONObject tv = jsonArray.getJSONObject(i);
String sid;
dict.put("cid", tv.getString("sid") );
// String cid = tv.getString("sid");
String categoryName =tv.getString("category_name");
String baseUrl = "//testing/";
String imageUrl = baseUrl + tv.getString("category_image");
//textView.append(cid + "," + categoryName + "," + imageUrl + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
assert jsonArray != null;
Log.d("Main",jsonArray.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(error.getMessage(), "utf-8");
}
});
requestQueue.add(jsonObjectRequest);
Please help
If I understood properly then I think you want to send HashMap dic to another activity. HashMap are serializable this means you can easily pass it in intent, moreover both key and value are string which are also serializable
intent.putExtra("dic.key", dic);
And in your next activity retrieve it with typecasting.. simple
HashMap<String, String> hashMap = (HashMap<String, String>) intent.getSerializableExtra("hashMap");

arraylist seems to be empty out side the function

Hi i have an array list which is defined in the beginning of the class and i try too put objects inside it so that i can use it for a custom arrayAdapter for a listview but when i want to use it seems to be empty outside the response Listener i tested it with two Toasts forst one runs with no problem second one throws IndexOutOfBoundsException here's my code i have put comments beside those two Toasts they are in getUserGamesInfo function (sry for the mess that has happened to the code when i pasted it here that happened):
public class account_games_info extends Fragment {
HashMap<String, String> info = new HashMap<>();
String Playerscores, Rivalscore;
String[] array = null;
ListView listView;
ArrayList<gameHistory_object> scoreList=new ArrayList<gameHistory_object>;//*************
gameHistory_object gameHistory_object;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
get_user_games_ids();//a functio that calls getUserGamesInfo but i didnt bring it here
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View games_info = inflater.inflate(R.layout.fragment_account_games_info, container, false);
listView = (ListView) games_info.findViewById(R.id.listView);
return games_info;
}
private void getUserGamesInfo(String gameID) {
final String MY_PREFS_NAME = "username and password";
SharedPreferences prefs = getActivity().getSharedPreferences(MY_PREFS_NAME,
MODE_PRIVATE);
final String id = prefs.getString("userID", null);
info.put("action", "sendGameInformation");
info.put("userID", id);
info.put("gameID", gameID);
JSONObject jsonObject = new JSONObject(info);
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
gameHistory_object = new gameHistory_object();
if (id.equals(response.getString("playerOneID"))) {
Playerscores = response.getString("playerOneTotalScore");
Rivalscore = response.getString("playerTwoTotalScore");
gameHistory_object.setRivalUsername(response.getString("playerTwoUsername"));
gameHistory_object.setPlayerScore(Playerscores);
gameHistory_object.setRivalScore(Rivalscore);
} else {
Playerscores = response.getString("playerTwoTotalScore");
Rivalscore = response.getString("playerTwoTotalScore");
gameHistory_object.setRivalUsername(response.getString("playerOneUsername"));
gameHistory_object.setPlayerScore(Playerscores);
gameHistory_object.setRivalScore(Rivalscore);
}
scoreList.add(gameHistory_object);
//first toast which runs with no problem
Toast.makeText(getActivity(),"inside $$$"+scoreList.get(0).getRivalUsername(),Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
if (Playerscores.equals("")) {
playerScore_view.setText("");
} else {
playerScore_view.setText(Playerscores);
rivalScore_view.setText(Rivalscore);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//second toast with outofboundexecption
Toast.makeText(getActivity(),"outside
$$$"+scoreList.get(0).getRivalUsername(),Toast.LENGTH_SHORT).show();
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
You never initialize your scoreList :
ArrayList<gameHistory_object> scoreList;
should be
ArrayList<gameHistory_object> scoreList = new ArrayList();
You access the 0th item of your scoreList before it's been put there. The JsonObjectRequest you start is asynchronous. Your code will start the asynchronous request, then continue to the part where you try to make your toast, but the request has not yet ended (the onResponse part), thus your list is empty.
Your arraylist is not initialized any where in your code hence the IndexOutOfBoundsException.
Do this in your variable declaration:
ArrayList<gameHistory_object> scoreList = new ArrayList <>();

RecycleView pagination not adding new item at the end?

I am getting data from the server through web service and showing in recycle view.Every request I am getting 5 item from the server. I debug my code and checked that when I scroll to end of recycleview then new data is getting from the server but it's not adding in the end of recycleview. How can I solve that?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timeline);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
listView = (RecyclerView) findViewById(R.id.listview);
listView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
listView.setLayoutManager(layoutManager);
//Adding an scroll change listener to recyclerview
listView.setOnScrollChangeListener(this);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
cd = new ConnectionDetector(this);
isInternetPresent = cd.isConnectingToInternet();
db = new SQLiteHandler(this);
// session manager
session = new SessionManager(this);
/*pref = getApplicationContext().getSharedPreferences("MayahudiPref", 0);
editor = pref.edit();*/
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
id = user.get("id");
token = user.get("token");
getData();
adapter = new TimeLineListAdapter(timeLineItems, this);
listView.setAdapter(adapter);
}
public void getTimeLineData(final String token, final String page) {
timeLineItems = new ArrayList<>();
String tag_string_req = "req_register";
// making fresh volley request and getting json
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.timeline, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
String message = jObj.getString("message");
if(error){
totalPages = jObj.getInt("totalPages");
pageCount = jObj.getInt("page");
int limit = jObj.getInt("limit");
parseJsonFeed(response);
}
}catch (Exception e){
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("page", page);
params.put("limit", "5");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void parseJsonFeed(String response) {
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray feedArray = jsonObj.getJSONArray("data");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
TimeLineItem item = new TimeLineItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
item.setLname(feedObj.getString("lname"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("story_text"));
item.setProfilePic(feedObj.getString("profile_pic"));
item.setTimeStamp(feedObj.getString("time_stamp"));
item.setIsLike(feedObj.getInt("is_like"));
item.setTotalLikes(feedObj.getString("total_likes"));
item.setTotalComment(feedObj.getString("total_comments"));
/*// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);*/
timeLineItems.add(item);
}
// notify data changes to list adapater
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
//This method will get data from the web API
private void getData() {
//Adding the method to the queue by calling the method getDataFromServer
getTimeLineData(token , String.valueOf(requestCount));
//Incrementing the request counter
requestCount++;
}
//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}
#Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//Ifscrolled at last then
if (isLastItemDisplaying(listView)) {
//Calling the method getdata again
getData();
}
}
I think you create a new items list each time you call getTimeLineData():
timeLineItems = new ArrayList<>();
First check if you already have a list:
if (timeLineItems == null) {
timeLineItems = new ArrayList<>();
}
RecylerView article_list;
article_list.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
visibleitemcount = linearLayoutManager.getChildCount();
total_itemcount = linearLayoutManager.getItemCount();
pastVisiblecount = linearLayoutManager.findFirstVisibleItemPosition();
Log.d(TAG, "Total : " + total_itemcount + "Visible : " + visibleitemcount + "Past : " + pastVisiblecount);
if (loading) {
if (visibleitemcount + pastVisiblecount >= total_itemcount) {
loading = false;
getHealthyLivingfromUrl(5, 0);
}
}
}
});
private void getHealthyLivingfromUrl(int limit, int offset) {
//get the data code
article_list.setAdapter(articleAdapter);
if (total_itemcount!=0 && total_itemcount > visibleitemcount) {
linearLayoutManager.setSmoothScrollbarEnabled(true);
linearLayoutManager.scrollToPosition(total_itemcount-visibleitemcount);
}
loading = true;
}
Why are you using POST method to obtain data ? Everytime you obtaining data you are creating new array, onCreate you assign to adapter an array. Then you create one, but no assign. I think you should create in adapter class, addItems(List items) method and every time you are getting data you use this method (inside this method you can notifi data has changed). That's all.

Accessing Arraylist Items

I want to access the items from bookList in the onItemClickListener. I want to access specific books and get specific items from them how to do this?
The code is :
// Creating volley request obj
final JsonArrayRequest bookrequest = 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 =(JSONObject) response.getJSONObject(i);
Book book = new Book();
book.setTitle(obj.getString("BTitle"));
book.setThumbnailUrl(obj.getString("BCoverpath"));
book.setAuthor(obj.getString("BAuthor"));
book.setEdition(obj.getString("BEdition"));
book.setCategory(obj.getString("Bcategory"));
book.setLanguage(obj.getString("BLanguage"));
book.setDescription(obj.getString("BDescription"));
book.setCover(obj.getString("BCover"));
book.setOwner(obj.getString("UserFN"));
// adding book to books array
bookList.add(book);
} 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();
}
}
);
// Adding request to request queue
AppController.getInstance().addToRequestQueue(bookrequest);
// setting an onItem click listener in order to open the view book activity
listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
bookname=((TextView)view.findViewById(R.id.title)).getText().toString();
Bauthor=((TextView)view.findViewById(R.id.author)).getText().toString();
Bedition=((TextView)view.findViewById(R.id.edition)).getText().toString();
// intent to take the viewbook activity as its next dextination
Intent i = new Intent(getApplicationContext(), ViewBook.class);
// putting the name of the book with the inten extra package to use it as
// a key to retrieve the book info from the database and display it
i.putExtra("bookname",bookname);
i.putExtra("category",Bcategory);
i.putExtra("Bauthor",Bauthor);
i.putExtra("Bedition",Bedition);
startActivity(i);
}
});
I tried many methods and most of them end with an Out of bound exception and index out of bounds.
From within onItemClick(...) you have access to the position of the item that was clicked and the source of the items so you can use that information to get the actual item that was clicked.
I renamed the parameters to onItemClick() to give them a more descriptive name and assumed you have matching getter methods for the fields in Book.
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Book b = bookList.get(position);
Intent i = new Intent(Romance.this, ViewBook.class)
.putExtra("bookname", b.getTitle())
.putExtra("category", b.getCategory())
.putExtra("Bauthor", b.getAuthor())
.putExtra("Bedition", b.getEdition);
startActivity(i);
}

Categories

Resources