How to add item to arraylist with button click? - android

Something is wrong with my code. In the application, when I "add item", it doesn't show anything, and if I am clicking somewhere around the Android application, then "item" sometimes comes.
Can somebody help me?
package com.example.proov;
import java.util.ArrayList;
import com.example.proov.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class proovin extends Activity {
private ListView LView;
ArrayList <String>ar = new ArrayList<String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LView = (ListView) findViewById(R.id.ListView01);
// Set option as Multiple Choice. So that user can able to select more the one option
LView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, ar));
LView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button b = (Button) findViewById(R.id.add_item);
final EditText d = (EditText) findViewById(R.id.title);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ar.add(d.getText().toString());
}
});
}
}

Use below code instead of your code.
public class proovin extends Activity {
private ListView LView;
ArrayList <String>ar = new ArrayList<String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LView = (ListView) findViewById(R.id.ListView01);
// Set option as Multiple Choice. So that user can able to select more
// the one option
final ArrayAdapter<String> adpt=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, ar);
LView.setAdapter(adpt);
LView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button b = (Button) findViewById(R.id.add_item);
final EditText d = (EditText) findViewById(R.id.title);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ar.add(d.getText().toString());
adpt.setNotifyOnChange(true);
LView.setAdapter(adpt);
}
});
}
}

The item is likely getting added to the ArrayList, but that is different from getting added to the ListView. You need to tell the ListView that you updated the data model so that it knows to look. See ArrayAdapter.notifyDatasetChanged()

you can use this add string to list on a button click
final String a[]={"hello","world"};
final ArrayAdapter<String> at=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a);
final ListView sp=(ListView)findViewById(R.id.listView1);
sp.setAdapter(at);
final EditText et=(EditText)findViewById(R.id.editText1);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
int k=sp.getCount();
String a1[]=new String[k+1];
for(int i=0;i<k;i++)
a1[i]=sp.getItemAtPosition(i).toString();
a1[k]=et.getText().toString();
ArrayAdapter<String> ats=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a1);
sp.setAdapter(ats);
}
});

Related

Spinner values to Database

