How to load Json data into a spinner in Android? - 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);

Related

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.

xamarin android bundle put parcelable array

I need to save array of object in bundle, here is what I did :
create class what is implementing IParcable interface:
public class SimpleSelectorItem : Java.Lang.Object, Android.OS.IParcelable
{
public int Id { get; set; }
public string Name { get; set; }
public bool Selected { get; set; }
IntPtr IJavaObject.Handle { get { return IntPtr.Zero; } }
public int DescribeContents()
{
return 0;
}
public SimpleSelectorItem()
{
}
public SimpleSelectorItem(int id, string name)
{
Id = id;
Name = name;
}
public SimpleSelectorItem(Parcel parcel)
{
Id = parcel.ReadInt();
Name = parcel.ReadString();
}
public void WriteToParcel(Parcel dest, [GeneratedEnum] ParcelableWriteFlags flags)
{
dest.WriteInt(Id);
dest.WriteString(Name);
}
static readonly GenericParcelableCreator<SimpleSelectorItem> _creator
= new GenericParcelableCreator<SimpleSelectorItem>((parcel) => new SimpleSelectorItem(parcel));
[ExportField("CREATOR")]
public static GenericParcelableCreator<SimpleSelectorItem> GetCreator()
{
return _creator;
}
}
when I'm creating instance of my fragment , trying to set array of SimpleSelectorItem in bundle :
var items = _viewModel.GetEmployees().Select(l => new SimpleSelectorItem(l.Id, l.LegalName)).ToArray();
....
args.PutParcelableArray(ITEMS, items);
But when I'm getting back this array, it is array of nulls..
var items = Arguments.GetParcelableArray(ITEMS);
Here is demo application , it throw exception while i'm trying to cast items:
https://github.com/Nininea/XamarinAndroidPutParcelableArray
But when I'm getting back this array, it is array of nulls..
I've tested the project.The data are passed correctly, but the cast failed.
To resolve the problem, you need to cast the array differently:
In SetData Method:
private void SetData(View rootView)
{
...
//use the following line to retrieve and cast the items to SimpleSelectorItem[]
var items = Arguments.GetParcelableArray(ITEMS).Cast<SimpleSelectorItem>().ToList();
_lvSelector = (ListView)rootView.FindViewById(Resource.Id.lvSelector);
//pass the items to your adapter.
SimpleSelectorListAdapter adapter = new SimpleSelectorListAdapter(Activity, items);
_lvSelector.Adapter = adapter;
}

Passing ArreyList between Fragments with Parcelable

