Dynamic add items to listview using arrayadapter Android - android

Im using Custom class to fill Adapter on ListView
Class looks like that:
package com.example.raidplanner;
public class RaidWpis {
private int id;
private int id_gildia;
private String nazwa;
private int schemat;
private int data_zapis;
private int data_start;
private int opis;
private int id_officer;
private int nick_officer;
private int typ;
public RaidWpis(int id,String nazwa) {
setNazwa(nazwa);
setId(id);
}
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getNazwa() {
return nazwa;}
public void setNazwa(String nazwa) {
this.nazwa = nazwa;
}
public String toString() {
return this.nazwa;
}
public String toString2() {
return this.id+" - "+nazwa;
}
}
In my activity Im using this code
RaidWpis[] items = {
new RaidWpis(1, "aaaa"),
new RaidWpis(3, "bbbb"),
new RaidWpis(6, "cccc"),
new RaidWpis(11, "dddd"),
new RaidWpis(17, "eeee"),
};
mainListView = (ListView) findViewById( R.id.mainListView );
ArrayAdapter<RaidWpis> raidList = new ArrayAdapter<RaidWpis>(this, R.layout.simplerow, items);
// Create ArrayAdapter using the raid list.
mainListView.setAdapter(raidList);
Now how to add new items to items array. Finaly I want to fill that items array with data from json data (passed from PHP)

I did it, just changed some code to that:
ArrayList<RaidWpis> raid_list = new ArrayList<RaidWpis>();
raid_list.add(new RaidWpis(1, "aaaa"));
raid_list.add(new RaidWpis(3, "bbb"));
raid_list.add(new RaidWpis(5, "ccc"));
ArrayAdapter<RaidWpis> raidList=new ArrayAdapter<RaidWpis>(this, R.layout.simplerow, raid_list);

Related

How to view RecyclerView items sorted by ID?

