I'm new to Asynctask and JSon.
May i know how to start to retrieve the currency rates from this site?
http://api.fixer.io/latest?base=SGD
I did look at this post but i'm not too sure how to start..
AsyncTask Android example
From the rates retrieved, i'd like to add the values into this ListView, by using a custom ListView adapter class.
Codes for xml file
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0.0dp"
android:orientation="horizontal"
android:layout_weight="0.4"
android:weightSum="1" >
<LinearLayout
android:layout_width="0.0dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="0.8" >
<TextView
android:id="#+id/convertedAmtTV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="0.00"
android:textSize="70dp"
android:gravity="right" />
<EditText
android:id="#+id/inputAmtET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="0"
android:textAlignment="textEnd" />
</LinearLayout>
<LinearLayout
android:layout_width="0.0dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="0.2">
<TextView
android:id="#+id/convertedCurrTV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SGD"
android:textSize="28dp"
android:paddingLeft="2dp"
android:paddingTop="29dp"
android:paddingBottom="19dp"
android:gravity="center_horizontal" />
<TextView
android:id="#+id/inputCurrTV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="AUD"
android:textSize="28dp"
android:paddingLeft="2dp"
android:layout_marginTop="3dp"
android:gravity="center_horizontal" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_weight="0.6"
android:layout_width="match_parent"
android:layout_height="0.0dp">
<TextView
android:text="From"
android:textSize="21dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/currencyLV"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Codes for MainActivity.class
public class MainActivity extends AppCompatActivity {
CurrencyRatesDetails crd = new CurrencyRatesDetails();
CurrencyRates cr = new CurrencyRates();
TextView inputCurrTV, convertedAmtTV;
ListView currencyLV;
EditText inputAmtET;
ArrayAdapter<String> adapter;
String[] currNameArr = crd.getNames();
String[] currCodeArr = crd.getCodes();
String[] currRateArr = crd.getRates();
String[] dbName;
String[] dbCode;
String[] dbRate;
Context context;
int index = 0;
//String[] rateCurrArr = {"AUD", "BGN", "BRL", "CAD", "CHF", "CNY"};
//double[] rateArr = {0.944, 1.2824, 2.2842, 0.96158, 0.70946, 4.8624}
Menu myMenu = null;
double amtInput, finalConversion;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
//context.deleteDatabase("currency.db");
inputAmtET = (EditText) findViewById(R.id.inputAmtET);
convertedAmtTV = (TextView) findViewById(R.id.convertedAmtTV);
inputCurrTV = (TextView) findViewById(R.id.inputCurrTV);
currencyLV = (ListView) findViewById(R.id.currencyLV);
/*for (int i = 0; i < currNameArr.length; i++) {
cr.addToDataBase(currNameArr[i], currCodeArr[i], currRateArr[i], getApplicationContext());
}*/
//cr.addToDataBase(currNameArr, getApplicationContext());
//Resources myRes = this.getResources();
//currArr = myRes.getStringArray(R.array.currencyList);
//adapter = ArrayAdapter.createFromResource(this, R.array.currencyList, android.R.layout.simple_selectable_list_item);
//adapter = new ArrayAdapter<String>(this, android.R.layout.simple_selectable_list_item, currNameArr);
//currencyLV.setAdapter(adapter);
dbName = cr.retrieveAllName(getApplicationContext());
dbCode = cr.retrieveAllCode(getApplicationContext());
dbRate = cr.retrieveAllRate(getApplicationContext());
currencyLV.setAdapter(new CustomAdapter(this, dbName, dbCode, dbRate));
currencyLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
inputCurrTV.setText(dbCode[i]);
index = i;
//Getting rate based on selected currency code
//rate = rateArr[i];
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
this.myMenu = menu;
addMenuItems(menu);
getMenuInflater().inflate(R.menu.mainmenu, menu);
return true;
}
private void addMenuItems(Menu menu) {
int index = 200;
menu.add(index, index, index, "Settings");
menu.add(index, index + 1, index + 1, "Add Custom Rate");
menu.add(index, index + 2, index + 2, "Load Default Rates");
}
public boolean onOptionsItemSelected(MenuItem item) {
//getOrder() to get Menu Item at this specific orderId
if (item.getItemId() == R.id.menu_convert) {
amtInput = Double.parseDouble(inputAmtET.getText().toString());
//finalConversion = amtInput / rate;
finalConversion = crd.conversion(amtInput, index);
//Formatting converted value to 2d.p
String finalValue = String.format("%.2f", finalConversion);
convertedAmtTV.setText(finalValue);
} else if (item.getItemId() == 201) {
Intent myIntent = new Intent(MainActivity.this, CustomXchangeRate.class);
startActivity(myIntent);
}
return true;
}
}
Custom ListView Adapter Class
public class CustomAdapter extends BaseAdapter{
String[] resultNames;
String[] resultCodes;
String[] resultRates;
Context context;
private static LayoutInflater inflater = null;
public CustomAdapter(CustomXchangeRate customXchangeRate, String[] names, String[] codes, String[] rates) {
resultNames = names;
resultCodes = codes;
resultRates = rates;
context = customXchangeRate;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public CustomAdapter(MainActivity mainActivity, String[] names, String[] codes, String[] rates) {
resultNames = names;
resultCodes = codes;
resultRates = rates;
context = mainActivity;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return resultNames.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class ViewHolder{
TextView tvName;
TextView tvCode;
TextView tvRate;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder vh = new ViewHolder();
View rowView;
rowView = inflater.inflate(R.layout.activity_custom_adapter, null);
vh.tvName = (TextView) rowView.findViewById(R.id.currencyNameTV);
vh.tvCode = (TextView) rowView.findViewById(R.id.currencyCodeTV);
vh.tvRate = (TextView) rowView.findViewById(R.id.currencyRateTV);
vh.tvName.setText(resultNames[position]);
vh.tvCode.setText(resultCodes[position]);
vh.tvRate.setText(resultRates[position]);
return rowView;
}
}
Would appreciate any help...
The best way to get this JSON inside ur app will be to use Volley :
https://developer.android.com/training/volley/simple.html
Check this link you will find what ur asking for.
Cheers
Related
I am coding a listView that gets the data from mySQL Server.
I have created the followings classes.
Class ListView. It has two contractors all in Strings. And I sat getters and setters.
I believe I have a problem with the Adapter its self. I can click on more than one option. While I have created the custom adapter in the layout as the followings:
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/RG_Adapter"
android:layoutDirection="rtl"
android:orientation="horizontal">
<RadioButton
android:id="#+id/TRIP_NAME"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"
android:textAlignment="center"
android:textSize="25sp"
android:textColor="#000000"
/>
<TextView
android:id="#+id/SUM_TRIPS"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:textColor="#000000"
android:textAlignment="center"
android:textSize="25sp" />
</RadioGroup>
I believe my problem is with the Adapter class.
I have created it like the followings:
public class TRIPS_LISTVIEW_ADAPTER extends ArrayAdapter<TRIPS_LISTVIEW> {
private Context mContext;
private ArrayList<TRIPS_LISTVIEW> mData;
private MyFunctionsClass myFunctionsClass = new MyFunctionsClass();
public TRIPS_LISTVIEW_ADAPTER (Context mContext, ArrayList<TRIPS_LISTVIEW> mData) {
super(mContext, R.layout.summary_shape_layout,mData);
this.mContext = mContext;
this.mData = mData;
}
public int getCount() {
return mData.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
LayoutInflater mInflater = (LayoutInflater)
mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.summary_shape_layout, null);
}
RadioGroup RG = (RadioGroup) convertView.findViewById(R.id.RG_Adapter);
TextView TRIP_NAME = (TextView) convertView.findViewById(R.id.TRIP_NAME);
TRIP_NAME.setTypeface(myFunctionsClass.FONT( TRIP_NAME.getContext().getAssets(),1));
TRIP_NAME.setText(myFunctionsClass.get_The_trip(mData.get(position).getTRIP_TITLE()));
TextView SUM_TRIPS = (TextView) convertView.findViewById(R.id.SUM_TRIPS);
SUM_TRIPS.setTypeface(myFunctionsClass.FONT( SUM_TRIPS.getContext().getAssets(),1));
SUM_TRIPS.setText(mData.get(position).getTRIP_COUNT());
return convertView;
}
}
The Data in my MainActivity Class are retrieved correctly. But as I mentioned I have multiple mode selection.
Try the following:
1) Demo2.class:-------------
public class Demo2 extends AppCompatActivity {
private ListView lv;
private CheckBox cb;
private Adapter adapter;
private List<Boolean> checkBoxState;
private List<String> checkBoxText;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo2);
checkBoxState = new ArrayList<>();
checkBoxText = new ArrayList<>();
for(int i = 0 ; i<10 ; i++){
if(i == 0) {
checkBoxState.add(i, true);
}else{
checkBoxState.add(i , false);
}
checkBoxText.add( i , "C" + (i+1));
}
lv = (ListView) findViewById(R.id.lv);
adapter = new Adapter(getApplicationContext() , checkBoxState , checkBoxText);
lv.setAdapter(adapter);
}
}
2) Adapter.class:------
public class Adapter extends BaseAdapter {
private Context context;
private LayoutInflater layoutInflater;
private List<Boolean> checkBoxState;
private List<String> checkBoxText;
public Adapter(Context context, List<Boolean> checkBoxState , List<String> checkBoxText) {
this.context = context;
layoutInflater = LayoutInflater.from(context);
this.checkBoxState = checkBoxState;
this.checkBoxText = checkBoxText;
}
public int getCount() {
return checkBoxState.size();
}
public Object getItem(int position) {
return checkBoxState.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final CheckBox cb_list_item;
if (convertView == null) {
if (layoutInflater != null) {
view = layoutInflater.inflate(R.layout.list_item, null);
}
}
cb_list_item = (CheckBox) view.findViewById(R.id.cb_list_item);
cb_list_item.setText(checkBoxText.get(position));
cb_list_item.setOnCheckedChangeListener(null); // mask onCheckedChangeListener()
cb_list_item.setChecked(checkBoxState.get(position));
cb_list_item.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (!b) { // already selected
compoundButton.setChecked(true);
} else { // is selected now
checkSelected(position);
}
}
});
return view;
}
private void checkSelected(int position){
try {
for (int i = 0; i < checkBoxState.size(); i++) {
checkBoxState.set(i, false);
}
checkBoxState.set(position, true);
this.notifyDataSetChanged();
}catch (Exception e){
e.printStackTrace();
}
}
}
3) demo2.xml:------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="100"
android:orientation="vertical">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/lv"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp">
</ListView>
</LinearLayout>
4) list_item.xml:----------
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="C"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:id="#+id/cb_list_item"/>
</android.support.constraint.ConstraintLayout>
5) Output:--------
i have seen many answers and i changed my code accordingly. now i am stuck with my own problem.after running this adapter , i am getting one value from list1 and only two values from list2 where both have three values.the layouts are coming fine.i don't know what is causing it and i am also not that much familiar with arrayadapter. it will be a great help. thanks in advance.
public class AxisAdapter extends ArrayAdapter<String> {
private ArrayList<String> list1 = new ArrayList<String>();
private ArrayList<String> list2 = new ArrayList<String>();
private Context context;
private final int view1 = 0;
private final int view2 = 1;
public MyAdapter(Context context, ArrayList<String> records,ArrayList<String> records1) {
super(context, 0, records);
this.context = context;
list1=records;
list2=records1;
}
public int getViewTypeCount() {
return 2;
}
public int getItemViewType(int position) {
return (position == 0) ? view1 : view2;
}
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
int viewType = getItemViewType(position);
switch (viewType) {
case view1: {
final String item = list1.get(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.abc_layout, parent, false);
}
final TextView list_Txt = (TextView) convertView.findViewById(R.id.txtDef);
Button list_But = (Button) convertView.findViewById(R.id.btnCall);
list_Txt.setText(item.replaceAll("[^A-Za-z]", " "));
list_But.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String number = item.replaceAll("[A-Za-z]", "");
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse("tel:" + number));
context.startActivity(i);
}
});
}
break;
case view2: {
final String item = list2.get(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.url_layout, parent, false);
}
final TextView list_Txt = (TextView) convertView.findViewById(R.id.txtDetail);
Button list_But = (Button) convertView.findViewById(R.id.btnVisit);
list_Txt.setText(item.replaceAll("[^A-Za-z]", " "));
list_But.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String number = item.replaceAll("[A-Za-z]", "");
Intent i = new Intent(Intent.ACTION_VIEW,Uri.parse("tel:12345"));
context.startActivity(i);
}
});
}
break;
}
return convertView;
}
}
in my activity class
public class AnActivity extends AppCompatActivity {
Toolbar toolbar;
AxisAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_axis);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if(getSupportActionBar()!= null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
ListView list = (ListView) findViewById(R.id.axisList);
String[] ussd = getResources().getStringArray(R.array.axisCode);
String[] links = getResources().getStringArray(R.array.axisLink);
ArrayList<String> myData = new ArrayList<String>();
ArrayList<String> myLinks = new ArrayList<String>();
for(int i = 0; i<ussd.length;i++) {
myData.add(ussd[i]);
}
for(int i =0;i<links.length;i++){
myLinks.add(links[i]);
}
adapter = new AxisAdapter(this,myData,myLinks);
list.setAdapter(adapter);
//adapter= new AxisAdapter(this,myLinks);
//list.setAdapter(adapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
}
and in my both layout class, there is one button and one text box.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="5dp"
android:background="#color/textboxColor">
<TextView
android:id="#+id/txtDef"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_marginLeft="2dp"
android:layout_weight="1"
android:fontFamily="#font/roboto_slab"
android:padding="5dp"
android:text="TextView"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textSize="20sp" />
<Button
android:id="#+id/btnCall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="2dp"
android:layout_weight="0"
android:fontFamily="#font/roboto_slab_bold"
android:text="Call"
android:theme="#style/PrimaryButton" />
</LinearLayout>
</LinearLayout>
another one:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="5dp"
android:background="#color/textboxColor">
<TextView
android:id="#+id/txtDetail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_marginLeft="2dp"
android:layout_weight="1"
android:fontFamily="#font/roboto_slab"
android:padding="5dp"
android:text="TextView"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textSize="20sp" />
<Button
android:id="#+id/btnVisit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="2dp"
android:layout_weight="0"
android:fontFamily="#font/roboto_slab_bold"
android:text="Visit"
android:theme="#style/PrimaryButton" />
</LinearLayout>
</LinearLayout>
Try to send some string like in below case a string to determine the type, what you are actually trying to switch between, in my case it was monthly,yearly and so on, based on that string you can use different views or maybe show alternative layouts easily.
public class incomeadapter extends ArrayAdapter {
private List<Incomemodel> getdatas;
private int resource;
String incometype;
private LayoutInflater inflater;
Context context;
public incomeadapter(Context context, int resource, List<Incomemodel> getdata, String type) {
super(context, resource, getdata);
this.context = context;
getdatas = getdata;
incometype = type;
this.resource = resource;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView t1, t2;
if (convertView == null) {
if (incometype.equals("monthly")) {
convertView = inflater.inflate(R.layout.incomemonthly_item, null);
t1 = (TextView) convertView.findViewById(R.id.text2);
t2 = (TextView) convertView.findViewById(R.id.text1);
t1.setText(getdatas.get(position).getMonths());
t2.setText(getdatas.get(position).getIncome());
}
if (incometype.equals("yearly")) {
convertView = inflater.inflate(R.layout.incomeyearly_item, null);
t1 = (TextView) convertView.findViewById(R.id.text2);
t2 = (TextView) convertView.findViewById(R.id.text1);
t1.setText(getdatas.get(position).getYear());
t2.setText(getdatas.get(position).getIncome());
}
}
return convertView;
}
}
PS. Try using recyclerview with multiple viewholders, that will make it easy i guess
Your concern:
i am getting one value from list1 and only two values from list2 where
both have three values
The problem you are facing lies in these places:
private final int view1 = 0;
private final int view2 = 1;
...
public int getItemViewType(int position) {
return (position == 0) ? view1 : view2;
}
And then you call getItemViewType method in the getView() method:
int viewType = getItemViewType(position);
The value of position ranges from 0 to the number of items in the list minus 1. So the getItemViewType() method always return 0 (view1) if position = 0, and return 1 (view2) if position = 1, 2, 3...
You then write:
switch (viewType) {
case view1: {
final String item = list1.get(position);
...
}
break;
case view2: {
final String item = list2.get(position);
...
}
break;
}
In the case view1, it is simply indicating the first item in your list with position = 0. There is only 1 item staying at position 0, so final String item = list1.get(position); is only called once, that is why it returns 1 value.
In the case view2, it is simply indicating the items at position 1, 2, 3... As you said there are 3 items in the list, the adapter will generate 3 items for the list view and case view2 will be equal to position 1 and 2. So final String item = list2.get(position); is called twice, that is why it returns 2 values.
I dont know what your next step would be because I don't understand what you expect.
Update: specific solution:
public class AxisAdapter extends ArrayAdapter<String> {
private ArrayList<String> list1;
private ArrayList<String> list2;
private Context context;
public AxisAdapter(Context context, ArrayList<String> records,ArrayList<String> records1) {
super(context, 0);
this.context = context;
list1=records;
list2=records1;
}
#Override
public int getCount() {
return list1.size() + list2.size();
}
public int getViewTypeCount() {
return 2;
}
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
if (position < list1.size()) {
final String item = list1.get(position);
convertView = LayoutInflater.from(getContext()).inflate(R.layout.abc_layout, parent, false);
final TextView list_Txt = (TextView) convertView.findViewById(R.id.txtDef);
Button list_But = (Button) convertView.findViewById(R.id.btnCall);
list_Txt.setText(item.replaceAll("[A-Za-z]", ""));
list_But.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String number = item.replaceAll("[A-Za-z]", "");
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse("tel:" + number));
context.startActivity(i);
}
});
}
else {
final String item = list2.get(position - list1.size());
convertView = LayoutInflater.from(getContext()).inflate(R.layout.url_layout, parent, false);
final TextView list_Txt = (TextView) convertView.findViewById(R.id.txtDetail);
Button list_But = (Button) convertView.findViewById(R.id.btnVisit);
list_Txt.setText(item.replaceAll("[A-Za-z]", ""));
list_But.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String number = item.replaceAll("[A-Za-z]", "");
Intent i = new Intent(Intent.ACTION_VIEW,Uri.parse("tel:12345"));
context.startActivity(i);
}
});
}
return convertView;
}
}
Here, in a listview I have added a custom row in which Checkbox and EditText are there and with a add button I just add multiple views to my listview. Adding is working perfectly but when it comes to removing part the checked items are not removing and apart from that suppose I selected two items, then two items from last deleted. I don't know whats going on with my code please help me.
Here is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
AdapterCustom customAdapter;
ArrayList<String> stringArrayList;
ListView listView;
ArrayList<Integer> listOfItemsToDelete;
AdapterCustom.ViewHolder item;
int POS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listOfItemsToDelete = new ArrayList<Integer>();
stringArrayList = new ArrayList<String>();
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
listView = (ListView) findViewById(R.id.list_item);
customAdapter = new AdapterCustom(MainActivity.this, R.layout.main, stringArrayList);
}
public void addItems(View v) {
stringArrayList.add("");
listView.setAdapter(customAdapter);
customAdapter.notifyDataSetChanged();
}
public void removeItems(View v) {
if (listOfItemsToDelete.isEmpty()) {
Toast.makeText(getBaseContext(), "No items selected.",
Toast.LENGTH_SHORT).show();
} else {
Log.i("Delete Pos", POS + "");
if (!listOfItemsToDelete.equals("")) {
for (int j = 0; j < listOfItemsToDelete.size(); j++) {
stringArrayList.remove(listOfItemsToDelete.get(j) - j);
customAdapter.notifyDataSetChanged();
}
}
}
}
AdapterCustom.java
public class AdapterCustom extends ArrayAdapter<String> {
Context context;
ArrayList<String> stringArrayList;
ArrayList<Boolean> positionArray;
MainActivity activity;
public AdapterCustom(Context context, int resourceId, ArrayList<String> arrayList) {
super(context, resourceId, arrayList);
this.context = context;
this.stringArrayList = arrayList;
positionArray = new ArrayList<Boolean>(stringArrayList.size());
for (int i = 0; i < stringArrayList.size(); i++) {
positionArray.add(false);
}
activity = new MainActivity();
}
#Override
public int getCount() {
return stringArrayList.size();
}
#Override
public String getItem(int position) {
return stringArrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public class ViewHolder {
EditText ediText;
CheckBox checkBox;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
item = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.main, null);
item.ediText = (EditText) convertView.findViewById(R.id.ediText);
item.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
item.checkBox.setTag(new Integer(position));
convertView.setTag(item);
final View finalConvertView1 = convertView;
item.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
int getPosition = (Integer) compoundButton.getTag();
POS = getPosition;
listOfItemsToDelete.add(POS);
Log.i("position after check", POS + "");
Log.i("position check array", listOfItemsToDelete + "");
}
}
});
} else {
item = (ViewHolder) convertView.getTag();
}
item.checkBox.setTag(position);
return convertView;
}
}
activity_main.xml
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="10">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal"
android:weightSum="10">
<Button
android:id="#+id/addBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:onClick="addItems"
android:text="Add New Item" />
<Button
android:id="#+id/goBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:onClick="goItems"
android:text="Go to Item" />
</LinearLayout>
<ListView
android:id="#+id/list_item"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="8"
android:drawSelectorOnTop="false"
android:visibility="visible" />
<Button
android:id="#+id/removeBtn"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:onClick="removeItems"
android:text="Remove Item" />
</LinearLayout>
main.xml
<LinearLayout
android:id="#+id/custom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dp"
android:weightSum="10">
<CheckBox
android:id="#+id/checkBox"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<EditText
android:id="#+id/ediText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="9"
android:background="#android:color/white"
android:hint="Type Anything You Want" />
</LinearLayout>
You only remove the item from the array. Try removing the item also from the list view adapter with adapter.remove(itemPosition);
What does mean
- j
in this code:
for (int j = 0; j < listOfItemsToDelete.size(); j++) {
stringArrayList.remove(listOfItemsToDelete.get(j) - j);
customAdapter.notifyDataSetChanged();
}
?
I think that:
for (String itemToRemove:listOfItemsToDelete) {
stringArrayList.remove(itemToRemove);
}
customAdapter.notifyDataSetChanged();
listOfItemsToDelete.clear();
would be appropriate.
I have a Recyclerview in my main activity and a button on a every fragment of recyclerview. When i click on that button the data just get added to listview present on another activity. And I have a button present on my action bar, when i click that button wants to see only the list view. Thanks in Advance.
My MainAcitivity code is as follows:
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
// ArrayList<Integer> images;
// ArrayList<String> imageNames, contents;
public static int[] images = {R.drawable.bengalithali,R.drawable.chikanthali,R.drawable.eggthali, R.drawable.gujratithali,
R.drawable.maharstrianthali, R.drawable.keralathali, R.drawable.rajsthanithali, R.drawable.tamilthali};
public static String[] imageNames = {"Bengali Thali","Chikan Thali", "Egg Thali", "Gujrathi Thali", "Maharashtrian Thali", "Kerala Thali",
"Rajsthani Thali", "Tamil Thali"};
public static String[] contents = {"As seen in Pic","As seen in Pic","As seen in Pic","As seen in Pic","As seen in Pic","As seen in Pic",
"As seen in Pic","As seen in Pic"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
// images = new ArrayList<>();
// images.add(R.drawable.bengalithali);
// images.add(R.drawable.chikanthali);
// images.add(R.drawable.eggthali);
// images.add(R.drawable.gujratithali);
// images.add(R.drawable.maharstrianthali);
// images.add(R.drawable.keralathali);
// images.add(R.drawable.rajsthanithali);
// images.add(R.drawable.tamilthali);
//
// imageNames = new ArrayList<>();
// imageNames.add("Bengali Thali");
// imageNames.add("Chikan Thali");
// imageNames.add("Egg Thali");
// imageNames.add("Gujrathi Thali");
// imageNames.add("Maharashtrian Thali");
// imageNames.add("Kerala Thali");
// imageNames.add("Rajsthani Thali");
// imageNames.add("Tamil Thali");
//
// contents = new ArrayList<>();
// contents.add("As seen in Pic");
// contents.add("As seen in Pic");
// contents.add("As seen in Pic");
// contents.add("As seen in Pic");
// contents.add("As seen in Pic");
// contents.add("As seen in Pic");
// contents.add("As seen in Pic");
// contents.add("As seen in Pic");
adapter = new RecyclerAdapter(MainActivity.this,images, imageNames, contents);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_button,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = new Intent(MainActivity.this, MyCartList.class);
startActivity(intent);
return super.onOptionsItemSelected(item);
}
}
My Recyclerview adapter code is as follows:
public class RecyclerAdapter extends
RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder> {
String[] imageNames, contents;
int[] images;
Context context;
public RecyclerAdapter(Context context,int[] images,String[] imageNames,String[] contents) {
this.images = images;
this.imageNames = imageNames;
this.contents = contents;
this.context = context;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_items, parent, false);
RecyclerViewHolder rvh = new RecyclerViewHolder(view);
return rvh;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
holder.productImage.setFitsSystemWindows(true);
holder.productImage.setImageResource(images[position]);
holder.productName.setText(imageNames[position]);
holder.productContent.setText(contents[position]);
}
#Override
public int getItemCount() {
return images.length;
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder{
ImageView productImage;
TextView productName, productContent, quantity;
CircleButton plusButton, minusButton;
FButton addToCartButton;
public RecyclerViewHolder(final View itemView) {
super(itemView);
productImage = (ImageView) itemView.findViewById(R.id.product_image);
productName = (TextView) itemView.findViewById(R.id.product_name);
productContent = (TextView) itemView.findViewById(R.id.product_content);
plusButton = (CircleButton) itemView.findViewById(R.id.plus_button);
minusButton = (CircleButton) itemView.findViewById(R.id.minus_button);
quantity = (TextView) itemView.findViewById(R.id.show_quantity);
addToCartButton = (FButton) itemView.findViewById(R.id.add_button);
plusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int Quantity = Integer.parseInt(quantity.getText().toString());
quantity.setText(String.valueOf(Quantity+1));
if (Quantity == 10 && plusButton.isClickable()){
quantity.setText("10");
}
}
});
minusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int Quantity = Integer.parseInt(quantity.getText().toString());
quantity.setText(String.valueOf(Quantity-1));
if (Quantity == 0 && minusButton.isClickable()){
quantity.setText("0");
}
}
});
addToCartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, MyCartList.class);
// Bundle bundle = new Bundle();
// bundle.putString("KEYONE",imageNames[getAdapterPosition()]);
// bundle.putString("KEYTWO", contents[getAdapterPosition()]);
// intent.putExtras(bundle);
intent.putExtra("KEYONE", imageNames[getAdapterPosition()]);
intent.putExtra("KEYTWO", contents[getAdapterPosition()]);
view.getContext().startActivity(intent);
Toast.makeText(context, ""+imageNames[getAdapterPosition()]+ "\n"+ contents[getAdapterPosition()], Toast.LENGTH_SHORT).show();
}
});
}
}
}
My CartList activity code is as follows:
public class MyCartList extends AppCompatActivity {
ListView myList = null;
MyListViewAdapter myListViewAdapter;
public static ArrayList<String> c = new ArrayList<>();
public static ArrayList<String> d = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_cart_list);
Intent i = getIntent();
String a = i.getStringExtra("KEYONE");
String b = i.getStringExtra("KEYTWO");
c.add(a);
d.add(b);
myList = (ListView) findViewById(R.id.my_list_view);
myListViewAdapter = new MyListViewAdapter(MyCartList.this,c,d);
myList.setAdapter(myListViewAdapter);
}
}
My listview adapter code is as follows:
public class MyListViewAdapter extends BaseAdapter{
Context mContext;
public static ArrayList<String> thaliNames, thaliContent;
SharedPreferences sharedPreferences;
public MyListViewAdapter(Context context,ArrayList<String> thaliNames, ArrayList<String> thaliContent) {
this.mContext = context;
this.thaliNames = thaliNames;
this.thaliContent = thaliContent;
}
#Override
public int getCount() {
return thaliNames.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.my_list, null);
TextView listItem = (TextView) view.findViewById(R.id.my_product_name);
listItem.setText(thaliNames + "\n" + thaliContent);
return view;
}
}
activity_main.xml is as follows:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.gaurya.carttask.MainActivity"
android:scrollbars="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
list_tems.xml is as follows:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.makeramen.roundedimageview.RoundedImageView
android:id="#+id/product_image"
android:layout_width="150dp"
android:layout_height="200dp"
app:riv_border_color="#android:color/holo_red_dark"
app:riv_corner_radius="30dip"
app:riv_border_width="2dip"
app:riv_mutate_background="true"
app:riv_tile_mode="repeat"
app:riv_oval="true"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:orientation="vertical">
<TextView
android:id="#+id/product_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_marginLeft="20dp"
android:text="Name"
android:textSize="20sp"/>
<TextView
android:id="#+id/product_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="20dp"
android:text="Name"
android:textSize="15sp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<at.markushi.ui.CircleButton
android:id="#+id/plus_button"
android:layout_width="40dip"
android:layout_height="40dip"
android:layout_marginTop="25dp"
android:layout_marginLeft="15dp"
app:cb_color="#64daed"
android:src="#drawable/plus"
/>
<TextView
android:id="#+id/show_quantity"
android:layout_width="40sp"
android:layout_height="40sp"
android:layout_marginTop="25dp"
android:text="0"
android:gravity="center"
android:textSize="30sp"
android:padding="5dp"
android:layout_marginLeft="10dp"/>
<at.markushi.ui.CircleButton
android:id="#+id/minus_button"
android:layout_width="40dip"
android:layout_height="40dip"
android:layout_marginTop="25dp"
app:cb_color="#64daed"
android:src="#drawable/negative"
android:layout_marginLeft="10dp"/>
</LinearLayout>
<info.hoang8f.widget.FButton
android:id="#+id/add_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="add to cart"
app:shadowEnabled="true"
app:shadowHeight="5dp"
app:cornerRadius="15dp"
android:layout_marginTop="17dp"/>
</LinearLayout>
</LinearLayout>
activity_my_cart_list.xml is as follows:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_my_cart_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.gaurya.carttask.MyCartList">
<ListView
android:id="#+id/my_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical">
</ListView>
</RelativeLayout>
my_list.xml is as follows:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/my_product_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
The Simplest way is, You can create one public class which can hold List of Elements and you can access it whenever you want.
Example by Using String Object
public static class MyListHolder{
static List<String> lstOfObj;
public Static MyListHolder(){
lstOfObj = new ArrayList<String>();
}
public static void addNewObject(String object){
lstOfObj.add(object);
}
public static List<String> getMyObjList(){
return lstOfObj;
}
}
Now You can use this class & methods to manage your List of Object.
I have a custom listView with three textViews. The data comes from a class with three ArrayLists, two of which are strings and the last one is an Integer. I have no problems populating and adding items to the list as I saw that when I displayed the ArrayList values on logCat via log.d, all three ArrayLists had their respectful items.
It seems to me that there is something wrong with the way I display data.
Here are the files:
list_row_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/variant"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="variant" />
<TextView
android:id="#+id/quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="quantity" />
<TextView
android:id="#+id/unit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginRight="221dp"
android:layout_toLeftOf="#+id/quantity"
android:text="unit" />
</RelativeLayout>
Here is the part in my activity_order_form.xml that has the listView element.
<RelativeLayout
android:id="#+id/relativeLayout3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_below="#+id/relativeLayout2"
android:orientation="vertical" >
<TextView
android:id="#+id/textViewVariantB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="94dp"
android:text="Variant"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textViewUnit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="123dp"
android:text="Unit"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ListView
android:id="#+id/listViewProductOrder"
android:layout_width="match_parent"
android:layout_height="350dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/textViewVariantB" >
</ListView>
</RelativeLayout>
Here is the class where the ArrayList are stored.
public class CurrentOrderClass {
private String productName;
//ArrayLists
private ArrayList<String> variantArray = new ArrayList<String>();
private ArrayList<String> unitArray = new ArrayList<String>();
private ArrayList<Integer> quantityArray = new ArrayList<Integer>();
//TODO ArrayList functions
public ArrayList<String> getUnitArray() {
return unitArray;
}
public void setUnitArray(ArrayList<String> unitArray) {
this.unitArray = unitArray;
}
public void addToUnitArray(String unit){
this.unitArray.add(unit);
}
public ArrayList<Integer> getQuantityArray() {
return quantityArray;
}
public void setQuantityArray(ArrayList<Integer> quantityArray) {
this.quantityArray = quantityArray;
}
public void addToQuantityArray(int quantity){
this.quantityArray.add(quantity);
}
public ArrayList<String> getVariantArray() {
return variantArray;
}
public void setVariantArray(ArrayList<String> variantArray) {
this.variantArray = variantArray;
}
public void addToVariantArray(String variantArray){
this.variantArray.add(variantArray);
}
}
Here is the CustomListAdapter.java file
public class CustomListAdapter extends BaseAdapter {
private ArrayList<CurrentOrderClass> listData;
private LayoutInflater layoutInflater;
public CustomListAdapter(Context context, ArrayList<CurrentOrderClass> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
holder = new ViewHolder();
holder.variantView = (TextView) convertView.findViewById(R.id.variant);
holder.unitView = (TextView) convertView.findViewById(R.id.unit);
holder.quantityView = (TextView) convertView.findViewById(R.id.quantity);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.variantView.setText(listData.get(position).getVariantArray().get(position).toString());
holder.unitView.setText(listData.get(position).getUnitArray().get(position).toString());
holder.quantityView.setText(String.valueOf(listData.get(position).getQuantityRow()));
return convertView;
}
static class ViewHolder {
TextView variantView;
TextView unitView;
TextView quantityView;
}
public void setListData(ArrayList<CurrentOrderClass> data){
listData = data;
}
}
This is part of my OrderForm.java activity, this shows the onCreate and the method that populates the listView.
public class OrderForm extends Activity {
public TextView tv;
private int variantPosition;
CustomListAdapter customListAdapter;
CurrentOrderClass currentOrder = new CurrentOrderClass();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_form);
tv = (TextView)findViewById(R.id.textViewProduct);
//set variants here
popolateItem();
//set current order listview here
ArrayList image_details = getListData();
final ListView lv1 = (ListView) findViewById(R.id.listViewProductOrder);
customListAdapter = new CustomListAdapter(this, image_details);
lv1.setAdapter(customListAdapter);
}
private ArrayList getListData() {
ArrayList results = new ArrayList();
if(currentOrder.getQuantityArray().size() > 10){
loopUntil = currentOrder.getQuantityArray().size();
for(int i = 0; i < loopUntil; i++){
currentOrder.getQuantityArray();
currentOrder.getUnitArray();
currentOrder.getVariantArray();
results.add(currentOrder);
}
}
else{
loopUntil = 10;
for(int i = 0; i < loopUntil; i++){
currentOrder.getQuantityArray().add(i);
currentOrder.getUnitArray().add("Sample text here." + i);
currentOrder.getVariantArray().add("Another sample text here" + i);
results.add(currentOrder);
}
}
return results;
}
}
When I execute a Log.d statement to display the contents of my ArrayLists, it shows that my quantityArray has elements [0, 1, 2, 3, 4, 5, 6, 7, 9].
I know I can just convert quantityArray to an ArrayList from an ArayList, but I don't want to do that.
I think there's something wrong with my CustomListAdapter.
Any thoughts?
There is no where that you actually set the view, as in, it doesn't do anything, if convertView is null, you can't call any methods of it, convertView, if its is not null, will be ViewHolder in your context, what you need to do is have an object which is extending some type of view, instantiate it, give it methods to set the values, things like that.
For example here is what I use in an adapter that displays simple messages:
public class MessageView extends RelativeLayout {
private TextView mBody;
private String mBodyString = "";
private boolean mDrawn = false;
private boolean mLocal = false;
public MessageView(Context context) {
super(context);
this.drawView();
}
public MessageView(Context context, String body) {
super(context);
mBodyString = body;
this.drawView();
}
public MessageView(Context context, String body, boolean local) {
super(context);
mBodyString = body;
mLocal = local;
this.drawView();
}
private void drawView() {
if (mDrawn)
return;
mDrawn = true;
this.removeAllViews();
LayoutInflater li = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
if(mLocal){
this.addView(li.inflate(R.layout.list_item_message_device, this, false),
params);
}else{
this.addView(li.inflate(R.layout.list_item_message_remote, this, false),
params);
}
mBody = (TextView) this.findViewById(R.id.tMessage);
mBody.setText(mBodyString);
}
public void setLocal(){
this.setLocal(true);
}
public void setLocal(boolean local){
mLocal = local;
mDrawn = false;
this.drawView();
}
public void setMessage(String body){
mBodyString = body;
mBody.setText(mBodyString);
}
}
I got it.
I changed
holder.quantityView.setText(String.valueOf(listData.get(position).getQuantityRow()));
to
holder.quantityView.setText(String.valueOf(listData.get(position).getQuantityArray().get(position)));