I can't make the spinner write to the database. I read the docs about spinner, but I'm definitely doing something wrong. Can someone give some advice?
I've read many tutorials but I'm getting confused. How can I make the spinner write to database in the onClick in which I have already on input and want to add 1 more including the spinner.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class AddActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
DatabaseHelper mylogsDB;
Button btn_save;
EditText etHours;
Spinner etShift;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
etHours = (EditText) findViewById(R.id.editText);
etShift = (Spinner) findViewById(R.id.spinner);
btn_save = (Button) findViewById(R.id.btn_save);
mylogsDB = new DatabaseHelper(this);
AddData();
// Spinner click listener
etShift.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories = new ArrayList<>();
categories.add("Πρωί");
categories.add("Μεσημέρι");
categories.add("Νύχτα");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
etShift.setAdapter(dataAdapter);
}
public void onItemSelected (AdapterView <?> parent, View view,int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Έχετε επιλέξει: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
public void AddData() {
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String hours = etHours.getText().toString();
String shift = etShift.getSelectedItem().toString();
boolean insertData = mylogsDB.addData(hours, shift);
if (insertData == true) {
Toast.makeText(AddActivity.this, "Η αποθήκευση ολοκληρώθηκε επιτυχώς.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(AddActivity.this, "Ώχ,Κάτι πήγε στραβά.", Toast.LENGTH_LONG).show();
}
}
});
}
}
You need to keep the selected value from the Spinner and then use it in the method of which you use to insert into database
Also you should call AddData(); in your btn_save onClick event !
public class AddActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
DatabaseHelper mylogsDB;
Button btn_save;
EditText etHours;
Spinner etShift;
private String spinnerSelectedItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
etHours = (EditText) findViewById(R.id.editText);
etShift = (Spinner) findViewById(R.id.spinner);
btn_save = (Button) findViewById(R.id.btn_save);
mylogsDB = new DatabaseHelper(this);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddData();
}
});
// Spinner click listener
etShift.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories = new ArrayList<>();
categories.add("Πρωί");
categories.add("Μεσημέρι");
categories.add("Νύχτα");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
etShift.setAdapter(dataAdapter);
}
public void onItemSelected (AdapterView <?> parent, View view,int position, long id) {
// On selecting a spinner item
spinnerSelectedItem = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Έχετε επιλέξει: " + spinnerSelectedItem, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
public void AddData() {
String hours = etHours.getText().toString();
//spinnerSelectedItem should have a value
if(!hours.equals("") && !spinnerSelectedItem.equals("")){
boolean insertData = mylogsDB.addData(hours, spinnerSelectedItem);
if (insertData == true) {
Toast.makeText(AddActivity.this, "Η αποθήκευση ολοκληρώθηκε επιτυχώς.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(AddActivity.this, "Ώχ,Κάτι πήγε στραβά.", Toast.LENGTH_LONG).show();
}
}else{
//do something
}
}
}

Test if a user has selected an item from AutoCompleteTextView

My problem is that my code does not react accordingly whenever an user selects an item from an AutoCompleteTextView.
flag is a variable which is set to a value whenever one item from each AutoCompleteTextView has been selected. If it's set to 1, then it means it's right and it should proceed to main activity. Otherwise, a toast is displayed on click of button whose onClick calls the method callMainActivity.
There are no errors. Gradle build is successful, but clicking on that button (mentioned above) does nothing at all.
Code:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
public class Location extends AppCompatActivity {
private static int flag=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
int city = android.R.layout.simple_dropdown_item_1line;
int area = android.R.layout.simple_dropdown_item_1line;
int store = android.R.layout.simple_dropdown_item_1line;
String []city_array = getResources().getStringArray(R.array.City);
String []area_array= getResources().getStringArray(R.array.Area);
String []store_array= getResources().getStringArray(R.array.Store);
List<String> city_list= Arrays.asList(city_array);
List<String> area_list= Arrays.asList(area_array);
List<String> store_list= Arrays.asList(store_array);
ArrayAdapter<String> adapter_city = new ArrayAdapter(this,city, city_list);
ArrayAdapter<String> adapter_area = new ArrayAdapter(this, area, area_list);
ArrayAdapter<String> adapter_store = new ArrayAdapter(this, store, store_list);
final AutoCompleteTextView autocompleteView_city =
(AutoCompleteTextView) findViewById(R.id.City);
final AutoCompleteTextView autocompleteView_area =
(AutoCompleteTextView) findViewById(R.id.Area);
final AutoCompleteTextView autocompleteView_store =
(AutoCompleteTextView) findViewById(R.id.Store);
autocompleteView_area.setAdapter(adapter_area);
autocompleteView_city.setAdapter(adapter_city);
autocompleteView_store.setAdapter(adapter_store);
autocompleteView_area.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autocompleteView_area.showDropDown();
if(autocompleteView_area.getListSelection()!= ListView.INVALID_POSITION)
flag=1;
else
flag=0;
}
});
autocompleteView_city.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autocompleteView_city.showDropDown();
if(autocompleteView_area.getListSelection()!= ListView.INVALID_POSITION)
flag=1;
else
flag=0;
}
});
autocompleteView_store.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autocompleteView_store.showDropDown();
if(autocompleteView_area.getListSelection()!= ListView.INVALID_POSITION)
flag=1;
else
flag=0;
}
});
//This is the newly updated part
autocompleteView_area.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick (AdapterView<?> parent, View view, int position, long id) {
//... your stuff
if(autocompleteView_area.getListSelection()>0) {
flag = 1;
System.out.println(flag + "flag at area");
}else
flag=0;
}
});
}
public void callMainActivity(View view){
if(flag==1) {
Intent in = new Intent(getBaseContext(), MainActivity.class);
startActivity(in);
}
else
Toast.makeText(getBaseContext(),"Please select all fields properly",Toast.LENGTH_LONG);
}
}
The reason you are not seeing the Toast or changing activities, is because you are never calling callMainActivity(View view) in your code. Add this line to the end of all your OnClickListeners: callMainActivity(arg0) -- if this does not work, put some log statements in your OnClickListeners to check if they are triggering or not.
Also, if you want to trigger the call when an item from your AutoCompleteTextView result list is selected, you should use an AdapterView.OnItemClickedListener instead. This will notify you when an item is selected from the AutoCompleteTextView list, or when nothing is selected and then you can react accordingly.