In my app i have something like a menu that load data stored in SharedPreferences to a Constructor and build from it 2 RecyclerView's.
Now i want to make that if i press an button from the bottom recyclerView like "CICCIO" that has in it constructor item like ID set by 1 i would that in the other recyclerView where there are a lot of colored buttons to be visualized just button's that have also ID set by 1 in their constructor but i'm not very in to android and i can't get how can i make a "sort method" like that.
I have yet the onClick method set on bottom RecyclerView and i have yet method's getID from the bottom recyclerView constructor and getID from the top RecyclerView.
ACTIVITY SCREENSHOT HERE
And here is the code from my activity:
// Builder del BOTTOM recyclerView
public void buildRecyclerViewMenu(){
RecyclerView mRecyclerView = findViewById(R.id.recyclerViewMenu);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false);
RecyclerViewMenu recyclerViewMenu = new RecyclerViewMenu(menuConstructors);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(recyclerViewMenu);
recyclerViewMenu.setOnItemClickListener(new RecyclerViewMenu.OnItemClickListener() {
#Override
public void onItemClick(int position) {
}
});
}
// Builder del TOP recyclerView
public void buildRecyclerView(){
mRecyclerViewBOT = findViewById(R.id.recyclerView);
mRecyclerViewBOT.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 4);
Adapter mAdapter = new Adapter(items);
mRecyclerViewBOT.setLayoutManager(mLayoutManager);
mRecyclerViewBOT.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new Adapter.OnItemClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onItemClick(final int position) {
}
});
}
While here are the method's where i load data to Bottom and top RecyclerView
private void loadDataMenu(){
new ArrayList<MenuConstructor>();
SharedPreferences sharedPreferences = getSharedPreferences("MENU_SAVE", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("menu list",null);
Type type = new TypeToken<ArrayList<MenuConstructor>>() {}.getType();
menuConstructors = gson.fromJson(json, type );
if(menuConstructors == null){
menuConstructors = new ArrayList<>();
Toast.makeText(cassa.this,"NESSUN TASTO DA VISUALIZZARE" ,Toast.LENGTH_SHORT).show();
}
}
private void loadDataTasti(){
new ArrayList<Item>();
SharedPreferences sharedPreferences = getSharedPreferences("TASTI_SAVE", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("tasti list",null);
Type type = new TypeToken<ArrayList<Item>>() {}.getType();
items = gson.fromJson(json, type );
if(items == null){
items = new ArrayList<>();
Toast.makeText(cassa.this,"NESSUN TASTO DA VISUALIZZARE" ,Toast.LENGTH_SHORT).show();
}
}
While here is my Item.java that is the model class of TOP recycler View:
public class Item {
private int menu;
private String tipo;
private String codice;
private String deskT;
private String deskS;
private String sfondo;
private String font;
private String qta;
private double pre;
Item(int id, String typo, String codice_t, String desk_T,String desk_S,String sfondo_c,String font_c,String quant,double prezzo){
menu = id;
tipo = typo;
codice = codice_t;
deskT = desk_T;
deskS = desk_S;
sfondo = sfondo_c;
font = font_c;
qta = quant;
pre = prezzo;
}
public int getMenu(){return menu;}
public String getTipo(){return tipo;}
public String getCodice(){return codice;}
public String getDeskT(){return deskT;}
public String getDeskS(){return deskS;}
public String getSfondo(){return sfondo;}
public String getFont(){return font;}
public String getQuant(){return qta;}
public double getPrice(){return pre;}
}
And here is the model of MenuConstructor (bottom recyclerView)
public class MenuConstructor {
int id;
private String deskT;
private String sfondo;
private String font;
MenuConstructor(int idID,String Desk,String Sfondo,String Font){
id = idID;
deskT = Desk;
sfondo = Sfondo;
font = Font;
}
public int getBtnID(){
return id;
}
public String getDesk(){
return deskT;
}
public String getSfondoColor(){
return sfondo;
}
public String getFontColor(){
return font;
}
}
so i want to compare the id from MenuConstructor with menu (id) from the Item.java and show just item with a certain ID.
You can using Collections.sort()
private List<Item> getSortedItems(List<Item> items) {
Collections.sort(items, new Comparator<Item>() {
#Override
public int compare(Item item, Item nextItem) {
return ComparisonChain.start()
.compare(item.getMenu(), nextItem.getMenu())
.result();
}
});
return items;
}
this method will return the item list sort by menu
hope this helps
Solved by creating a new ArrayList and comparing the item.getMenu() with menuConstructors.getBtnID() in a for cycle which scrolls for the same lenght of the ArrayList.
recyclerViewMenu.setOnItemClickListener(new RecyclerViewMenu.OnItemClickListener() {
#Override
public void onItemClick(int position) {
Toast.makeText(cassa.this,String.valueOf(menuConstructors.get(position).getBtnID()),Toast.LENGTH_SHORT).show();
ArrayList<Item> filteredList = new ArrayList<>();
for(Item item : items) {
if(item.getMenu() == menuConstructors.get(position).getBtnID() ) {
filteredList.add(item);
}
}
mAdapter.filterList(filteredList);
}
});

Click on ListView item not opening new Activity

I have a ListView "resultList", but clicking on an item is not opening the new (detailed) Activity. What's my mistake?
Thank you!
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.resultList = (ListView) findViewById(R.id.resultList) ;
this.dataSource = MyExpenseOpenHandler.getInstance(this).readAllExpenses();
this.adapter = new ExpenseOverviewAdapter(this, dataSource);
this.resultList.setAdapter(adapter);
this.resultList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> adapterView, View view, final int i, final long l) {
Object element = adapterView.getAdapter().getItem(i);
if (element instanceof Expense) {
Expense expense = (Expense) element;
Intent intent = new Intent(MainActivity.this, ExpenseDetailActivity.class);
intent.putExtra(ExpenseDetailActivity.EXPENSE_KEY, expense);
startActivity(intent);
}
Log.e("Click on List: ", element.toString());
}
});
}
Your code seems alright .I think the problem is that your if condition may be returning false and the code inside the if statement is not being executed.You can put a log message inside the if statement to check if the code is being executed.
if (element instanceof Expense) {
Log.d(YOUR_LOG_TAG,"The if condition not executed")
Expense expense = (Expense) element;
Intent intent = new Intent(MainActivity.this, ExpenseDetailActivity.class);
intent.putExtra(ExpenseDetailActivity.EXPENSE_KEY, expense);
startActivity(intent);
}
If you see the log message in your android monitor you can be sure that the code inside your if condition is not executed and hence your activity is not starting.
Did you implement Parcelable on your class Expense ?
Something like this
public class Expense implements Parcelable{
private String id;
private String name;
private String grade;
// Constructor
public Expense(String id, String name, String grade){
this.id = id;
this.name = name;
this.grade = grade;
}
// Getter and setter methods
.........
.........
// Parcelling part
public Expense(Parcel in){
String[] data = new String[3];
in.readStringArray(data);
// the order needs to be the same as in writeToParcel() method
this.id = data[0];
this.name = data[1];
this.grade = data[2];
}
#Оverride
public int describeContents(){
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] {this.id,
this.name,
this.grade});
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Expense createFromParcel(Parcel in) {
return new Expense(in);
}
public Expense[] newArray(int size) {
return new Expense[size];
}
};
}
what kind of view in the list, if the child view get the focus like button may lead to item click not work well.
you can try to add android:descendantFocusability="beforeDescendants" in you listview.

