Accessing Arraylist Items - java

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);
}

Related

How putExtra in RecyclerView with arraylist from JSON

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'

Cant get android's autocomplete working with server response

So I have been trying to add a suggestion list for my auto-complete text view in android. I have added an onClickListener to it. Whenever onCLick is triggered. I have created an adapter and a data structure called mylist (ArrayList). I can't see any error but at the same time the autocomplete feature is not working. I am pretty sure there is some small glitch I am unable to find. Please let me know where am I going wrong. TIA.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user_input = findViewById(R.id.autoCompleteTextView1);
Log.i("here", "something");
user_input.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("here", "something");
String symbol_auto = String.valueOf(user_input.getText());
String company_auto = "http://us-east-2.elasticbeanstalk.com/autocomplete/"+symbol_auto;
requestQueue = Volley.newRequestQueue(MainActivity.this);
JsonArrayRequest arrayreq = new JsonArrayRequest(company_auto+symbol_auto,
new Response.Listener<JSONArray>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONArray response) {
try {
JSONObject jsonobj = response.getJSONObject(0);
data = jsonobj.getString("Name");
mylist.add(data);
Log.i("here", data);
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,android.R.layout.select_dialog_item, mylist);
user_input.setThreshold(1);
user_input.setAdapter(adapter);
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
},
// The final parameter overrides the method onErrorResponse() and passes VolleyError
//as a parameter
new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
// Adds the JSON array request "arrayreq" to the request queue
requestQueue.add(arrayreq);
}
});
}
I have tried adding elements to myList manually and it works like charm but the dropdown list just doesnt appear once I try adding it after querying to my back-end. My back-end is working fine. I have verified.
You have to iterate over your elements and add each one to your list, then set the adapter.
new Response.Listener<JSONArray>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONArray response) {
try {
mylist = new ArrayList();
for (int i = 0; i< response.length(); i++){
JSONObject jsonobj = response.getJSONObject(i);
String value = jsonobj.getString("Name");
mylist.add(value);
Log.i("here", value);
}
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,android.R.layout.select_dialog_item, mylist);
user_input.setThreshold(1);
user_input.setAdapter(adapter);
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
},
UPDATE - use OnClickListener to fire the event
user_input.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("here", "something");
String symbol_auto = String.valueOf(user_input.getText());
String company_auto = "http://us-east-2.elasticbeanstalk.com/autocomplete/"+symbol_auto;
requestQueue = Volley.newRequestQueue(MainActivity.this);
JsonArrayRequest arrayreq = new JsonArrayRequest(company_auto+symbol_auto,
new Response.Listener<JSONArray>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONArray response) {
try {
mylist = new ArrayList();
for (int i = 0; i < response.length(); i++){
JSONObject jsonobj = response.getJSONObject(i);
String value = jsonobj.getString("Name");
mylist.add(value);
Log.i("here", value);
}
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,android.R.layout.select_dialog_item, mylist);
user_input.setThreshold(1);
user_input.setAdapter(adapter);
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
},
// The final parameter overrides the method onErrorResponse() and passes VolleyError
//as a parameter
new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
// Adds the JSON array request "arrayreq" to the request queue
requestQueue.add(arrayreq);
}
});

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 <>();

How to delete a listitem from a listview set up like this

I set up this listvide like this from the data elements I received from a json request. Now what I'm not to sure about is how would I delete an listitem from this listview on a long click.
This is the background activity that populates the listview
class readNotifications extends AsyncTask<String, String, String>{
;
#Override
protected String doInBackground(String... params) {
// TODO Auto-generatNameValuePairb
List<NameValuePair>param=new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("id",SaveSharedPreference.getUserId(Notifications.this))); //SaveSharedPreference.getUserId(Notifications.this)
JSONObject json=jsonParser.makeHttpRequest(url_notifications, "POST", param);
Log.d("My Notifications", json.toString());
try {
JSONArray array = json.getJSONArray("notifications");
Log.d("Notifications length",Integer.toString(array.length()));
//if(array.length()==0)
//Log.d("Messages?","No Messages");
if(array.length()>0){
for (int i = 0; i < array.length(); i++) {
// Log.i("name", array.getJSONObject(i).getString("name"));
JSONObject c = array.getJSONObject(i);
// Storing each json item in variable
String id = c.getString("notification_id");
String message = c.getString("message");
//Log.i("picture_url", picture);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put("notification_id", id);
map.put("message", message);
// adding HashList to ArrayList
notifications.add(map);
}
}else{
runOnUiThread(new Runnable() {
public void run() {
TextView tx=(TextView)findViewById(R.id.nonotifications);
tx.setVisibility(0);
}
});
//Log.d("Notifications length",Integer.toString(array.length()));
}
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
Notifications.this, notifications,
R.layout.notifications, new String[] { "notification_id","message"},
new int[] { R.id.pid, R.id.notification});
// updating listview
setListAdapter(adapter);
}
});
}
}
class deleteNotification extends AsyncTask<String, String, String>{
String theirId=((TextView) findViewById(R.id.pid)).getText().toString();
#Override
protected String doInBackground(String... params) {
// TODO Auto-generatNameValuePairb
List<NameValuePair>param=new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("id",SaveSharedPreference.getUserId(Notifications.this))); //SaveSharedPreference.getUserId(Notifications.this)
param.add(new BasicNameValuePair("nid",notiId));
JSONObject json=jsonParser.makeHttpRequest(url_delete_notification, "POST", param);
Log.d("Their Id", theirId );
Log.d("My Notifications", json.toString());
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
//new readNotifications().execute();
}
});
}
}
This is the start of the longclicklistener I did.
ListView lv= getListView();
registerForContextMenu(lv);
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id)
yeah so I don't know how I would delete any item from the listview.
You remove the item from the list adapter and call notifyDataSetChanged().
The plain ListAdapter doesn't have a remove method, and I don't know what SimpleAdapter extends, but ArrayAdapter has a remove method and you could add your own to a BaseAdapter.
Btw, if you want a simpler way to create a ListAdapter, this may help (make a class that extends SilkAdapter instead of ArrayAdapter or whatever you're using): https://github.com/afollestad/Silk/blob/master/src/com/afollestad/silk/adapters/SilkAdapter.java
Now what I'm not to sure about is how would I delete an listitem from
this listview on a long click.
You just have to remove the item from your dataset and call notifyDataSetChanged on the ListViews adapter.
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id){
notifications.remove(pos);
adapter.notifyDataSetChanged();
}