Android Apptitude practice app

I want to develop an aptitude app..
for that in my text view i have to display first question .. On clicking next button i have to display second question.. on again clicking same next button third question have to be displayed.. liked that i want to display some 30 questions ..all questions should be displayed in single java file.I Tried to display two questions . but for multiple questions i could not find the code..
package com.example.asl;
import java.util.Arrays;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Aptitude extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aptitude);
Button b=(Button) findViewById(R.id.button1);
final TextView tv=(TextView) findViewById(R.id.textView1);
final String Question[]={"what is UR Name","What is ur Age","Whats ur Qualification"};
Button btnNext = (Button) findViewById(R.id.button1);
final TextView cumulos = (TextView) findViewById(R.id.textView1);
//TextView respostas = (TextView)findViewById(R.id.respostas);
Random randPhrase = new Random();
final String[] cum = {"what is UR Name","What is ur Age","Whats ur Qualification"};
//String[] resp = getResources().getStringArray(R.array.resp_cumulos);
String textout = "";
String textresp = "";
//Button btnPrevious = (Button) findViewById(R.id.yourPreviousbutton);
btnNext.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
int i = 0;
if(i<cum.length-1){
i+=1;
cumulos.setText(cum[i]);
// respostas.setText(resp[i]);
}
}
});
//btnPrevious.setOnClickListener(new OnClickListener(){
//public void onClick(View arg0) {
//if(i>0){
// i-=1;
// cumulos.setText(cum[i]);
// respostas.setText(resp[i]);
// }
// }
//});
}
}
enter code here
Initializing your counter in your onClick() is always going to reset it
Initialize it outside of onClick() and increment it in onClick() as you are.
public class Aptitude extends Activity {
int i = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aptitude);
Button b=(Button) findViewById(R.id.button1);
...
}
public void onClick(View arg0) { // rename arg0 to something meaningful
// like v or view for readibility
// int i = 0; remove this guy
if(i<cum.length-1){
i+=1;
cumulos.setText(cum[i]);
If this doesn't fix your problem then please explain what the problem is but I'm sure this part was causing you trouble.

on button click automatically remove selected spinner item

I have a spinner that show my array data list and delete button.
What I am trying to do is when I click on the delete button, it automatically deletes a selected spinner value, but I'm not certain how to do this.
In the delete button click function, deleted the selected spinner value after debugging my activity again but I want delete automatically a selected spinner value when I click on the delete button.
package quesansw.the1;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Dialog;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
public class View1 extends Activity {
SQLiteDatabase db;
ArrayAdapter adapter;
private String array_spinner[];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = openOrCreateDatabase("mydatabase.db",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
final Dialog d1 = new Dialog(this);
Window window = d1.getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
//d1.setTitle("Login");
d1.setContentView(R.layout.view);
d1.show();
Button Click = (Button) d1.findViewById(R.id.Click);
Button Save = (Button) d1.findViewById(R.id.Save);
Button Delete = (Button) d1.findViewById(R.id.Delete);
ArrayList<String> list = new ArrayList<String>();
Cursor cursor = db.rawQuery("select * from records", null);
list.add("");
if (cursor.moveToFirst())
{
do
{
list.add(cursor.getString(0));
}
while (cursor.moveToNext());
}
/*array_spinner=new String[20];
array_spinner[0]=list.get(0);*/
Spinner s = (Spinner) d1.findViewById(R.id.tittle_spinner);
adapter = new ArrayAdapter<Object>(this,android.R.layout.simple_spinner_item, list.toArray());
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
/*Save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Spinner s = (Spinner) d1.findViewById(R.id.tittle_spinner);
String str = s.getSelectedItem().toString();
System.out.println("********"+str);
Cursor cur1=db.rawQuery("select * from records where tittle='"+str+"' ",null);
cur1.moveToNext();
String str1=cur1.getString(1);
EditText ans = (EditText) d1.findViewById(R.id.text);
ans.setText(str1);
}
});*/
Delete.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Spinner s = (Spinner) d1.findViewById(R.id.tittle_spinner);
String str = s.getSelectedItem().toString();
db.execSQL("delete from records where tittle='"+str+"' ");
}
});
Click.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Spinner s = (Spinner) d1.findViewById(R.id.tittle_spinner);
String str = s.getSelectedItem().toString();
System.out.println("********"+str);
Cursor cur1=db.rawQuery("select * from records where tittle='"+str+"' ",null);
cur1.moveToNext();
String str1=cur1.getString(1);
EditText ans = (EditText) d1.findViewById(R.id.text);
ans.setText(str1);
}
});
}
}
1) Here is my activity screen shot
2) Another screen shot with spinner values:
Why are you declaring and initializing your Spinner so many times? Just do it once
public class View1 extends Activity {
SQLiteDatabase db;
ArrayAdapter adapter;
private String array_spinner[];
Spinner spinner; // Declare your spinner here
then in onCreate()
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = openOrCreateDatabase("mydatabase.db",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
spinner = (Spinner) d1.findViewById(R.id.tittle_spinner); //initialize your spinner here
final Dialog d1 = new Dialog(this);
then when you click delete button call adapter.notifyDataSetChanged() to update your Array and spinner
In deleteButton's onClickListener, remove the selected spinner value from the array data list and call onnotifydatasetChanges or again setSpinner adapter with the new array list after deletion.
public class MainActivity extends Activity {
Spinner spin;
Button delete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
delete = (Button) findViewById(R.id.button1);
spin = (Spinner) findViewById(R.id.spinner1);
final ArrayList<String> spinneritems = new ArrayList<String>();
spinneritems.add("item 1");
spinneritems.add("item 2");
spinneritems.add("item 3");
spinneritems.add("item 4");
spinneritems.add("item 5");
final ArrayAdapter<String> adp = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,spinneritems );
adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adp);
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String selectedSpinner = spin.getSelectedItem().toString();
spinneritems.remove(selectedSpinner);
adp.notifyDataSetChanged();
}
});
}
}
}
On delete button click listener add following code
Spinner s = (Spinner) d1.findViewById(R.id.tittle_spinner);
String str = s.getSelectedItem().toString();
adapter.remove(str);
adapter.notifyDataSetChanged();
s.setSelection(0);