How to load Json data into a spinner in Android?

I can get the data from the server loaded into a List<>, but can't get the specific items.
Json data looks like this.
[
{"subscriptionType":"1234,
"typeName":"stuff",
"name":"Alpha"},
{"subscriptionType":"1234,
"typeName":"stuff",
"name":"Beta"},
]
and so on...
I have a class that that I load the data into from a Presenter calling a Fetch event. All that seems to be working because I get a Log for the data loaded into the Array
public class AppEntitySubscriptions implements Parcelable {
public AppEntitySubscriptions(ApiSubscription apiSubscription) {
this.subscriptionType = apiSubscription.getSubscriptionType();
this.typeName = apiSubscription.getTypeName();
this.name = apiSubscription.getName();
}
private int subscriptionType;
private String typeName;
private String name;
public
int getSubscriptionType() {
return subscriptionType;
}
public String getTypeName() {
return typeName;
}
public String getName() {
return name;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.subscriptionType);
dest.writeString(this.typeName);
dest.writeString(this.name);
}
#SuppressWarnings("ResourceType")
protected AppEntitySubscriptions(Parcel in) {
this.subscriptionType = in.readInt();
this.typeName = in.readString();
this.name = in.readString();
}
public static final Creator<AppEntitySubscriptions> CREATOR = new Creator<AppEntitySubscriptions>() {
#Override
public AppEntitySubscriptions createFromParcel(Parcel in) {
return new AppEntitySubscriptions(in);
}
#Override
public AppEntitySubscriptions[] newArray(int size) {
return new AppEntitySubscriptions[size];
}
};
Now here is where I am getting lost. I just want to get the data for "name" elements into a spinner
Spinner spinner = (Spinner) findViewById(R.id.spinner);
List<AppEntitySubscriptions> userSubscriptions;//data is here
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.toolbar_spinner_item, "what goes here"???);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
I don't know how to get the name into a string array of it's own and loaded into the spinner. Any suggestions would be helpful.
Thanks.
You could not use this list in Spinner
private List<AppEntitySubscriptions> subscriptionsList = new ArrayList<>();
Create new list
private List subscriptionsStrings = new ArrayList<>();
and fill it
for (int i=0; i<subscriptionsList.size(); i++) {
subscriptionsStrings.add(subscriptionsList.get(i).getTypeName());
}
and then
ArrayAdapter<ArrayList<String>>(this, R.layout.toolbar_spinner_item, subscriptionsStrings);

How do I populate a spinner with a list of objects and not just strings?

