Android ArrayAdapter with Object and Get some data from that object - android

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

Related

Custom adapter with setOnitemClick

I have a spinner contains three options "ALL","PAYMENTS" and "EXPENSES". These will show 3 listviews. "ALL" option will show the mixture of both "PAYMENT" and "EXPENSES".
My problem is I want to add setOnItemClickListener for both of the lists. Please refer the screenshot. I will pass certain values whenever I click on each list. Whenever I click on list in payments, it will go to paymentdetails activity, and whenever click on list in expense it will go to expense details activity. This should be same from "ALL". There are three different adapter for each list (i.e., ALL, PAYMENT and expense). The code is below.
try {
final JSONArray invoices = new JSONArray(common.json);
if (invoices.length() == 0) {
(rootView.findViewById(R.id.no_items)).setVisibility(View.VISIBLE);
return;
}
final ArrayList<String[]> invoiceListData = new ArrayList<>();
for (int i = 0; i < invoices.length(); i++) {
JSONObject jsonObject1 = invoices.getJSONObject(i);
String[] data = new String[9];
data[0] = jsonObject1.getString("ID");
data[1] = jsonObject1.getString("EntryNo");
data[2] = jsonObject1.getString("Company");
data[3] = jsonObject1.getString("Date");
data[4] = jsonObject1.getString("PaymentMode");
data[5] = jsonObject1.getString("Amount");
data[6] = jsonObject1.getString("Type");
data[7] = jsonObject1.getString("ApprovalDate");
data[8] = jsonObject1.getString("GeneralNotes");
invoiceListData.add(data);
}
adapter = new CustomAdapter(getContext(), invoiceListData, Common.PREVIOUSPAYMENTS);
invoiceList.setAdapter(adapter);
(rootView.findViewById(R.id.list_card)).setVisibility(View.VISIBLE);
final ArrayList<String[]>PaymentListData=new ArrayList<>();
final ArrayList<String[]>ExpenseListData=new ArrayList<>();
for (int i = 0; i < invoiceListData.size(); i++) {
if (invoiceListData.get(i)[6].equals("Payment")) {
PaymentListData.add(invoiceListData.get(i));
invoiceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent approvalDetailsIntent = new Intent(getContext(),ApprovalDetails.class);
approvalDetailsIntent.putExtra(Common.APPROVALID,invoiceListData.get(position)[0]);
approvalDetailsIntent.putExtra(Common.ENTRYNO,invoiceListData.get(position)[1]);
approvalDetailsIntent.putExtra(Common.PAYMENT_MODE,invoiceListData.get(position)[2]);
approvalDetailsIntent.putExtra(Common.PAYMENT_DATE,invoiceListData.get(position)[3]);
approvalDetailsIntent.putExtra(Common.AMOUNT,invoiceListData.get(position)[4]);
approvalDetailsIntent.putExtra(Common.COMPANY_DETAILS,invoiceListData.get(position)[5]);
approvalDetailsIntent.putExtra(Common.GENERAL_NOTES,invoiceListData.get(position)[8]);
startActivity(approvalDetailsIntent);
}
});
} else if(invoiceListData.get(i)[6].equals("Expense")) {
(rootView.findViewById(R.id.list_card)).setVisibility(View.VISIBLE);
invoiceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent approvalDetailsIntent = new Intent(getContext(),ApprovalExpenseDetails.class);
approvalDetailsIntent.putExtra(Common.APPROVALID,ExpenseListData.get(position)[0]);
approvalDetailsIntent.putExtra(Common.REFNO,ExpenseListData.get(position)[1]);
startActivity(approvalDetailsIntent);
}
});
}
}
Padapter = new CustomAdapter(getContext(),PaymentListData,Common.PREVIOUSPAYMENTS); //Global variable
invoiceList.setAdapter(Padapter);
(rootView.findViewById(R.id.list_card)).setVisibility(View.VISIBLE);
Eadapter = new CustomAdapter(getContext(),ExpenseListData,Common.PREVIOUSPAYMENTS);
invoiceList.setAdapter(adapter);
(rootView.findViewById(R.id.list_card)).setVisibility(View.VISIBLE);
// Values passing for payments only.I dont know whether invoiceListData.get()..is correct or not.
invoiceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent approvalDetailsIntent=new Intent(getContext(),ApprovalDetails.class);
approvalDetailsIntent.putExtra(Common.APPROVALID,invoiceListData.get(position)[0]);
approvalDetailsIntent.putExtra(Common.ENTRYNO,invoiceListData.get(position)[1]);
approvalDetailsIntent.putExtra(Common.PAYMENT_MODE,invoiceListData.get(position)[2]);
approvalDetailsIntent.putExtra(Common.PAYMENT_DATE,invoiceListData.get(position)[3]);
approvalDetailsIntent.putExtra(Common.AMOUNT,invoiceListData.get(position)[4]);
approvalDetailsIntent.putExtra(Common.COMPANY_DETAILS,invoiceListData.get(position)[5]);
approvalDetailsIntent.putExtra(Common.GENERAL_NOTES,invoiceListData.get(position)[8]);
startActivity(approvalDetailsIntent);
}
});
//values passing for expense only
invoiceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent approvalDetailsIntent = new Intent(getContext(),ApprovalExpenseDetails.class);
approvalDetailsIntent.putExtra(Common.APPROVALID,ExpenseListData.get(position)[0]);
approvalDetailsIntent.putExtra(Common.REFNO,ExpenseListData.get(position)[1]);
startActivity(approvalDetailsIntent);
}
});
you can not set onclicklistener for items in list ! you must set onclicklistener for each view in customAdapter
If you have same type of data for all 3 types follow certain development rules.
Create POJO (model) class for data. that help you in storing data in structured manner.
InvoiceData.java
public class InvoiceData {
private String Id;
private String EntryNo;
private String Company;
private String Date;
private String PaymentMode;
private String Amount;
private String Type; // "ALL", "Income", "Expense"
private String ApprovalDate;
private String GeneralNotes;
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getEntryNo() {
return EntryNo;
}
public void setEntryNo(String entryNo) {
EntryNo = entryNo;
}
public String getCompany() {
return Company;
}
public void setCompany(String company) {
Company = company;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
Date = date;
}
public String getPaymentMode() {
return PaymentMode;
}
public void setPaymentMode(String paymentMode) {
PaymentMode = paymentMode;
}
public String getAmount() {
return Amount;
}
public void setAmount(String amount) {
Amount = amount;
}
public String getType() {
return Type;
}
public void setType(String type) {
Type = type;
}
public String getApprovalDate() {
return ApprovalDate;
}
public void setApprovalDate(String approvalDate) {
ApprovalDate = approvalDate;
}
public String getGeneralNotes() {
return GeneralNotes;
}
public void setGeneralNotes(String generalNotes) {
GeneralNotes = generalNotes;
}
}
Set data like this with model
final ArrayList<InvoiceData> invoiceListData = new ArrayList<>();
JSONObject jsonObject1;
InvoiceData rowObject;
for (int i = 0; i < invoices.length(); i++) {
jsonObject1 = invoices.getJSONObject(i);
rowObject = new InvoiceData();
rowObject.setId(jsonObject1.getString("ID"));
rowObject.setEntryNo(jsonObject1.getString("EntryNo"));
rowObject.setCompany(jsonObject1.getString("Company"));
rowObject.setDate(jsonObject1.getString("Date"));
rowObject.setPaymentMode(jsonObject1.getString("PaymentMode"));
rowObject.setAmount(jsonObject1.getString("Amount"));
rowObject.setApprovalDate(jsonObject1.getString("ApprovalDate"));
rowObject.setGeneralNotes(jsonObject1.getString("GeneralNotes"));
rowObject.setType("Expense");
invoiceListData.add(rowObject);
}
adapter = new CustomAdapter(getContext(), invoiceListData, Common.PREVIOUSPAYMENTS);
invoiceList.setAdapter(adapter);
And to set on item click listener on Listview (Make sure it is listview b'z recycler view have no such method)
invoiceList.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
InvoiceData rowObject = adapter.getItem(position);
if(rowObject != null) {
if(rowObject.getType().equals("Expense")) {
// write different code for Expense here
} else if(rowObject.getType().equals("Income")) {
// write different code for Income here
}
}
}
});
Hope this will help...