adding checkboxes to a listview in android

When I run the following code the name of the Checkboxes are coming up as random strings (like android.widget.CheckBox#43e641b0.) Also I cannot click those added Checkboxes.
This is my java code:
package com.srk.android.rough1;
import java.util.ArrayList;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.app.ListActivity;
public class Rough1Activity extends ListActivity {
ArrayList<CheckBox> listItems=new ArrayList<CheckBox>();
ArrayAdapter<CheckBox> adapter;
private EditText taskNameEditText;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
adapter=new ArrayAdapter<CheckBox>(this, android.R.layout.simple_list_item_multiple_choice, listItems);
setListAdapter(adapter);
}
public void addItems(View v) {
taskNameEditText=(EditText)findViewById(R.id.TaskName);
String taskName=taskNameEditText.getText().toString();
CheckBox cb=new CheckBox(this);
cb.setText(taskName);
listItems.add(cb);
adapter.notifyDataSetChanged();
}
}
You are trying to display CheckBoxes as you would add an array of integers or Strings... I suggest a different approach:
public class Rough1Activity extends ListActivity {
private ArrayList<String> listItems = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private EditText taskNameEditText;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
// I like this layout, but it's your choice
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, listItems);
//adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, listItems);
setListAdapter(adapter);
// I guessed that you want a multiple choice list from your first layout choice. This is optional, you can remove it.
ListView listView = getListView();
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
// Here you only need to initialize taskNameEditText once
taskNameEditText = (EditText) findViewById(R.id.TaskName);
}
public void addItems(View v) {
// Add the current string in the EditText to the ListView
adapter.add(taskNameEditText.getText().toString());
}
}
You want to have a list of Strings and display the strings with a Checkbox. I changed your ArrayList and ArrayAdapter to String subtypes to reflex this and the layout android.R.layout.simple_list_item_checked adds the Checkbox features itself. Now the user will see the text they entered in a ListView with checkable rows.
Hope this helps!

Categories

Resources