Hello I'm new at Android. I want to populate a Spinner with a list of objects. I have googled how to do it but I just find examples with an array of strings.
Can any one help me?
This is my code:
Categories class:
public class Categories
{
#com.google.gson.annotations.SerializedName("id")
private String mId;
#com.google.gson.annotations.SerializedName("name")
private String mName;
public Categories()
{}
public Categories(String id, String name)
{
this.setId(id);
this.setName(name);
}
#Override
public String toString()
{
return mName;
}
// ******** GET *************
public String getId()
{
return mId;
}
public String getName()
{
return mName;
}
// ******** SET *************
public final void setId(String id)
{
mId = id;
}
public final void setName(String name)
{
mName = name;
}
}
This is my Activity code:
public class AgregarActividadActivity extends ActionBarActivity
{
private MobileServiceClient mClient;
private MobileServiceTable<Activities> mActivitiesTable;
private MobileServiceTable<Categories> mCategoriesTable;
private MobileServiceTable<Projects> mProjectsTable;
private EditText mTxtTitulo;
private EditText mTxtDescr;
String categryId = null;
List<Categories> catList = new ArrayList<Categories>();
Spinner spEstado;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_agregar_actividad);
try
{
mClient = new MobileServiceClient(
"https://site.azure-mobile.net/",
"AppKey",
this);
mActivitiesTable = mClient.getTable(Activities.class);
mCategoriesTable = mClient.getTable(Categories.class);
}
catch (MalformedURLException e)
{
createAndShowDialogExc(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
}
mTxtTitulo = (EditText) findViewById(R.id.txtTitulo);
mTxtDescr = (EditText) findViewById(R.id.txtDescripcion);
getCategories();
spEstado = (Spinner)this.findViewById(R.id.spEstado);
ArrayAdapter<Categories> Adapter = new ArrayAdapter<Categories>(this,
android.R.layout.simple_spinner_item, catList);
Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spEstado.setAdapter(Adapter);
spEstado.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent,
View view,
int position,
long id) {
Categories item = (Categories) parent.getItemAtPosition(position);
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
);
spProjects = (Spinner)this.findViewById(R.id.spProyecto);
ArrayAdapter<Projects> proAdapter = new ArrayAdapter<Projects>(this,
android.R.layout.simple_spinner_item, proList);
proAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spProjects.setAdapter(proAdapter);
}
private void getCategories()
{
mCategoriesTable.execute(new TableQueryCallback<Categories>()
{
public void onCompleted(List<Categories> result, int count, Exception exception, ServiceFilterResponse response)
{
if (exception == null)
{
for (Categories item : result)
{
catList.add(item);
}
}
else
{
createAndShowDialog(exception, "Error");
}
}
});
}
}
I get the dropdownlist with the objects, but when I select one item, it is not displayed as the selected item, when the dropdownlist is hidden.
Any idea will help me! Thank you!!
You need to write a CustomAdapter for this. It is similar to writing a CustomAdapter for a ListView. You can look at Custom Adapter for List View for an idea

Android ArrayAdapter with Object and Get some data from that object

Im trying to make ListView using data from Array, but I need to get Id of clicked row (not shown in that row, but userd in creation of that product)
Im using this class for object:
package com.example.raidplanner;
public class RaidWpis {
private int id;
private int id_gildia;
private String nazwa;
private int schemat;
private int data_zapis;
private int data_start;
private int opis;
private int id_officer;
private int nick_officer;
private int typ;
public RaidWpis(int id,String nazwa) {
setNazwa(nazwa);
setId(id);
}
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getNazwa() { return nazwa; }
public void setNazwa(String nazwa) { this.nazwa = nazwa; }
public String toString() {
return this.nazwa;
}
public String toString2() {
return this.id+" - "+nazwa;
}
}
And this code in Activity:
RaidWpis[] items = {
new RaidWpis(1, "aaaa"),
new RaidWpis(3, "bbbb"),
new RaidWpis(6, "cccc"),
new RaidWpis(11, "dddd"),
new RaidWpis(17, "eeee"),
};
mainListView = (ListView) findViewById( R.id.mainListView );
ArrayAdapter<RaidWpis> raidList = new ArrayAdapter<RaidWpis>(this, R.layout.simplerow, items);
// Create ArrayAdapter using the raid list.
mainListView.setAdapter(raidList);
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id)
{
String item = ((TextView)view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
I need to get Id of clicked row (not shown in that row, but userd in creation of that product)
Try this in your onItemClick() method:
RaidWpis obj = parent.getAdapter().getItem(position); // or just raidList.get(position) if raidList is a field variable
Toast.makeText(getBaseContext(), obj.getID() + "", Toast.LENGTH_LONG).show();
from the position, you can get the RaidWpis Object by using raidList.get(position). Once you have this RaidWpis object, you can call getId() to get the id

Categories

Resources