Pass java object to new android instance on list view click

I have a list view populated by json returned from an api. As I parse the json I create a new java object that gets added to an array list. The array list is then used to build the list view. I can currentley click on an item in the list view and get a toast saying an item was clicked.
I would like to to be able to retrieve the individual object so I cna pass the object to a new instance and load all the objects details on a new instance to display to a user. How can I pass an object on like this?
My Code:
private class ReadJSONResult extends AsyncTask
<String, Void, String> {
protected String doInBackground(String... urls) {
return readJSONFeed(urls[0]);
}
protected void onPostExecute(String result) {
try {
System.out.println(result);
Log.d("asycTask", "[ Gets into asyc task ]");
///get
Log.d("search", "[ check if we get search results ]");
Log.d("search", "[" + result + "]");
JSONObject json = new JSONObject(result);
//acces listview
lv = (ListView) findViewById(android.R.id.list);
//make array list for beer
List<BeerData> beerList = new ArrayList<BeerData>();
//get json items
for(int i = 0; i < json.getJSONArray("data").length(); i++) {
String beerId = GetBeerDataFromJSON(i,"id", json);
String beerName = GetBeerDataFromJSON(i,"name", json);
String beerDescription = GetBeerDataFromJSON(i,"description" , json);
String beerAbv = GetBeerDataFromJSON(i,"abv" , json);
String beerIbu = GetBeerDataFromJSON(i,"ibu" , json);
String beerIcon = GetBeerIconsFromJSON(i, "icon",json );
String beerMediumIcon = GetBeerIconsFromJSON(i, "medium",json );
String beerGlass = GetBeerGlassFromJSON(i, json );
String beerStyle = GetBeerStyleFromJSON(i,"name", json );
String beerStyleDescription = GetBeerStyleFromJSON(i,"description", json );
String beerBreweryId = GetBeerBreweryInfoFromJSON(i, "id", json );
String beerBreweryName = GetBeerBreweryInfoFromJSON(i, "name", json );
String beerBreweryDescription = GetBeerBreweryInfoFromJSON(i, "description", json );
String beerBreweryWebsite = GetBeerBreweryInfoFromJSON(i, "website", json );
String beerBreweryYear = GetBeerBreweryInfoFromJSON(i, "established", json );
//create beer object
BeerData thisBeer = new BeerData(beerName, beerId, beerDescription, beerAbv, beerIbu, beerIcon,
beerMediumIcon, beerGlass, beerStyle, beerStyleDescription, beerBreweryId, beerBreweryName,
beerBreweryDescription, beerBreweryYear, beerBreweryWebsite);
//add beer to list
beerList.add(thisBeer);
}
//update listview
ArrayAdapter<BeerData> adapter1 = new ArrayAdapter<BeerData>(MainActivity.this, R.layout.list_item, R.id.itemName, beerList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
//on item click do this
Toast.makeText(MainActivity.this, "click worked", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
Log.d("ReadBeerDataTask", e.getLocalizedMessage());
}
}
}
Let your BeerData class implements the Parcelable interface. Then just do :
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra("myBeerObject", lv.getItemAtPosition(arg2));
startActivity(i);
}
});
From the second class :
Bundle b = getIntent().getExtras();
BeerData beer = b.getParcelable("myBeerObject");
Here's an example of how to implement the interface correctly.
Simple Steps to should allow you to do this:
Keep track of a BeerData collection. This would be beerList in your case.
Make BeerData implement Parceable.
(Use proper parameter names in OnItemClick. It should be onItemClick(AdapterView<?> parent, View view, int position, long id)"
In onItemClick
onItemClick(AdapterView<?> parent, View view, int position, long id) {
var beerData = beerList[position];
Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
intent.putExtra("BEER!", beerData);
startActivity(intent);
}
In NextActivities onCreate:
{
Bundle extras = getIntent().getExtras();
BeerData beerData = (BeerData) extras.getParcelable("BEER!);
}

Categories

Resources