Update an EditText of an Intent from a variable of an object

I will try to be brief and precise:
I have a user object that contains a chat, and this is updated every time I receive a message:
public class Usuarios implements Serializable {
private static final long serialVersionUID = 1113799434508676095L;
private int id;
private String nombre;
private String ip;
private boolean isSInicial;
//HERE WILL GO THE VARIABLE THAT STORMS THE CHAT, BUT I DO NOT KNOW HOW TO IMPLEMENT IT
public Usuarios(int id, String nombre, String ip, boolean isSInicial){
this.id = id;
this.nombre = nombre;
this.ip = ip;
this.isSInicial = isSInicial;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public boolean isSInicial() {
return isSInicial;
}
public void setSInicial(boolean SInicial) {
isSInicial = SInicial;
}}
I have an activity, that by clicking on a list, loads a new activity for the specific user:
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long id) {
Usuarios e = (Usuarios) listview.getItemAtPosition(pos);
Intent visorDetalles = new Intent(view.getContext(),Chat.class);
if(Contactos.listaDeContactos.indexOf(e) >= 0) {
visorDetalles.putExtra("indice", Contactos.listaDeContactos.indexOf(e));
startActivity(visorDetalles);
}
else{
Toast.makeText(contexto,"Usuario fuera de linea",Toast.LENGTH_LONG);
}
}
});
I need the EditText that contains the Intent to be updated automatically every time I click on a user of a ListView.
I do not know what kind of variable I should use in the user object and how to implement it.
In your Usuarios class add the variable:
public ArrayList<String> currentChat;
Instead of passing the index, pass the Object himself maybe.
if(Contactos.listaDeContactos.indexOf(e) >= 0) {
visorDetalles.putExtra("usuario",e);
startActivity(visorDetalles);
}
else{
Toast.makeText(contexto,"Usuario fuera de linea",Toast.LENGTH_LONG);
}
And in your onCreate Chat Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Intent intent = getIntent();
Usuario usuario = (Usuario) intent.getSerializableExtra("usuario");
EditText myEditText = (EditText)findViewById(R.id.myEditText1));
String allChat;
for(String chatLine : usuario.currentChat) {
allChat += chatLine + '\n';
}
myEditText.setText(allChat);
Did I got your problem right ?

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 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

Dynamic add items to listview using arrayadapter 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);

Categories

Resources