I want to create a ArrayAdapter for one spinner. So each element contain one string (which will be displayed in the spinner/list) and one value (e.g. an ID). How I can easily store a second value beside each string without implementing a new Adapter class?
Sincerely
xZise
You may create a class with two fields: one for text and another for ID. And implement toString method as returning the value of the text field. Here is an example:
package org.me.adaptertest;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ListActivity {
public static class Element {
private String mText;
private long mId;
public Element(String text, long id) {
mText = text;
mId = id;
}
public long getId() {
return mId;
}
public void setId(long id) {
mId = id;
}
public String getmText() {
return mText;
}
public void setmText(String mText) {
this.mText = mText;
}
#Override
public String toString() {
return mText;
}
}
private List<Element> mItems;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mItems = new ArrayList<MainActivity.Element>();
mItems.add(new Element("Element 1", 1));
mItems.add(new Element("Element 2", 2));
mItems.add(new Element("Element 3", 3));
setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1,
android.R.id.text1, mItems));
getListView().setOnItemClickListener(new ListView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this,
"ID is " + mItems.get(position).getId(),
Toast.LENGTH_SHORT).show();
}
});
}
}
You could use a hashmap to map an ID to each string.
Related
I have a listview activity that displays an array (ml_main) from my custom class (ml_lists) and adapter (ml_my_adapter). The array is added to via another activity. I have a 3rd activity that I want to display the item and subitem in textviews when the appropriate listitem is selected. Its this last part that I am struggling with, my intent opens the 3rd activity but the textviews are empty (dont even appear), any help really appreciated, code below...
package com.example.adam.mylists;
public class ml_lists {
// Store the name of the item
private String mItem;
// Store the name of the subitem
private String mSubItem;
// Constructor that is used to create an instance of the list_my_list object
public ml_lists(String mItem, String mSubItem) {
this.mItem = mItem;
this.mSubItem = mSubItem;
}
public String getmItem() {
return mItem;
}
public void setmItem(String mItem) {
this.mItem = mItem;
}
public String getmSubItem() {
return mSubItem;
}
public void setmSubItem(String mSubItem) {
this.mSubItem = mSubItem;
}
}
package com.example.adam.mylists;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
/*The code is now stable to generate a list which is predefined, now need to amend so that
it is populated via user input*/
public class ml_main extends AppCompatActivity {
String item;
String subitem;
ArrayList<ml_lists> userlist = new ArrayList<>();
private ListView listView;
private ml_my_adapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ml_main);
final Context context = getApplicationContext();
final FloatingActionButton addnewitem = (FloatingActionButton) findViewById(R.id.floatingActionButton);
listView = findViewById(R.id.listview_list);
userlist.add(new ml_lists("Item 1 example", "Sub item 1 example"));
mAdapter = new ml_my_adapter(this, userlist);
listView.setAdapter(mAdapter);
addnewitem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent launchactivity = new Intent(context, ml_create_new_item_screen.class);
startActivityForResult(launchactivity, 1);
overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up);
}
});
/*BELOW CODE TO SELECT ITEM FROM LISTVIEW AND OPEN IT BACK UP IN THE CREATE ITEM ACT*/
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
/*intent used to open selected activity into editor*/
Intent edititem = new Intent(context, ml_edit_existing_item_screen.class);
edititem.putExtra("item",item);
edititem.putExtra("subitem",subitem);
startActivity(edititem);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
item = data.getStringExtra("tempitem");
subitem = data.getStringExtra("tempsubitem");
userlist.add(new ml_lists(item, subitem));
mAdapter.notifyDataSetChanged();
}
if (resultCode == Activity.RESULT_CANCELED) {
Toast replacewithcode = Toast.makeText(ml_main.this, "replace with code", Toast.LENGTH_SHORT);
replacewithcode.show();
}
}
}
}
package com.example.adam.mylists;
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/*Created by Adam Garnham*/
public class ml_my_adapter extends ArrayAdapter<ml_lists> {
private Context mContext;
private List<ml_lists> mList = new ArrayList<>();
public ml_my_adapter(#NonNull Context context, #LayoutRes ArrayList<ml_lists> list) {
super(context, 0, list);
mContext = context;
mList = list;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listItem = convertView;
if (listItem == null)
listItem = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);
ml_lists currentItem = mList.get(position);
TextView mItem = (TextView) listItem.findViewById(R.id.textView_item);
mItem.setText(currentItem.getmItem());
TextView mSubItem = (TextView) listItem.findViewById(R.id.textView_subitem);
mSubItem.setText(currentItem.getmSubItem());
return listItem;
}
}
package com.example.adam.mylists;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
/**
* Created by Adam on 02/01/2018.
*/
public class ml_edit_existing_item_screen extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_existing_item_screen);
Intent edititem = getIntent();
String item = edititem.getStringExtra("item");
String subitem = edititem.getStringExtra("subitem");
TextView itemtextview = findViewById(R.id.itemtextview);
TextView subitemtextview = findViewById(R.id.subitemtextview);
itemtextview.setText(item);
subitemtextview.setText(subitem);
}
}
The problem with your code is that you are not assigning values to "item" and "subitem" in your on click listener. They are empty. You can fetch the values of current selected item by passing the selected position to userlist.
Most probably you can do something likes this.
ml_lists selectedItem=userlist.get(i);
item=selectedItem.getmItem();
subItem=selectedItem.getmSubItem();
I have a Main Activity that holds a viewpager that contains three fragments. In each fragment is a listview populated by a custom adapter. I need the ability to sort by date, name and quantity (the fields that the listview shows)
Here is my Main Activity
package com.bkbeesites.bkbeesalessheet;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.preference.PreferenceManager;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.text.Collator;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager viewPager;
private String TAG = "MainActivity";
public ArrayList<Customer> packageData;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("BK Bee Sales - Pending Sales");
setSupportActionBar(toolbar);
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String dft = preferences.getString("default", "");
if(!dft.equalsIgnoreCase(""))
{
if (dft.equals("package")){
viewPager.setCurrentItem(0);
}else if (dft.equals("nuc")){
viewPager.setCurrentItem(1);
}else if (dft.equals("queen")){
viewPager.setCurrentItem(2);
} else {
viewPager.setCurrentItem(0);
}
}
}
public void showAddCustomer(View view){
Intent intent = new Intent(this, AddCustomer.class);
startActivity(intent);
}
public void sortDate (View view){
Tab1 tab1 = new Tab1();
Tab2 tab2 = new Tab2();
Tab3 tab3 = new Tab3();
if (viewPager.getCurrentItem()==0){
tab1.sortDate();
}
}
private void setupViewPager(ViewPager viewPager){
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new Tab1(), "Packages");
adapter.addFragment(new Tab2(), "Nucs");
adapter.addFragment(new Tab3(), "Queens");
viewPager.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, Preferences.class);
startActivity(intent);
return true;
} else if (id==R.id.action_viewList){
Intent intent = new Intent(this,SalesRecord.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
Here is my Tab1 Class
package com.bkbeesites.bkbeesalessheet;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Tab1 extends Fragment {
private CustomerAdapter customerAdapter;
private static final String TAG = "fragment_tab1";
private ListView tab1ListView;
private ArrayList<Customer> packageData = new ArrayList<>();
TextView totalPackages;
TextView totalGross;
View rootView;
public Tab1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_tab1, container, false);
tab1ListView = (ListView) rootView.findViewById(R.id.tab1ListView);
totalPackages = (TextView)rootView.findViewById(R.id.totalPackages);
totalGross = (TextView)rootView.findViewById(R.id.totalGross);
return rootView;
}
#Override
public void onResume(){
super.onResume();
updatePackageList();
}
public void updatePackageList() {
packageData.clear();
tab1ListView.setAdapter(null);
int totalPackagesInt = 0;
try {
DatabaseHelper dbHelper = DatabaseHelper.getInstance(getActivity().getApplicationContext());
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM packageCustomers", null);
if (c != null) {
if (c.moveToFirst()) {
while (!c.isAfterLast()){
Customer cus = new Customer();
cus.setDate(c.getString(c.getColumnIndex("date")));
cus.setName(c.getString(c.getColumnIndex("name")));
cus.setPhone(c.getString(c.getColumnIndex("phone")));
cus.setEmail(c.getString(c.getColumnIndex("email")));
cus.setQuantity(c.getInt(c.getColumnIndex("quantity")));
cus.setNotes(c.getString(c.getColumnIndex("notes")));
cus.setId(c.getInt(c.getColumnIndex("id")));
packageData.add(cus);
totalPackagesInt = totalPackagesInt + cus.getQuantity();
c.moveToNext();
}
}
}
customerAdapter = new CustomerAdapter(this.getContext(), packageData);
tab1ListView.setAdapter(customerAdapter);
db.close();
c.close();
String totalPackagesText = totalPackagesInt + " Total Packages Reserved";
totalPackages.setText(totalPackagesText);
packageMath(totalPackagesInt);
tab1ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Customer cus = new Customer();
cus = customerAdapter.getItem(position);
int sqlId = cus.getId();
Intent intent = new Intent(getContext(), CustomerModel.class);
intent.putExtra("table", "packageCustomers");
intent.putExtra("id", sqlId);
startActivity(intent);
}
});
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
}
public void packageMath(int i){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(rootView.getContext());
String p = preferences.getString("packagePrice","");
if(!p.equals("")) {
int price = Integer.parseInt(p);
int totalGrossInt = i * price;
String grossText = "Projected Earnings: $" + String.valueOf(totalGrossInt);
totalGross.setText(grossText);
} else {
totalGross.setText("Edit Price Preferences");
}
}
public void sortDate(){
Collections.sort(packageData);
tab1ListView.setAdapter(customerAdapter);
updatePackageList();
}
}
Here is my Customer Class
package com.bkbeesites.bkbeesalessheet;
import android.support.annotation.NonNull;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Created by Brett on 12/6/2017.
*/
public class Customer implements Comparable<Customer>{
public String name;
private String email;
private String phone;
private int quantity;
private String notes;
private String date;
private int id;
private Date dateTime;
public Customer (){
this.name = "";
this.email="";
this.phone="";
this.quantity=0;
this.notes="";
this.date="";
}
public Customer (int id, String name, String phone, String email, int quantity, String notes, String date) {
this.name = name;
this.email = email;
this.phone = phone;
this.quantity = quantity;
this.notes = notes;
this.date = date;
}
public Date getDateTime() throws ParseException {
String myFormat = "MM/dd/yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
Date convertedDate = new Date();
convertedDate = sdf.parse(date);
return convertedDate;
}
public void setDateTime(Date dateTime) {
this.dateTime = dateTime;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public int compareTo(#NonNull Customer o) {
try {
return getDateTime().compareTo(o.getDateTime());
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
}
And Lastly, here is my CustomerAdapter
package com.bkbeesites.bkbeesalessheet;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Brett on 12/6/2017.
*/
public class CustomerAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
private ArrayList<Customer> mDataSource;
public CustomerAdapter(Context context, ArrayList<Customer> items) {
super();
mContext = context;
mDataSource = items;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mDataSource.size();
}
//2
#Override
public Customer getItem(int position) {
return mDataSource.get(position);
}
//3
#Override
public long getItemId(int position) {
return position;
}
//4
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get view for row item
View rowView = mInflater.inflate(R.layout.list_item, parent, false);
// Get title element
TextView nameTextView =
(TextView) rowView.findViewById(R.id.nameTextView);
TextView quantityTextView =
(TextView) rowView.findViewById(R.id.quantityTextView);
TextView dateTextView =
(TextView) rowView.findViewById(R.id.dateTextView);
Customer cus = mDataSource.get(position);
nameTextView.setText(cus.getName());
quantityTextView.setText(String.valueOf(cus.getQuantity()));
dateTextView.setText(cus.getDate());
return rowView;
}
}
Sorry if that was a lot of unnecessary code but I'm a beginner here and did not know what you would want to see.
I'm trying to call Collections.sort when the Column Title Textview "Order Date" is clicked. The Data that contains the Customer objects is stored in an SQLite database (not sure if that's pertinent).
You need to write a method in adapter class that should look like this;
public void sort(){
Collections.sort(list, new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
return o1.compareTo(o2);
}
});
notifyDataSetChanged();
}
if you don't want to create comparator every method call you can create variable of comparator.
private Comparator comp = new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
return o1.compareTo(o2);
}
});
in this case you need to change sort method like;
public void sort(){
Collections.sort(list, comp);
notifyDataSetChanged();
}
whenever you want to sort in your activity class you need to call this sort method it will sort your list and update listview.
In your activity class you need to call method like below
adapter.sort();
Also if you want to compare according to other fields. You can create variable as
private int sortType;
You should pass parameter to adapter class.
public void sort(int sortType){
this.sortType = sortType;
Collections.sort(list, comp);
notifyDataSetChanged();
}
and change the comparator field as below
private Comparator comp = new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
switch(sortType){
case 0: //By Name
return o1.getName().compareTo(o2.getName);
break;
case 1:
return o1.getQuantitiy() - o2.getQuantitiy();
break;
case 2:
return o1.compareTo(o2);
break;
default:
return 0;
}
}
});
Am looking sample program which could dynamically populating Spinner item from server using Retrofit 1.9 but still I couldn't find any sample can someone share if there is any sample regarding this requirement or else share the method.
How it should be done as am new for android bit struggling to find a solution thanks in advance!
Here is my spinneritem class:
public class MySpinnerItem {
public MySpinnerItem(){
}
public MySpinnerItem(String text, Integer value) {
Text = text;
Value = value;
}
public String getText() {
return Text;
}
public void setText(String text) {
Text = text;
}
public Integer getValue() {
return Value;
}
public void setValue(Integer value) {
Value = value;
}
public String Text;
public Integer Value;
}
Here is my spinner adapter:
package first.service.precision.servicefirst;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by 4264 on 25-11-2015.
*/
public class MySpinnerAdapter extends ArrayAdapter<MySpinnerItem> {
private Context context;
private List<MySpinnerItem> objects;
public MySpinnerAdapter(Context context, int resource, List<MySpinnerItem> objects) {
super(context, resource, objects);
this.context = context;
this.objects = objects;
}
#Override
public void add(MySpinnerItem object) {
this.objects.add(object);
}
#Override
public int getCount() {
return objects.size();
}
#Override
public MySpinnerItem getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView label = new TextView(context);
label.setText(objects.get(position).getText());
return label;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
TextView label = new TextView(context);
label.setText(objects.get(position).getText());
return label;
}
}
Here is the fragment where i set adapter for spinners:
package first.service.precision.servicefirst;
/**
* Created by 4264 on 23-11-2015.
*/
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import com.squareup.otto.Bus;
import java.util.ArrayList;
import java.util.List;
public class NewRequirements extends Fragment {
Bus bus;
MyListAdapter listAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
List<MySpinnerItem> SbuList = new ArrayList<MySpinnerItem>();
SbuList.add(new MySpinnerItem("Saravanan.R",1));
SbuList.add(new MySpinnerItem("Yogeshwaran",2));
SbuList.add(new MySpinnerItem("Sathesh",3));
SbuList.add(new MySpinnerItem("Barath",4));
SbuList.add(new MySpinnerItem("Deepak",5));
SbuList.add(new MySpinnerItem("Venkat",6));
SbuList.add(new MySpinnerItem("Meena",7));
SbuList.add(new MySpinnerItem("Ram",8));
SbuList.add(new MySpinnerItem("Jegan",9));
View view = inflater.inflate(R.layout.fragment_dialog_claim, container,
false);
final Button btnupdate;
btnupdate = (Button) view.findViewById(R.id.btnAdd);
final Spinner spSbuID = (Spinner) view.findViewById(R.id.spSbuID);
final Spinner spBuID = (Spinner) view.findViewById(R.id.spBuID);
final Spinner spSubBuID = (Spinner) view.findViewById(R.id.spSubBuID);
final Spinner spServiceCategoryID = (Spinner) view.findViewById(R.id.spServiceCategoryID);
final Spinner spServiceSubCategoryID = (Spinner) view.findViewById(R.id.spServiceSubCategoryID);
final EditText txtRequirements=(EditText)view.findViewById(R.id.txtRequirements);
MySpinnerAdapter myadapter = new MySpinnerAdapter(getActivity().getBaseContext(),android.R.layout.simple_spinner_dropdown_item,SbuList);
spSbuID.setAdapter(myadapter);
myadapter = new MySpinnerAdapter(getActivity().getBaseContext(),android.R.layout.simple_spinner_dropdown_item,SbuList);
spBuID.setAdapter(myadapter);
myadapter = new MySpinnerAdapter(getActivity().getBaseContext(),android.R.layout.simple_spinner_dropdown_item,SbuList);
spSubBuID.setAdapter(myadapter);
myadapter = new MySpinnerAdapter(getActivity().getBaseContext(),android.R.layout.simple_spinner_dropdown_item,SbuList);
spServiceCategoryID.setAdapter(myadapter);
myadapter = new MySpinnerAdapter(getActivity().getBaseContext(),android.R.layout.simple_spinner_dropdown_item,SbuList);
spServiceSubCategoryID.setAdapter(myadapter);
try{
Object o;
o = getFragmentManager().findFragmentByTag("add");
Log.v("FIND", o.toString());
}
catch (Exception ex) {
Log.v("FIND", ex.toString());
}
// add.notify();
btnupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LeadRequirementsView objLeadRequirementsView = new LeadRequirementsView();
MySpinnerItem item;
item = (MySpinnerItem)spSbuID.getSelectedItem();
objLeadRequirementsView.setSbuID(item.getValue());
objLeadRequirementsView.setSbuName(item.getText());
item = (MySpinnerItem)spBuID.getSelectedItem();
objLeadRequirementsView.setBuID(item.getValue());
objLeadRequirementsView.setBuName(item.getText());
item = (MySpinnerItem)spSubBuID.getSelectedItem();
objLeadRequirementsView.setSubBuID(item.getValue());
objLeadRequirementsView.setSubBuName(item.getText());
item = (MySpinnerItem)spServiceCategoryID.getSelectedItem();
objLeadRequirementsView.setServiceCategoryID(item.getValue());
objLeadRequirementsView.setServiceCategoryName(item.getText());
item = (MySpinnerItem)spServiceSubCategoryID.getSelectedItem();
objLeadRequirementsView.setServiceSubCategoryID(item.getValue());
objLeadRequirementsView.setServiceSubCategoryName(item.getText());
objLeadRequirementsView.setDescription(txtRequirements.getText().toString());
Add add;
add = (Add)getFragmentManager().findFragmentByTag("add");
add.updateListView(objLeadRequirementsView);
getActivity().getFragmentManager().popBackStack();
}
});
return view;
}
}
My doubt is i have done it using dummy data but i need to bind the json response from the server to my spinner how come i do this.
Below, is a sample for setting the spinner
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter;
List<String> data;
data = new ArrayList<>();
for (int i = 0; i < 20; i++)
data.add("Data " + (i + 1));
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, data);
spinner.setAdapter(adapter);
Here data is a dummy data , in your case it will be dummy data.
first create theretrofitapi interface
/**
* reCreated by goodlife on 1/11/2016.
*/
import java.util.List;
import retrofit.Callback;
import retrofit.client.Response;
import retrofit.http.Field;
import retrofit.http.FormUrlEncoded;
import retrofit.http.GET;
import retrofit.http.POST;
/**
* Created by Belal on 11/5/2015.
*/
public interface RetrofitInternetApi {
//#FormUrlEncoded, we have to write this if we want to send post data to the server.
//#POST, because we are using an HTTP Post request we have written this.
// Inside it we have the URL of the script that will be receiving the post request.
// Note that the URL is excluding the root URL. And we have defined the root URL in our MainActivity.
//#Field(“key”) String variable inside key we have to write what we have written inside $_POST[‘key’] in our script.
// And we have to specify it for all the values we are going to send.
//Callback<Response> callback it is also inside the retrofit library. It will receive the output from the server.
//But this is only an interface and the method is abstract.
//We will define the method inside fetchDepartmentName() method that is declared inside MainActivity.java.
#GET("/getDepartmentName.php")
public void getDepartmentName(Callback<List<DepartmentNoRealm>> response);
}
then create the function
private void fetchDepartmentName(){
//Creating a rest adapter
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(ROOT_URL)
.build();
//Creating an object of our api interface
RetrofitInternetApi retrofitInternetApi = restAdapter.create(RetrofitInternetApi.class);
//While the app fetched data we are displaying a progress dialog
final ProgressDialog loading = ProgressDialog.show(getActivity(), "Fetching Data", "Please wait...", false, false);
//Defining the method
retrofitInternetApi.getDepartmentName(new Callback<List<DepartmentNoRealm>>() {
#Override
public void success(List<DepartmentNoRealm> list, Response response) {
//Dismissing the loading progressbar
loading.dismiss();
Log.d("JSON LIST",list.toString());
//Storing the data in our list
departmentNoRealmList = list;
//Calling a method to show the list
showListinSpinner(); }
#Override
public void failure(RetrofitError error) {
//you can handle the errors here
}
});
}
then create a class model
package myafya.safaricom.co.ke.myafya.model.realm;
/**
* Created by 001557 on 1/13/2016.
*/
public class DepartmentNoRealm {
public int departmentID;
public String departmentName;
public String departmentURLimage;
public int getDepartmentID() {
return departmentID;
}
public void setDepartmentID(int departmentID) {
this.departmentID = departmentID;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public String getDepartmentURLimage() {
return departmentURLimage;
}
public void setDepartmentURLimage(String departmentURLimage) {
this.departmentURLimage = departmentURLimage;
}
}
now the code showList in Spinner
//Our method to show list
private void showListinSpinner(){
//String array to store all the book names
String[] items = new String[departmentNoRealmList.size()];
//Traversing through the whole list to get all the names
for(int i=0; i<departmentNoRealmList.size(); i++){
//Storing names to string array
items[i] = departmentNoRealmList.get(i).getDepartmentName();
}
//Spinner spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
//setting adapter to spinner
spinnerDepartments.setAdapter(adapter);
//Creating an array adapter for list view
}
Then SHARE IT AND MAKE IT EASY
MY JSON WAS
[
{
"departmentID": "1",
"departmentName": "Enterprise Business Unit (EBU)",
"departmentURLimage": "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSKOZmGNAA08NbHwRJrloAouWqs6r4x7BGXY4k-ULWiHuPEobHI"
},
{
"departmentID": "2",
"departmentName": "Consumer Business Unit (CBU)",
"departmentURLimage": "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQ0IAFhZ52KiG_0ck5VbBxweZWf_MEA9eRmgHAEr6CG-rUG_a2QEQ"
}
]
try {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService service = retrofit.create(APIService.class);
Call<List<People>> call = service.getYear(user_id);
call.enqueue(new Callback<List<People>>()
{
#Override
public void onResponse(Response<List<People>> response, Retrofit retrofit) {
posts = response.body();
String[] s =new String[posts.size()];
for(int i=0;i<posts.size();i++)
{
s[i]= posts.get(i).getYear();
final ArrayAdapter a = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_spinner_item, s);
a.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
Branch.setAdapter(a);
}
}
#Override
public void onFailure(Throwable t) { }
});
} catch (Exception e) {
Log.d("onResponse", "There is an error");
}
}
I have been taking this Android tutorial at CodeLearn and have faced a problem. I have searched all through the Internet and I can't seem to find any answer for this.
Here's the code for the TweetListActivity:
package com.arvisapps.aryansh.encryptit;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class TweetListActivity extends ListActivity
{
private String[] stringArray;
private ArrayAdapter tweetItemArrayAdapter;
private List<Tweet> tweets;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tweet_list);
tweets = new ArrayList<Tweet>();
for(int i = 0; i < 5 ; i++)
{
Tweet tweet = new Tweet();
tweet.setTitle("Header #" + i);
Log.d("Fuck Me", "Title captured " + tweet.getTitle());
tweet.setBody("Body text #" + i);
tweets.add(tweet);
}
tweetItemArrayAdapter = new TweetAdapter(this, tweets);
setListAdapter(tweetItemArrayAdapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
Intent intent = new Intent(this, TweetDetailActivity.class);
startActivity(intent);
}
}
Here's the code for TweetAdapter:
package com.arvisapps.aryansh.encryptit;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class TweetAdapter extends ArrayAdapter<Tweet> {
String headerSet;
private LayoutInflater inflater;
public TweetAdapter(Activity activity, List<Tweet> tweets) {
super(activity, R.layout.row_tweet, tweets);
inflater = activity.getWindow().getLayoutInflater();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.row_tweet, parent, false);
Tweet tweet = new Tweet();
headerSet = tweet.getTitle();
Log.d("Text Captured", "Text Captured "+headerSet);
((TextView)convertView.findViewById(R.id.tweetTitle)).setText(headerSet);
return convertView;
}
}
Here's an additional POJO:
package com.arvisapps.aryansh.encryptit;
public class Tweet
{
private String id;
private String title;
private String body;
public void setTitle(String title)
{
this.title = title;
}
public String getTitle()
{
return this.title;
}
public void setBody(String body)
{
this.body = body;
}
public String getBody()
{
return this.body;
}
public void setId(String id)
{
this.id = id;
}
public String getId()
{
return this.id;
}
}
The problem is that when I check the logcat for TweetListActivity it shows the right text, i.e, the text I need as an output but in TweetAdapter upon checking the Logcat the same text is nullified, i.e, it is displayed as null in the logcat. I want that the text in TweetAdapter to be what it is in the TweetListActivity.
i want to put a 2 column listview in the 2nd column of my first 2 column listview but i dont know how to and is it possible to use the same code to make it a 3 column list view?where in the first column is an image and the 2nd and 3rd column are both text i tried it but it has error... my code goes like this..
main
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class WeatherToday extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weathertoday);
ListView view = (ListView) findViewById(R.id.todaylist);
final List<MyStringPair> myStringPairList = MyStringPair.makeData(10);
MyStringPairAdapter adapter = new MyStringPairAdapter(this, myStringPairList);
view.setAdapter(adapter);
}
}
stringpairlist
import java.util.ArrayList;
import java.util.List;
public class MyStringPair {
private String columnOne;
private String columnTwo;
public MyStringPair(String columnOne, String columnTwo) {
super();
this.columnOne = columnOne;
this.columnTwo = columnTwo;
}
public String getColumnOne() {
return columnOne;
}
public void setColumnOne(String columnOne) {
this.columnOne = columnOne;
}
public String getColumnTwo() {
return columnTwo;
}
public void setColumnTwo(String columnTwo) {
this.columnTwo = columnTwo;
}
public static List<MyStringPair> makeData(int n) {
List<MyStringPair> pair = new ArrayList<MyStringPair>();
pair.add(new MyStringPair("Weather Condition", "Partly Cloudy"));
pair.add(new MyStringPair("Temperature", "30 Celcius "));
pair.add(new MyStringPair("Moisture", "Dew Point:" ));
pair.add(new MyStringPair("Wind", "Column2 "));
pair.add(new MyStringPair("Precipitation", "Column2 "));
pair.add(new MyStringPair("Condition", "Pressure:1014 mb "));
return pair;
}
}
adapter
import java.util.List;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class MyStringPairAdapter extends BaseAdapter {
private Activity activity;
private List<MyStringPair> stringPairList;
public MyStringPairAdapter(Activity activity, List<MyStringPair> stringPairList) {
super();
this.activity = activity;
this.stringPairList = stringPairList;
}
#Override
public int getCount() {
return stringPairList.size();
}
#Override
public Object getItem(int position) {
return stringPairList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = activity.getLayoutInflater();
convertView = inflater.inflate(R.layout.listrow, null);
}
TextView col1 = (TextView) convertView.findViewById(R.id.column1);
TextView col2 = (TextView) convertView.findViewById(R.id.column2);
col1.setText(stringPairList.get(position).getColumnOne());
col2.setText(stringPairList.get(position).getColumnTwo());
return convertView;
}
}
i've added a box on the column where i want another 2 column..basically i want to put two more column in the smaller box i want to divide the text into two parts so i need two columns for that but im out of ideas