After consuming a json with Retrofit and using unsynchronous callback I can't pass An ArrayList from The MainActivity to a fragment .
Code from MainActivity:
lFragmentManager = getFragmentManager();
lFragment = lFragmentManager.findFragmentById(R.id.frame_container);
lFragment = new Fragment_Categories();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("list_categories", Categories_.getCategories());
//for(int a = 0 ; a < Categories_.getCategories().size(); a++)
// Log.d("billy",Categories_.getCategories().get(a).getTitle());
lFragment.setArguments(bundle);
lFragmentManager.beginTransaction().replace(R.id.frame_container ,lFragment ).commit();
Note that the Log inside comments does print the context of the list, so I take the ArrayList in the fragment with this code inside onCreateView:
if(savedInstanceState != null)
categories = savedInstanceState.getParcelableArrayList("list_categories");
/*
* initialize the Recycler view
*/
mRecycler = (RecyclerView)view.findViewById(R.id.categories_list);
mAdapter = new AdapterCategories(categories,getActivity());
mRecycler.setAdapter(mAdapter);
Here is my Class Category :
public class Categories implements Parcelable{
private ArrayList<NavDrawerItem> categories;
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedList(categories);
}
public static final Parcelable.Creator<Categories> CREATOR = new Parcelable.Creator<Categories>() {
public Categories createFromParcel(Parcel in) {
return new Categories(in);
}
public Categories[] newArray(int size){
return new Categories[size];
}
};
private Categories(Parcel in){
categories = in.createTypedArrayList(NavDrawerItem.CREATOR);
}
public ArrayList<NavDrawerItem> getCategories() {
return categories;
}
}
And here is the Class NavDrawerItem:
public class NavDrawerItem implements Parcelable {
private String title;
private String description;
private String image;
private String post_count;
private String id;
private String slug;
private int parent;
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(description);
dest.writeString(image);
dest.writeString(post_count);
dest.writeString(id);
dest.writeString(slug);
dest.writeInt(parent);
}
public static final Parcelable.Creator<NavDrawerItem> CREATOR = new Parcelable.Creator<NavDrawerItem>() {
public NavDrawerItem createFromParcel(Parcel in) {
return new NavDrawerItem(in);
}
public NavDrawerItem[] newArray(int size){
return new NavDrawerItem[size];
}
};
private NavDrawerItem(Parcel in){
title = in.readString();
description = in.readString();
image = in.readString();
post_count = in.readString();
id = in.readString();
slug = in.readString();
parent = in.readInt();
}
The problem is that inside fragment (when trying to pass the list to the Adapter of the RecyclerView) or inside the adapter of the RecyclerView I take a null exception :
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.ArrayList android.os.Bundle.getParcelableArrayList(java.lang.String)' on a null object reference
Thank you for the help!!
You wouldn't use the savedInstanceState to get your arguments, because they weren't passed as part of a saveInstanceState() operation. You want to use getArguments() instead. So try this...
categories = getArguments().getParcelableArrayList("list_categories");

Update an object passed through Parcelable intent

I'm new to Android and i'm still learning. I currently have a ListView which allows you to click on an item. Clicking on an item will open a new intent displaying extra information about the item.
The thing i'm tripping up on is figuring out how to get the updated values back into my custom object and update the values in array at the correct index.
For example:
I'll add an item and set it's quantity to 2. This will appear in my ListView. Great. I decide i need 3 instead of 2, so i click the item to open the new activity, see 2 sitting in quantity, update it to 3 and hit save. On the save click i want to go back to my listview and have the updated quantity value displaying there and also updated in the array at the index.
Code for segments:
Onclick method for the listview in ItemList class
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
bean = (CustomObject) listview.getItemAtPosition(arg2);
Intent in1 = new Intent(Itemlist.this, SingleItem.class);
in1.putExtra("ActivityObject", bean);
startActivity(in1);
}
});
Adding an item the array in my ItemList class. this contain the listview.
else {
objects.add(new CustomObject(roomname.getText().toString() + " - " + resultSet.get(namecount), resultSet.get(partno), itemq, "$" + resultSet.get(rrpcol), resultSet.get(glcode), resultSet.get(desc)));
adapter.notifyDataSetChanged();
SingleItem class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singleitem);
siname = (TextView) findViewById(R.id.siname);
sipartno = (TextView) findViewById(R.id.sipartno);
siquantity = (EditText) findViewById(R.id.siq);
sirrp = (EditText) findViewById(R.id.sirrp);
siglcode = (TextView) findViewById(R.id.siglcode);
sidesc = (EditText) findViewById(R.id.sidesc);
update = (Button) findViewById(R.id.siupdate);
Bundle b = getIntent().getExtras();
CustomObject itemInfo = b.getParcelable("ActivityObject");
siname.setText(itemInfo.getItemName());
sipartno.setText(itemInfo.getItemPartNo());
siquantity.setText(itemInfo.getItemQuantity());
sirrp.setText(itemInfo.getItemPrice());
siglcode.setText(itemInfo.getItemGLCode());
sidesc.setText(itemInfo.getItemDesc());
}
Custom Object class
public class CustomObject implements Parcelable {
private String itemName;
private String itemPartNo;
private String itemQuantity;
private String itemPrice;
private String itemGLCode;
private String itemDesc;
public CustomObject(Parcel source){
/*
* Reconstruct from the Parcel
*/
//Log.v(TAG, "ParcelData(Parcel source): time to put back parcel data");
//id = source.readInt();
itemName = source.readString();
itemPartNo = source.readString();
itemQuantity = source.readString();
itemPrice = source.readString();
itemGLCode = source.readString();
itemDesc = source.readString();
}
public CustomObject(String prop1, String prop2, String prop3, String prop4, String prop5, String prop6) {
this.itemName = prop1;
this.itemPartNo = prop2;
this.itemQuantity = prop3;
this.itemPrice = prop4;
this.itemGLCode = prop5;
this.itemDesc = prop6;
}
public String getItemName() {
return itemName;
}
public String getItemPartNo() { return itemPartNo; }
public String getItemQuantity() {
return itemQuantity;
}
public String getItemPrice() {
return itemPrice;
}
public String getItemGLCode() {return itemGLCode;}
public String getItemDesc() {return itemDesc;}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(itemName);
dest.writeString(itemPartNo);
dest.writeString(itemQuantity);
dest.writeString(itemPrice);
dest.writeString(itemGLCode);
dest.writeString(itemDesc);
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public CustomObject createFromParcel(Parcel in) {
return new CustomObject(in);
}
public CustomObject[] newArray(int size) {
return new CustomObject[size];
}
};
}
I want to be able to change the quantity in the SingleItem class, click the Update button, and then have it load up the itemlist class with the updated values in the item list.
It'd be more efficient to use Fragments with your own callback interfaces defined for the activity. But, if you want to go the Activity approach, use startActivityForResult() and have your detail Activity send back a result Intent with any updates object contents.

