I have two spinners, one with a list of countries(countrySpinner) and the other with a list of provinces(stateSpinner). I want the stateSpinner to be active only if Nigeria is selected on the countrySpinner, and for the other countries on to be selectable without selecting item on the stateSpinner. My code seam to work when I select Nigerian on the countrySpinner and a corresponding state, but I GET THIS NullPointerException : println needs a message, anytime I select a country other than Nigeria on the countrySpinner. Not quite sure of what to do to get pass here. I Would appreciate any help. My code below.enter code here
public class RegisterActivity extends AppCompatActivity {
Spinner countrySpinner, stateSpinner;
List<String> countryList;
ArrayList<String> stateList;
ArrayAdapter<String> stateAdapter;
String countrySelected, stateSelected, gender;
TextInputLayout name, email, password, confirmPw;
RadioGroup genderOptionGroup;
RadioButton genderOptionBtn;
TextView countryUnCheckedWarning;
Button nextButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);nextButton = findViewById(R.id.createAccNext);
countryUnCheckedWarning = findViewById(R.id.countrySelectW);
genderOptionGroup = findViewById(R.id.gender_group);
name = findViewById(R.id.fullNameInputLayout);
email = findViewById(R.id.emailInputLayout);
password = findViewById(R.id.pwInputLayout);
confirmPw = findViewById(R.id.cpwInputLayout);
countrySpinner = findViewById(R.id.countryDropDown);
stateSpinner = findViewById(R.id.stateDropDown);
stateList = new ArrayList<String>(Arrays.asList("Select State of Residence", "Abia", "Abuja", "Adamawa", "Akwa Ibom", "Anambra",
"Bauchi", "Bayelsa", "Benue", "Borno", "Cross River", "Delta", "Ebonyi", "Enugu", "Edo",
"Ekiti", "Gombe", "Imo", "Jigawa", "Kaduna", "Kano", "Katsina", "Kebbi", "Kogi", "Kwara",
"Lagos", "Nasarawa", "Niger", "Ogun", "Ondo", "Osun", "Oyo", "Plateau", "Rivers", "Sokoto",
"Taraba", "Yobe", "Zamfara", "Territory"));
stateAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stateList);
stateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
stateSpinner.setAdapter(stateAdapter);
countryList = new ArrayList<String>();
countryList.add(0, "Select Country");
countryList.add("Gambia");
countryList.add("Sierra Leone");
countryList.add("Liberia");
countryList.add("Ghana");
countryList.add("Nigeria");
countryList.add("South Africa");
ArrayAdapter<String> countryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countryList);
countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
countrySpinner.setAdapter(countryAdapter);
// Country Spinner
countrySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (!(parent.getItemAtPosition(position).equals("Nigeria")) && !(parent.getItemAtPosition(position).equals("Select Country"))){
// Country other than Nigeria has been selected
countrySelected = parent.getItemAtPosition(position).toString();
Log.i("Country Selected is",countrySelected);
nextButton.setEnabled(true);
nextButton.setBackgroundColor(getResources().getColor(R.color.red));
}else if (parent.getItemAtPosition(position).equals("Nigeria")){
// Nigeria is selected
stateSpinner.setAlpha(1);
countrySelected = "Nigeria";
nextButton.setEnabled(false);
nextButton.setBackgroundColor(getResources().getColor(R.color.silverash));
}else {
countrySelected = "";
nextButton.setEnabled(false);
nextButton.setBackgroundColor(getResources().getColor(R.color.silverash));
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// State SpinnerGroup
stateSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getItemAtPosition(position).equals("Select State of Residence")) {
nextButton.setEnabled(false);
nextButton.setBackgroundColor(getResources().getColor(R.color.silverash));
} else {
stateSelected = parent.getItemAtPosition(position).toString();
nextButton.setEnabled(true);
nextButton.setBackgroundColor(getResources().getColor(R.color.red));
Log.i("State Selected", stateSelected);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
// Name, Email and Password Validation MTDs Below
private boolean validateName() {
String nameInpute = name.getEditText().getText().toString().trim();
// check for non empty field
if (nameInpute.isEmpty()) {
name.setError("Name Field Can't be empty");
return false;
} else if (nameInpute.length() < 5) {
name.setError("Name is too short");
return false;
} else {
name.setError(null);
return true;
}
}
private boolean validateEmail() {
String emailInpute = email.getEditText().getText().toString().trim();
// Now we check for non empty field
if (emailInpute.isEmpty()) {
email.setError("E-mail Field Can't be empty");
return false;
} else if (!Patterns.EMAIL_ADDRESS.matcher(emailInpute).matches()) {
email.setError("Please enter a valid email address");
return false;
} else {
// Remove Error and return true
email.setError(null);
return true;
}
}
private boolean validatePassword() {
String passwordInpute = password.getEditText().getText().toString().trim();
// check for non empty field
if (passwordInpute.isEmpty()) {
password.setError("Password Field Can't be empty");
return false;
} else if (passwordInpute.length() > 15) {
password.setError("Password is too long");
return false;
} else {
password.setError(null);
return true;
}
}
private boolean validateCPassword() {
String passwordInpute = password.getEditText().getText().toString().trim();
String confirmPWInpute = confirmPw.getEditText().getText().toString().trim();
// check for non empty field
if (confirmPWInpute.isEmpty()) {
confirmPw.setError("Password Field Can't be empty");
return false;
} else if (!confirmPWInpute.equals(passwordInpute)) {
confirmPw.setError("Password does not match");
return false;
} else {
password.setError(null);
return true;
}
}
public void moveToNextOnReg(View view) {
// check for or validations
if (!validateName() | !validateEmail() | !validatePassword() | !validateCPassword()) {
return; }
// put whatever result needed here
String fullName = name.getEditText().getText().toString().trim();
String emailRegistered = email.getEditText().getText().toString().trim();
String passwordRegistered = password.getEditText().getText().toString().trim();
Log.i("Name", fullName);
Log.i("E-mail", emailRegistered);
Log.i("Password", passwordRegistered);
Log.i("Country", countrySelected);
Log.i("State", stateSelected);
Log.i("Sex", gender);
Intent intentNext = new Intent(getApplicationContext(),ToNextActivity.class);
startActivity(intentNext);
}
public void backToOnboarding(View view) {
Intent intent = new Intent(getApplicationContext(), OnboardingActivity.class);
startActivity(intent);
finish();
}
public void onGenderSelected(View view){
int radioId = genderOptionGroup.getCheckedRadioButtonId();
genderOptionBtn = findViewById(radioId);
gender = genderOptionBtn.getText().toString();
Log.i("Gender Selceted", genderOptionBtn.getText().toString());
}
}
You don't seem to initialize nextButton in onCreate():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);nextButton = findViewById(R.id.createAccNext);
countryUnCheckedWarning = findViewById(R.id.countrySelectW);
genderOptionGroup = findViewById(R.id.gender_group);
name = findViewById(R.id.fullNameInputLayout);
email = findViewById(R.id.emailInputLayout);
password = findViewById(R.id.pwInputLayout);
confirmPw = findViewById(R.id.cpwInputLayout);
countrySpinner = findViewById(R.id.countryDropDown);
stateSpinner = findViewById(R.id.stateDropDown);
//here.....
nextButton = findViewById(...............);//what ever the id is in xml
Related
I'm trying to make a laundry ordering application. I've made it to the order process, at the end of the order process, the user clicks the next button to checkout the ordered results, I have successfully made the checkout results, but what I made is still in one variable string. how to put the checkout results into an array variable so that I can post the results in the form of JSONArray?
HERE IS MY ORDER ACTIVITY CODE :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_produk);
// menghubungkan variablel pada layout dan pada java
listProduk = (ListView)findViewById(R.id.list_produk);
swipeProduct = (SwipeRefreshLayout)findViewById(R.id.swipeProduct);
radioExpress = (RadioButton)findViewById(R.id.radio_express);
radioReguler = (RadioButton)findViewById(R.id.radio_regular);
tvTotal = (TextView)findViewById(R.id.total);
next = (Button)findViewById(R.id.button_next);
actionBar = getSupportActionBar();
laundry_id = getIntent().getStringExtra(TAG_LAUNDRY_ID);
// untuk mengisi data dari JSON ke dalam adapter
productAdapter = new CheckboxAdapter(this, (ArrayList<ProductModel>) productList, this);
listProduk.setAdapter(productAdapter);
listProduk.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
productAdapter.setCheckBox(position);
}
});
// menampilkan widget refresh
swipeProduct.setOnRefreshListener(this);
swipeProduct.post(new Runnable() {
#Override
public void run() {
swipeProduct.setRefreshing(true);
productList.clear();
tvTotal.setText(String.valueOf(0));
radioReguler.isChecked();
regular = true;
productAdapter.notifyDataSetChanged();
callProduct();
}
}
);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String checkbox = "";
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(dipilih);
}
});
}
private void formSubmit(String hasil){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.form_submit, null);
dialog.setView(dialogView);
dialog.setIcon(R.mipmap.ic_launcher);
dialog.setTitle("Menu Yang Dipilih");
dialog.setCancelable(true);
txtnamaProduk = (TextView) dialogView.findViewById(R.id.txtNama_produk);
txtnamaProduk.setText(hasil);
dialog.setNeutralButton("CLOSE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
}
AND HERE IS THE CODE OF THE RESULT :
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String checkbox = "";
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(dipilih);
}
});
}
in my code above, I still use the variable checkbox to accommodate all the results of the order chosen by the user. how to put all the result into array variable so i can post to server as a JSONArray? Please help me to solve this problem. because i'm still a beginner in android.
HERE IS MY ADAPTER CODE IF NEEDED :
public class CheckboxAdapter extends BaseAdapter{
private Context context;
private ArrayList<ProductModel> productItems;
ProdukLaundry produk;
public CheckboxAdapter(Context context, ArrayList<ProductModel> items, ProdukLaundry produk) {
this.context = context;
this.productItems = items;
this.produk = produk;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getCount() {
return productItems.size();
}
#Override
public Object getItem(int position) {
return productItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder viewHolder;
final ProductModel items = productItems.get(position);
if(view == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_produk, null, true);
viewHolder.checkBox = (CheckBox) view.findViewById(R.id.checkBox_productName);
viewHolder.decrease = (TextView) view.findViewById(R.id.decrease_product);
viewHolder.count = (TextView) view.findViewById(R.id.count_product);
viewHolder.increase = (TextView) view.findViewById(R.id.increase_product);
viewHolder.price = (TextView) view.findViewById(R.id.product_price);
view.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.checkBox.setText(items.getProduct_name());
viewHolder.price.setText(items.getProduct_price());
viewHolder.count.setText(String.valueOf(items.getCountProduct()));
//fungsi untuk set posisi textview + dan -
viewHolder.increase.setTag(R.integer.btn_plus_view, view);
viewHolder.increase.setTag(R.integer.btn_plus_pos, position);
viewHolder.decrease.setTag(R.integer.btn_minus_view, view);
viewHolder.decrease.setTag(R.integer.btn_minus_pos, position);
//fungsi untuk disable textview + dan - jika checkbox tidak di klik
viewHolder.decrease.setOnClickListener(null);
viewHolder.increase.setOnClickListener(null);
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
viewHolder.increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View tempview = (View) viewHolder.increase.getTag(R.integer.btn_plus_view);
TextView tv = (TextView) tempview.findViewById(R.id.count_product);
Integer pos = (Integer) viewHolder.increase.getTag(R.integer.btn_plus_pos);
int countProduct = Integer.parseInt(tv.getText().toString()) + 1;
tv.setText(String.valueOf(countProduct));
productItems.get(pos).setCountProduct(countProduct);
produk.tambah(pos);
}
});
viewHolder.decrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View tempview = (View)viewHolder.decrease.getTag(R.integer.btn_minus_view);
TextView tv = (TextView) tempview.findViewById(R.id.count_product);
Integer pos = (Integer) viewHolder.decrease.getTag(R.integer.btn_minus_pos);
int total = productItems.get(pos).getCountProduct();
if (total>0){
int countProduct = Integer.parseInt(tv.getText().toString()) - 1;
tv.setText(String.valueOf(countProduct));
productItems.get(pos).setCountProduct(countProduct);
produk.kurang(pos);
}
}
});
} else {
viewHolder.checkBox.setChecked(false);
//fungsi untuk reset jumlah harga dan produk pada checkbox
String count = viewHolder.count.getText().toString();
int jumlah = Integer.parseInt(count);
int harga = Integer.parseInt(productItems.get(position).getProduct_price());
int kurang = jumlah * harga;
viewHolder.count.setText("0");
productItems.get(position).setCountProduct(0);
produk.kurangCheckbox(kurang);
}
return view;
}
public ArrayList<ProductModel> getAllData(){
return productItems;
}
public void setCheckBox(int position){
ProductModel items = productItems.get(position);
items.setCheckbox(!items.isCheckbox());
notifyDataSetChanged();
}
static class ViewHolder{
TextView decrease, count, increase, price;
CheckBox checkBox;
}
}
just create getter setter method of Arraylist like below
CompleteOrder:-
public class CompleteOrder {
List<OrderItem> order_items;
public List<OrderItem> getOrder_items() {
return order_items;
}
public void setOrder_items(List<OrderItem> order_items) {
this.order_items = order_items;
}
}
Create another Getter setter class of variable you want to add in arraylist
OrderItem:-
public class OrderItem {
String product_name;
int product_total;
public OrderItem(String product_name, int product_total) {
this.product_name = product_name;
this.product_total = product_total;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public int getProduct_total() {
return product_total;
}
public void setProduct_total(int product_total) {
this.product_total = product_total;
}
}
Now in your onClick method just create new List as below
public void onClick(View view) {
String checkbox = "";
CompleteOrder completeOrder=new CompleteOrder();
List<OrderItem> masterProductorderCount=new ArrayList<>();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
masterProductorderCount.add(new OrderItem(holder.getProduct_name(),total);
}
}
completeOrder.setOrder_items(masterProductorderCount);
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(completeOrder);//pass object of CompleteOrder
}
});
CompleteOrder object give JSON output as below
{
"CompleteOrder":[
{
"product_name":"your product name",
"product_total":1
},
{
"product_name":"your product name",
"product_total":1
},
{
"product_name":"your product name",
"product_total":1
}
]
}
make a model that contains product name , total and etc,
then put each data into an object and put each object into an array
finally use Gson to map properties to model / list of models or the other way around.
ArrayList<Model> list = new ArrayList<>();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
Model model = new Model();
model.productName = hold.getProduct_name();
model.total = total;
list.add(model);
}
}
String jsonArray = Gson().toJson(list);
You need to create a JSONObject for each entry in the JSONArray.
As far as I can see this should take care of it:
public void onClick(View view) {
String checkbox = "";
JSONArray jsonArray = new JSONArray();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
JSONObject jsonObj = new JSONObject();
jsonObj.put("product_name", hold.getProduct_name());
jsonObj.put("product_total", total);
jsonArray.put(jsonObj);
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
String jsonArrayString = jsonArray.toString();
formSubmit(dipilih);
}
Depending on your data the resulting string from jsonArrayString would be:
{[
{"product_name":"product1","product_total":1},
{"product_name":"product2","product_total":2},
{"product_name":"product3","product_total":3}
]}
I really do not know what you intend on doing with the JSON data so I just created a String "jsonArrayString".. do what ever you need to with it.
I made a custom adapter that displays objects in Listview and an icon for each item in list. There are 3 icons that show next to an item in the list view. User can select option "Kupljeno" which changes Status of object to 1, option "Nije kupljeno" to 0 and "Nije dostupno" to 2. Each number represents a different icon, you can that in getView() function of Adapter class. The adapter class looks like this:
public class ListaAdapter extends ArrayAdapter<Proizvod> {
public ListaAdapter(Context context, ArrayList<Proizvod> proizvodi) {
super(context, 0, proizvodi);
}
public void remove(int position) {
this.remove(getItem(position));
}
public View getView(int position, View convertView, ViewGroup parent) {
Proizvod proizvod = getItem(position);
if(convertView==null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.shoppinglista_prikazproizvoda,parent,false);
TextView t = (TextView)convertView.findViewById(R.id.text1);
t.setText(proizvod.toString());
switch(proizvod.getStatus())
{
case 0:
t.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_nijekupljeno, 0);
break;
case 1:
t.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_kupljeno, 0);
break;
case 2:
t.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_nedostupno, 0);
break;
}
}
return convertView;
}
}
You can see that I set icon of each item in getView().
The user should be able to change Status of each Proizvod object with a context menu and when the user chooses object Status, the list should update and show the appropriate icon.
My Proizvod class is this:
public class Proizvod {
private int id;
private String naziv;
private int kolicina=1;
private double cijena;
private String lista;
public int status=0; //0 - nije kupljeno, 1 - kupljeno, 2 - nedostupno
public Proizvod() {
}
public Proizvod(int id, String naziv, int kolicina, double cijena, String lista, int status) {
this.id = id;
this.naziv = naziv;
this.kolicina = kolicina;
this.cijena = cijena;
this.status = status;
}
public String getNaziv() {
return naziv;
}
public void setNaziv(String naziv) {
this.naziv = naziv;
}
public int getKolicina() {
return kolicina;
}
public void setKolicina(int kolicina) {
this.kolicina = kolicina;
}
public double getCijena() { return cijena; }
public void setCijena(double cijena) {
this.cijena = cijena;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLista() { return lista; }
public void setLista(String lista) { this.lista = lista; }
public int getStatus() { return status; }
public void setStatus(int status) { this.status = status; }
#Override
public String toString() {
if(this.kolicina==1) {
return this.naziv + " ["+ this.kolicina +" komad, ukupno " + this.cijena + " kn ]";
}
else {
return this.naziv + " ["+ this.kolicina +" komada, ukupno " + this.cijena + " kn ]";
}
}
}
The code for context menu and changing icon (activity):
public class KreiranjeListeActivity extends AppCompatActivity {
ArrayList<Proizvod> ShoppingLista = new ArrayList<Proizvod>();
EditText nazivProizvoda;
EditText kolicina;
EditText cijena;
Button dodaj;
Button ocisti;
Button spremi;
ListView lista;
ListaAdapter adapter;
//Funkcija vraća ukupan iznos svih stavki u listi
public void AzurirajUkupniTrosak() {
DecimalFormat zaokruzi=new DecimalFormat("0.00");
double ukupniIznos=0;
for(Proizvod p : ShoppingLista)
{
ukupniIznos+=p.getCijena();
}
String ukupniIznosString=zaokruzi.format(ukupniIznos);
TextView prikazUkupnogIznosa=(TextView)findViewById(R.id.textView_ukupaniznos);
prikazUkupnogIznosa.setText("Ukupno: " + ukupniIznosString + " kn");
}
//Funkcija otvara meni dužim pritiskom na stavku u listi i nudi opciju brisanja stavke
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
if (v.getId() == R.id.shoppinglista2_list) {
ListView lv = (ListView) v;
AdapterView.AdapterContextMenuInfo acmi = (AdapterView.AdapterContextMenuInfo) menuInfo;
Proizvod proizvod = (Proizvod) lv.getItemAtPosition(acmi.position);
menu.add(200,201,1,"Obriši");
menu.add(200,202,2,"Kupljeno");
menu.add(200,203,3,"Nije kupljeno");
menu.add(200,204,4,"Proizvod je nedostupan");
menu.add(200,205,5,"Zatvori prozor");
}
}
//funkcija u kojoj se sa adaptera briše odabrana stavka, iste promjene se automatski primijene i na listu
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case 201:
adapter.remove(info.position);
adapter.notifyDataSetChanged();
AzurirajUkupniTrosak();
return true;
case 202:
ShoppingLista.get(info.position).setStatus(1);
adapter.notifyDataSetChanged();
return true;
case 203:
ShoppingLista.get(info.position).setStatus(0);
adapter.notifyDataSetChanged();
return true;
case 204:
ShoppingLista.get(info.position).setStatus(2);
adapter.notifyDataSetChanged();
return true;
}
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kreiranje_liste);
final DBHandler db = new DBHandler(this);
nazivProizvoda=(EditText)findViewById(R.id.nazivproizvoda_text);
kolicina=(EditText)findViewById(R.id.kolicinaproizvoda_text);
cijena=(EditText)findViewById(R.id.cijenaproizvoda_text);
dodaj=(Button)findViewById(R.id.dodaj_gumb);
ocisti=(Button)findViewById(R.id.ocisti_gumb);
spremi=(Button)findViewById(R.id.spremi_gumb);
lista=(ListView)findViewById(R.id.shoppinglista2_list);
registerForContextMenu(lista);
adapter = new ListaAdapter(this,ShoppingLista);
lista.setAdapter(adapter);
dodaj.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/////////////PROVJERE KOD UPISA ///////////////////////
if(TextUtils.isEmpty(nazivProizvoda.getText())) {
nazivProizvoda.setError("Unesite naziv proizvoda!");
return;
}
if(TextUtils.isEmpty(cijena.getText())) {
cijena.setError("Unesite cijenu!");
return;
}
if(TextUtils.isEmpty(kolicina.getText())) {
kolicina.setError("Unesite količinu!");
return;
}
if((kolicina.getText().toString()).contains(".")) {
kolicina.setError("Unesite ispravan broj!");
return;
}
/////////////PROVJERE KOD UPISA -KRAJ ////////////////////////
DecimalFormat zaokruzi=new DecimalFormat("0.00");
Proizvod p = new Proizvod();
p.setNaziv(nazivProizvoda.getText().toString());
p.setKolicina(Integer.parseInt(kolicina.getText().toString()));
String ukupnaCijena=zaokruzi.format(Float.parseFloat(cijena.getText().toString())*Integer.parseInt(kolicina.getText().toString())).toString();
p.setCijena(Double.parseDouble(ukupnaCijena)); //množi se količina sa cijenom jednog komada proizvoda
ShoppingLista.add(p);
adapter.notifyDataSetChanged();
AzurirajUkupniTrosak();
Toast.makeText(getApplicationContext(), "Proizvod dodan u listu!",
Toast.LENGTH_SHORT).show();
nazivProizvoda.setText("");
kolicina.setText("");
cijena.setText("");
}
});
ocisti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ShoppingLista.clear();
adapter.notifyDataSetChanged();
AzurirajUkupniTrosak();
Toast.makeText(getApplicationContext(), "Proizvodi su obrisani!",
Toast.LENGTH_SHORT).show();
}
});
spremi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(KreiranjeListeActivity.this);
View promptsView = li.inflate(R.layout.spremanje_liste, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
KreiranjeListeActivity.this);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText nazivListe = (EditText) promptsView
.findViewById(R.id.nazivListe);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("Spremi",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
ShoppingLista shoppinglista = new ShoppingLista(nazivListe.getText().toString(),"TEST DATUMA");
/////POSTAVLJANJE UKUPNOG IZNOSA U NOVOSTVORENU LISTU
DecimalFormat zaokruzi=new DecimalFormat("0.00");
double ukupniIznos=0;
for(Proizvod p : ShoppingLista)
{
ukupniIznos+=p.getCijena();
}
//////////////////////////////////////////////////////
db.dodajListu(shoppinglista);
for(Proizvod p : ShoppingLista)
{
db.dodajProizvod(p,nazivListe.getText().toString());
}
Intent i = new Intent(KreiranjeListeActivity.this, PopisListaActivity.class);
startActivity(i);
}
})
.setNegativeButton("Otkaži",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
}
The problem is that the icons don't change at all. The value of Status of a selected object changes but the icon doesn't, even though I use adapter.notifyDataSetChanged(); What's wrong?
Here change this in your code in your List adapter class:
First create a list of type Proizvod
List<Proizvod> dataList = new ArrayList<>();
then
public ListaAdapter(Context context, ArrayList<Proizvod> proizvodi) {
super(context, 0, proizvodi);
this.dataList = proizvodi;
}
In place of Proizvod proizvod = getItem(position);
use
Proizvod proizvod = dataList.getItem(position);
Hope it helps!!!
I am using Listview to infate the value from backend end.My problem is that whenever i Run my code i always get the size of arraylist zero in getcount method.
I have search but have not understood properly
Can Anyone Help Me out From it Please Friend
My Listview Adapter Class is
private class ListViewAdaptar extends BaseAdapter {
private LayoutInflater _inflater;
private List<Student_Location_Model> _list;
private Context _context;
String enroll_no;
String driver_id, hash;
//CharSequence[] show_data = {"Home Pick", "Home Drop", "School Pick", "School Drop", "Absent", "Other"};
CharSequence[] show_data1 = {"School Drop", "School Pick", "Home Drop", "Absent"};
String cat = "notselected";
String changed_cat, remark = "remark";
public ListViewAdaptar(Activity context, List<Student_Location_Model> lst) {
if (context != null && lst != null) {
this._context = context;
_list = lst;
_inflater = LayoutInflater.from(context);
}
}
#Override
public int getCount() {
return _list.size();
}
#Override
public Object getItem(int i) {
return _list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public View getView(final int position, View listItems, ViewGroup parent) {
final ViewHolder holder;
SharedPreferences sharedPreferences = _context.getSharedPreferences(_context.getString(R.string.BUS_DETAILS), Context.MODE_PRIVATE);
hash = sharedPreferences.getString(_context.getString(R.string.HASH), "");
driver_id = sharedPreferences.getString(_context.getString(R.string.DRIVER_ID), "");
// if (listItems == null) {
listItems = _inflater.inflate(R.layout.listview_adapter_design, null);
holder = new ViewHolder();
holder.txt_loc_id = (TextView) listItems.findViewById(R.id.location_id);
holder.txt_enroll_no = (TextView) listItems.findViewById(R.id.textview_student_enroll);
holder.txt_student_name = (TextView) listItems.findViewById(R.id.textview_student_name);
holder.select_data = (TextView) listItems.findViewById(R.id.select_data);
holder.checkbox_select_one = (CheckBox) listItems.findViewById(R.id.checkbox_select_one);
final Student_Location_Model locationModel = _list.get(position);
holder.txt_student_name.setText(locationModel.getStudent_name());
holder.txt_enroll_no.setText(locationModel.getEnroll_num());
holder.txt_loc_id.setText(locationModel.getLocation_name());
holder.checkbox_select_one.setChecked(locationModel.isItemCheck());
holder.select_data.setText(locationModel.getStudent_track_status());
holder.checkbox_select_one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (((CheckBox) view).isChecked()) {
Student_Location_Model model = _list.get(position);
model.setItemCheck(true);
notifyDataSetChanged();
} else {
Student_Location_Model model = _list.get(position);
model.setItemCheck(false);
notifyDataSetChanged();
}
String selected_student = "";
for (int i = 0; i < _list.size(); i++) {
Student_Location_Model locationModel1 = _list.get(i);
if (locationModel1.isItemCheck()) {
selected_student = locationModel1.getEnroll_num() + " , " + selected_student;
}
}
checkbox_select_all.setChecked(false);
Log.e("String of Students :- ", selected_student);
selected_enroll_no.setText(selected_student);
}
});
if (holder.checkbox_select_one.isChecked()) {
SharedPreferences preferences = New_Student_Details_Location.this.getSharedPreferences(getString(R.string.LATEST_SELECTION), MODE_PRIVATE);
String new_selection = preferences.getString(getString(R.string.SELECTED_VALUE), "");
holder.select_data.setText(new_selection);
if (new_selection.equalsIgnoreCase("")) {
holder.select_data.setText("Select");
}
}
holder.select_data.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final AlertDialog.Builder builder;
builder = new AlertDialog.Builder(_context);
builder.setTitle("Select One");
builder.setSingleChoiceItems(show_data1, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i) {
case 0:
cat = (String) show_data1[i];
break;
case 1:
cat = (String) show_data1[i];
//holder.select_data.setText(cat);
break;
case 2:
cat = (String) show_data1[i];
// holder.select_data.setText(cat);
break;
case 3:
cat = (String) show_data1[i];
// holder.select_data.setText(cat);
break;
}
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
/* if (cat.equalsIgnoreCase("Home Pick")) {
holder.select_data.setText(cat);
//newcat = holder.select_data.getText().toString();
changed_cat = cat.replace("Home Pick", "home_pickup");
enroll_no = holder.txt_enroll_no.getText().toString();
Toast.makeText(_context, "You have Selected " + cat, Toast.LENGTH_SHORT).show();
new BackgroundJob().execute();
cat = "notselected";
}*/
if (cat.equalsIgnoreCase("Home Drop")) {
holder.select_data.setText(cat);
//newcat = holder.select_data.getText().toString();
changed_cat = cat.replace("Home Drop", "home_drop");
enroll_no = holder.txt_enroll_no.getText().toString();
StyleableToast.makeText(_context, "You Selected " + cat, Toast.LENGTH_SHORT, R.style.StyledToast).show();
new BackgroundJob().execute();
cat = "notselected";
} else if (cat.equalsIgnoreCase("School Pick")) {
holder.select_data.setText(cat);
//newcat = holder.select_data.getText().toString();
changed_cat = cat.replace("School Pick", "school_pickup");
enroll_no = holder.txt_enroll_no.getText().toString();
StyleableToast.makeText(_context, "You Selected " + cat, Toast.LENGTH_SHORT, R.style.StyledToast).show();
new BackgroundJob().execute();
cat = "notselected";
} else if (cat.equalsIgnoreCase("School Drop")) {
holder.select_data.setText(cat);
//newcat = holder.select_data.getText().toString();
changed_cat = cat.replace("School Drop", "school_drop");
enroll_no = holder.txt_enroll_no.getText().toString();
StyleableToast.makeText(_context, "You Selected " + cat, Toast.LENGTH_SHORT, R.style.StyledToast).show();
new BackgroundJob().execute();
cat = "notselected";
} else if (cat.equalsIgnoreCase("Absent")) {
holder.select_data.setText(cat);
//newcat = holder.select_data.getText().toString();
changed_cat = cat.replace("Absent", "absent");
enroll_no = holder.txt_enroll_no.getText().toString();
StyleableToast.makeText(_context, "You Selected " + cat, Toast.LENGTH_SHORT, R.style.StyledToast).show();
new BackgroundJob().execute();
cat = "notselected";
}
/* else if (cat.equalsIgnoreCase("Other")) {
holder.select_data.setText(cat);
//newcat = holder.select_data.getText().toString();
changed_cat = cat.replace("Other", "other");
enroll_no = holder.txt_enroll_no.getText().toString();
AlertDialog.Builder builder1 = new AlertDialog.Builder(_context);
final EditText edt_remark = new EditText(_context);
builder1.setTitle("Reason");
builder1.setMessage("Please enter a valid reason");
builder1.setView(edt_remark);
builder1.setPositiveButton("SAVE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
remark = edt_remark.getText().toString();
new BackgroundJob().execute();
}
});
builder1.show();
cat = "notselected";
}*/
else if (cat.equalsIgnoreCase("notselected")) {
StyleableToast.makeText(_context, "Please Select One", Toast.LENGTH_SHORT, R.style.StyledToast_one).show();
}
}
});
builder.setCancelable(false);
builder.show();
}
});
listItems.setTag(holder);
listItems.setTag(R.id.checkbox_select_one, holder.checkbox_select_one);
holder.checkbox_select_one.setTag(position);
return listItems;
}
#Override
public int getItemViewType(int position) {
return position;
}
private class ViewHolder {
TextView txt_loc_id;
TextView txt_enroll_no;
TextView txt_student_name;
TextView select_data;
CheckBox checkbox_select_one;
}
private class BackgroundJob extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
return JsonParser.makeHttpUrlConnectionRequest(API.Update_Student_Details, dataparams());
}
private List<NameValuePair> dataparams() {
ArrayList<NameValuePair> parameters = new ArrayList<>();
parameters.add(new BasicNameValuePair("hash", hash));
parameters.add(new BasicNameValuePair("driver_id", driver_id));
parameters.add(new BasicNameValuePair("enroll_num", enroll_no));
parameters.add(new BasicNameValuePair("track_status", changed_cat));
parameters.add(new BasicNameValuePair("remark", remark));
Log.e("Parematers", ":" + parameters);
return parameters;
}
#Override
protected void onPostExecute(String httpResponse) {
JSONObject responseParameters;
if (httpResponse == null) {
StyleableToast.makeText(_context, "No Internet Connection", Toast.LENGTH_SHORT, R.style.StyledToast_one).show();
} else {
try {
responseParameters = new JSONObject(httpResponse);
String status = responseParameters.getString("status");
if (status.equalsIgnoreCase("success")) {
StyleableToast.makeText(_context, "Saved Successfully.", Toast.LENGTH_SHORT, R.style.StyledToast).show();
} else {
StyleableToast.makeText(_context, "Status Already Updated", Toast.LENGTH_SHORT, R.style.StyledToast_one).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
My Class for setting the adapter
public class Student_Location_Model {
String location_id, location_name, enroll_num, student_name, student_track_status;
boolean isItemCheck;
public Student_Location_Model(String location_id, String location_name,
String enroll_num, String student_name,
boolean isItemCheck, String student_track_status) {
this.location_id = location_id;
this.location_name = location_name;
this.enroll_num = enroll_num;
this.student_name = student_name;
this.isItemCheck = isItemCheck;
this.student_track_status = student_track_status;
}
public String getStudent_track_status() {
return student_track_status;
}
public void setStudent_track_status(String student_track_status) {
this.student_track_status = student_track_status;
}
public boolean isItemCheck() {
return isItemCheck;
}
public void setItemCheck(boolean itemCheck) {
isItemCheck = itemCheck;
}
public String getLocation_id() {
return location_id;
}
public void setLocation_id(String location_id) {
this.location_id = location_id;
}
public String getLocation_name() {
return location_name;
}
public void setLocation_name(String location_name) {
this.location_name = location_name;
}
public String getEnroll_num() {
return enroll_num;
}
public void setEnroll_num(String enroll_num) {
this.enroll_num = enroll_num;
}
public String getStudent_name() {
return student_name;
}
public void setStudent_name(String student_name) {
this.student_name = student_name;
}
}
I'm new to Java and Android and am trying to figure out how to write a ListView and load the ListView from where it is saved.
I have ListView and each item on the ListView has a string and bool that changes if a checkbox for the item is checked or unchecked. I have a working method to add items to the ListView and am now trying to figure out how to write the ListView to a textfile.
I got some code for saving the ListView by clicking a menu item and them I'm trying to load it when I re-run the program in my OnCreate, but nothing is loading. I'm not sure if its the write or load that is not working or both.
Here is a class I made that works with my ListView.
Item.java
public class Item {
String name;
boolean isChecked = false;
public Item(String name) {this.name = name;}
public Item(String name, boolean checked){
this.name = name;
this.isChecked = checked;
}
#Override
public String toString(){
return name;
}
}
Here is my MainActivity.java that includes my saveList() and readFile()
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getName();
ArrayList<Item> items = new ArrayList<>();
private ListView lv;
private static final String sFile = "Saved.txt";
protected ListView getListView() {
if (lv == null) {
lv = (ListView) findViewById(android.R.id.list);
}
return lv;
}
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
protected ListAdapter getListAdapter() {
ListAdapter adapter = getListView().getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
return ((HeaderViewListAdapter) adapter).getWrappedAdapter();
} else {
return adapter;
}
}
private void deleteList()
{
if (!items.isEmpty())
{
items.clear();
}
lv.invalidateViews();
}
private void deleteCheckedItems()
{
SparseBooleanArray checked = lv.getCheckedItemPositions();
for(int i = 0; i < lv.getCount(); i++)
{
if (checked.get(i)==true)
{
items.remove(i);
}
lv.invalidateViews();
}
lv.clearChoices();
}
private void saveList(ArrayList<Item> itemlist) {
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(sFile, 0));
int iCnt = 0;
String allstring = "";
for (Item s : items)
{
if (s.isChecked)
{
iCnt++;
if (iCnt < items.size()) {
String thisstring;
thisstring = s.name + "\r\n";
out.write(thisstring);
allstring += thisstring;
} else {
String thisstring;
thisstring = s.name;
out.write(thisstring);
allstring += thisstring;
}
}
}
out.close();
//Toast.makeText(activity, allstring + " Written", duration).show();
}
catch (java.io.FileNotFoundException e)
{
}
catch (Exception ex)
{
// Toast.makeText(activity, "Write Exception : " + ex.getMessage(), duration).show();
}
}
public String readFile(ArrayList<Item> itemsList)
{
String sRet = "Nothing";
try
{
InputStream is = openFileInput(sFile);
if (is != null)
{
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String sLine;
StringBuffer sb = new StringBuffer();
while ((sLine = br.readLine()) != null)
sb.append(sLine + "\r\n");
is.close();
sRet = sb.toString();
// Toast.makeText(Toast.LENGTH_LONG).show();
}
}
catch (java.io.FileNotFoundException e)
{
}
catch (Exception ex)
{
// Toast.makeText(activi"Read Exception" + ex.getMessage(), Toast.LENGTH_LONG).show();
}
return sRet;
}
private void addItemDialog()
{
LayoutInflater inflater = LayoutInflater.from(this);
final View addView = inflater.inflate(R.layout.add, null);
new AlertDialog.Builder(this)
.setTitle("Add Item")
.setView(addView)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EditText txtAdd = (EditText) addView.findViewById(R.id.etInput);
String sItem = (txtAdd).getText().toString();
items.add(new Item(sItem));
for (int i = 0; i < items.size(); i++)
{
lv.setItemChecked(i, items.get(i).isChecked);
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
}).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setListAdapter(new ArrayAdapter<Item>(this, android.R.layout.simple_list_item_multiple_choice, items));
lv = this.getListView();
for (int i = 0; i < items.size(); i++)
{
lv.setItemChecked(i, items.get(i).isChecked);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
readFile(items);
}
#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) {
switch(item.getItemId()){
case R.id.add_item:
addItemDialog();
return true;
case R.id.clear_all:
deleteList();
return true;
case R.id.clear_checked:
deleteCheckedItems();
return true;
case R.id.write:
saveList(items);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
put your oncreate method above after declaration that means after this line
private static final String sFile = "Saved.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.......
.......
//your code
}
//other method
Read Android activity lifecyle for better understanding
I dont know where the problem is because everything is fine. There are no errors showing or nothing. I even did a System.out.println() on the adapter data to get its count and it shows. The problem is, the listview is not showing anything.
Here is my code: (Any pointers / help will be really appreciated) The adapter that needs help is answers_adapter
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_question);
c = this;
//define view controls
question = (EditText) findViewById(R.id.question);
answers = (ListView) findViewById(R.id.answers);
type = (Spinner) findViewById(R.id.type);
add_choice = (Button) findViewById(R.id.add_choice);
info = (TextView) findViewById(R.id.info);
optional = (CheckBox) findViewById(R.id.optional);
//default data preparation
add_choice.setEnabled(false);
final List<String> types = new ArrayList<>();
types.add("Free Text");
types.add("Free Number");
types.add("Date");
types.add("MultiChoice Text");
types.add("MultiChoice Images");
ArrayAdapter<String> types_adapter = new ArrayAdapter<String>(c,android.R.layout.simple_spinner_item, types);
types_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
type.setAdapter(types_adapter);
type.setSelection(0);
type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = types.get(position).trim().toLowerCase();
if (selection.contains("multi")) {
add_choice.setEnabled(true);
} else {
add_choice.setEnabled(false);
}
//reset the answer choices
answers_adapter.clear();
answers_adapter.notifyDataSetChanged();
info.setText("Answer Choices (" + answers_adapter.getCount() + ")");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
type.setSelection(0);
}
});
answers_data = new ArrayList<>(); //Initialize array adapter data
//if this is a question edit, add question info
String editpredata = getIntent().getStringExtra(NewQuestions.EXTRA_MESSAGE);
editpredata_pos = Integer.parseInt(editpredata);
if (editpredata_pos > -1){
CustomListData epcd = NewQuestions.questions_adapter.getItem(editpredata_pos);
String epcd_QJSON = epcd.getMoreinfo();
try {
JSONObject epcdqobj = new JSONObject(epcd_QJSON);
question.setText(epcdqobj.getString("question"));
int types_pos = 0;
for (int i = 0;i<types.size();i++){
String type_str = types.get(i);
if (type_str.trim().toLowerCase().matches(epcdqobj.getString("type").trim().toLowerCase())){
types_pos = i;
}
}
type.setSelection(types_pos);
optional.setChecked(epcdqobj.getString("optional").toLowerCase().trim().matches("yes"));
if (epcdqobj.getString("multichoice_type").trim().length() > 0){
JSONArray epcdmulti = epcdqobj.getJSONArray("multichoices");
for (int i=0;i<epcdmulti.length();i++){
JSONObject spobj = epcdmulti.getJSONObject(i);
CustomListData epcdmcd = new CustomListData();
int epcdmcd_imgpos = isNumeric(spobj.getString("image").trim()) ? Integer.parseInt(spobj.getString("image")) : -1;
epcdmcd.setIcon(epcdmcd_imgpos < 0 ? R.drawable.choice : NewQuestion.ds[epcdmcd_imgpos]);
epcdmcd.setItem(spobj.getString("choice"));
epcdmcd.setDesc(spobj.getString("points"));
epcdmcd.setMoreinfo(spobj.getString("image").trim());
answers_data.add(epcdmcd);
}
}
}
catch (Exception e){
System.out.println("INTERNAL ERROR: --> (PREPARING DATA) " + t.exceptionString(e));
}
}
System.out.println(answers_data.size());
answers_adapter = new CustomListAdapter(((Activity)c), answers_data);
answers.setAdapter(answers_adapter);
answers.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
showDialogChoice("", position);
}
});
add_choice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String selection = type.getSelectedItem().toString().toLowerCase().trim();
if (selection.contains("image")) {
showDialogChoice("image", -1);
} else {
showDialogChoice("", -1);
}
}
});
}
CustomListData
public class CustomListData {
private int icon;
private String item;
private String desc;
private String moreinfo;
public CustomListData(){};
public CustomListData(int icon, String item, String desc){
super();
this.icon = icon;
this.item = item;
this.desc = desc;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public int getIcon() {
return icon;
}
public void setIcon(int icon) {
this.icon = icon;
}
public String getMoreinfo() {
return moreinfo;
}
public void setMoreinfo(String moreinfo) {
this.moreinfo = moreinfo;
}
}