can't pass Parcelable data between activities

I looked everywhere and I think I'm missing something... I trying to pass my ArrayList with my object from activity to activity and getting "Unable to start activity... null pointer exception expected receiver of type EcgResultsHolder"...and the app crashes.
the type:
public class EcgDetails
{
private final String m_EcgProperties;
private final String m_Category;
public EcgDetails(String i_EcgProps, String i_Category)
{
m_EcgProperties = i_EcgProps;
m_Category = i_Category;
}
public String getEcgParams()
{
return m_EcgProperties;
}
public String getCategory()
{
return m_Category;
}
}
public class EcgResultsHolder extends ArrayList<EcgDetails> implements Parcelable
{
private static final long serialVersionUID = 663585476779879096L;
public EcgResultsHolder( )
{
}
public EcgResultsHolder(Parcel in){
readFromParcel(in);
}
#SuppressWarnings("unchecked")
public final Parcelable.Creator CREATOR = new Parcelable.Creator() {
#Override
public EcgResultsHolder createFromParcel(Parcel in) {
return new EcgResultsHolder(in);
}
#Override
public Object[] newArray(int arg0) {
return null;
}
};
private void readFromParcel(Parcel in) {
this.clear();
//First we have to read the list size
int size = in.readInt();
//Reading remember that we wrote first the Name and later the Phone Number.
//Order is fundamental
for (int i = 0; i < size; i++)
{
EcgDetails c = new EcgDetails(in.readString(), in.readString());
this.add(c);
}
}
#Override
public void writeToParcel(Parcel dest, int flags)
{
int size = this.size();
//We have to write the list size, we need him recreating the list
dest.writeInt(size);
//We decided arbitrarily to write first the Name and later the Phone Number.
for (int i = 0; i < size; i++) {
EcgDetails c = this.get(i);
dest.writeString(c.getEcgParams());
dest.writeString(c.getCategory());
}
}
#Override
public int describeContents()
{
return 0;
}
}
this is how I put it:
Bundle bundle = new Bundle();
bundle.putParcelable("EcgList", m_EcgListFromServer);
intent.putExtras(bundle);
this is how I read it on the called activity:
EcgResultsHolder m_EcgList = getIntent().getExtras().getParcelable("EcgList");
Add static qualifier to your CREATOR field. It must be static.
public static final Parcelable.Creator<EcgResultsHolder> CREATOR
= new Parcelable.Creator<EcgResultsHolder>() {
...
}

Categories

Resources