I am using Android Studio, I have an activity with a list, when I add items to the list after filling a textbox and clicking a button the items show, but when I try to add items to the list from an SQL query the list does not show the items.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent d = getIntent();
setContentView(R.layout.activity_add_group);
String choosengroup = d.getStringExtra("chosen");
groupn = (EditText) findViewById(R.id.gname);
soldiern = (EditText) findViewById(R.id.soldiername);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
final Button savebutton = (Button) findViewById(R.id.savegroup);
final Button addbutton = (Button) findViewById(R.id.addsoldier);
final DatabaseHelper db;
db = new DatabaseHelper(getApplicationContext());
setListAdapter(adapter);
if(!choosengroup.equals("")){
groupn.setText(choosengroup);
list=getAllsoldiers(choosengroup,db);
// Log.d("list",list.toString());
onContentChanged ();
}
savebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
db.createGroup(new Groups(groupn.getText().toString())); //Creates a group in Groups table
// Creates a new table for the specific group
db.getWritableDatabase().execSQL(" CREATE TABLE `Group_"+groupn.getText().toString()+"` (`id` INTEGER PRIMARY KEY AUTOINCREMENT ,`name` TEXT,`ghours` INTEGER DEFAULT "+'"'+"0"+'"'+",`ahours`INTEGER DEFAULT "+'"'+"0"+'"'+", `khours` INTEGER DEFAULT "+'"'+"0"+'"'+");");
for (String name: list) {
// Log.d("names:",name.toString());
db.getWritableDatabase().execSQL("INSERT INTO `Group_"+groupn.getText().toString()+"` (name) VALUES('"+name+"');");
}
Intent act2 = new Intent(view.getContext(),ChooseGroup.class);
startActivity(act2);
}
});
addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// soldier.add(new Soldiers(soldiern.getText().toString()));
list.add(soldiern.getText().toString());
soldiern.setText("");
//setListAdapter(adapter);
Log.d("list",list.toString());
onContentChanged ();
}
});
The addbutton.setOnClickListener add items and they are shown on the list.
But this :
if(!choosengroup.equals("")){
groupn.setText(choosengroup);
list=getAllsoldiers(choosengroup,db);
// Log.d("list",list.toString());
onContentChanged ();
}
Does not show the items on the listview.
Any idea why?
Thanks in advance.
Try
list.addAll(getAllsoldiers(choosengroup,db));
instead of
list=getAllsoldiers(choosengroup,db);
My thinking is that the assignment:
list=getAllsoldiers(choosengroup,db);
changes the value of the reference held in list from the original list to a new reference, and the adapter is still using the reference to the original list.
ie when you created the adapter, you passed in the value of the reference to the original list
when you did the assignment, you just changed the value of reference stored in list, but the adapter is still holding the pointer to the original list
using addAll() will add the items to the original list which is still being referenced by your adapter.
Related
I have a ListView that displays an ArrayList that is dynamically created using an adapter. However, certain elements of each list item view are calculated based on previous item values. I am using Intents to open another activity where the user can edit a selected list item, and the updates are passed back to the main activity. In the main activity I've placed the getIntent, and the associated setters, after the ArrayList is generated and before the adapter. When the main activity is first created the adapter correctly calculates all list view items. But when the user accepts updates in the edit activity and returns to the main activity, only the selected list item is updated. Having the entire list cycle through and update would be fine (it will never be a very long list), but I'm a little surprised that only the selected list item is getting updated. I expected that either the adapter would run as it does when the activity is first created and all items would get updated, or that it wouldn't run at all and none would get updated.
public class MainActivity extends AppCompatActivity {
private final Context thisContext = MainActivity.this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView planListView = findViewById(R.id.plan_listview);
final ArrayList<ItemProfile> planSteps = BuildPlan();
if(getIntent().getExtras() != null)
{
int stepNumber = getIntent().getIntExtra("stepNumber", 0);
ItemProfile thisStep = (ItemProfile) getIntent().getSerializableExtra("itemProfile");
planSteps.get(stepNumber-1).setDepth(thisStep.getDepth());
planSteps.get(stepNumber-1).setTime(thisStep.getTime());
planSteps.get(stepNumber-1).setInterval(thisStep.getInterval());
}
ItemsListAdapter planAdapter = new ItemsListAdapter(this, planSteps);
planListView.setAdapter(planAdapter);
planListView.setOnItemClickListener(
new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l)
{
int index = pos-1;
Intent i = new Intent(thisContext, EditItemActivity.class);
i.putExtra("stepNumber", pos);
i.putExtra("stepProfile", planSteps.get(index));
if (index > 0)
{
i.putExtra("groupStart", planSteps.get(index-1).getGroupEnd());
}
startActivity(i);
}
}
);
}
}
Update... I've added the mainActivity code. It creates an ArrayList plan (I'm using a BuildPlan method to populate a dummy plan while I'm developing) then checks for an intent that is returning an updated plan step. If an intent exists the specified step is updated in the plan. The list adapter is then created and set. Finally the clickListener is created and set.
I've done something relatively similar but I used dynamic spinners and listviews from a database.
Here is the code. Basically you invalidate the list view, reset the data and call notifyDataSetChanged() on the adapter.
public ListView lv;
Spinner suburbSpinner;
ArrayAdapter<String> suburbAdapter;
ArrayList<String> suburbs = new ArrayList<>();
ArrayList<Resource> resources = new ArrayList<>();
ArrayAdapter<Resource> arrayAdapter;
public void updateList(String type, String suburb, String businessType, int suburbPos) {
DatabaseHelper db = new DatabaseHelper(this, "fairCanberraDB", null, 1);
lv = findViewById(R.id.list);
// Reset suburb spinner, get new list view resources.
lv.invalidateViews();
resources = db.resourceQuery(type, suburb, businessType);
System.out.println("resource: " + resources);
ArrayList<Resource> suburbQuery = db.resourceQuery(type, "All", businessType);
Spinner suburbSpinner = findViewById(R.id.suburbSpinner);
suburbs.clear();
suburbs.add("All");
for (int x = 0; x < suburbQuery.size(); x++) {
if (suburbs.contains(suburbQuery.get(x).getSuburb())) {
continue;
} else {
suburbs.add(suburbQuery.get(x).getSuburb());
}
}
db.close();
suburbAdapter.notifyDataSetChanged();
arrayAdapter.notifyDataSetChanged();
ArrayAdapter<Resource> arrayAdapter = new ArrayAdapter<Resource>(
this,
android.R.layout.simple_list_item_1,
resources);
lv.setAdapter(arrayAdapter);
if(suburbPos < suburbSpinner.getCount())
{ suburbSpinner.setSelection(suburbPos);}
setSpinnerListener(suburbSpinner);
}
// Register listener for a spinner
public void setSpinnerListener(Spinner spinner)
{
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
Spinner typeSpinner = (Spinner) findViewById(R.id.typeSpinner);
Spinner businessTypeSpinner = (Spinner) findViewById(R.id.businessTypeSpinner);
Spinner suburbSpinner = (Spinner) findViewById(R.id.suburbSpinner);
String businessType = businessTypeSpinner.getSelectedItem().toString();
if(businessType.contains("Private"))
{
businessType = "private user";
}
updateList(typeSpinner.getSelectedItem().toString(), suburbSpinner.getSelectedItem().toString(),
businessType, suburbSpinner.getSelectedItemPosition());
}
I'm doing a grocery list app and i want all the list to be sort by department (Meat, fruit, bakery etc.). I try to do the first list which is the fruit list everything is working i can add item the checkbox is there i can use it no problem. the problem is that when i check items and i press the previous button on the phone and then i click back on the button to access the fruit list the items are not checked anymore.
I use the android.R.layout.simple_list_item_multiple_choice for the checkbox.
I try to use onSaveinstance but i cant get it to work ...i would like to save it without using SQl now my array are save in a file for my list.
I eard about shared preference but i'm not sure its what i'm looking for and i would need some help to understand how to use it.
This is the class that call the activity where the fruit list is displayed with the checkbox:
public class SelectDoActivity extends AppCompatActivity {
/*Set the instance variable*/
private ImageButton btn_FruitList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_select_do);
btn_FruitList = (ImageButton) findViewById (R.id.btn_FruitList);
/*Create the method that call the activity*/
btn_FruitList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFruitList_Activity();
}
});
}
public void openFruitList_Activity() {
Intent intent = new Intent (this, FruitList_Activity.class);
startActivity(intent);
}
}
This is the class that display the fruit list with the check mark.
public class FruitList_Activity extends AppCompatActivity {
private ListView fruitsList;
private ArrayAdapter<String> adapterFruit;
private Button btn_Delete;
private Button btn_SelectAll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_fruit_list_);
fruitsList = findViewById(R.id.list_Fruits);
fruitsList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
btn_Delete = findViewById (R.id.btn_delete);
CreateActivity.itemsFruit = FileHelper.readData(this);
adapterFruit = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, CreateActivity.itemsFruit);
fruitsList.setAdapter(adapterFruit);
/*button to Remove items*/
btn_Delete.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
SparseBooleanArray checkedItemPositions = fruitsList.getCheckedItemPositions();
int itemCount = fruitsList.getCount();
for(int i=itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
fruitsList.setItemChecked(i,true);
adapterFruit.remove(CreateActivity.itemsFruit.get(i));
FileHelper.writeData(CreateActivity.itemsFruit, FruitList_Activity.this );
}
}
adapterFruit.notifyDataSetChanged();
}
});
}
}
I've been stuck with this since 2 weeks i would we really like some precious help i'm ne to java and android so thanks for taking the time to explain how to fix this.
I wrote a simple program that will display an ArrayList and the user can select an item and delete it with a button.
If the user does not select an item but continues to hit the delete button, they will remove the first item on the ArrayList. How do I prevent this from happening? The delete button should only run when an item is selected, so I need to find a way to check for that
int positionID;
ListView listview;
ArrayList<String> valuesArray = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listview);
valuesArray.add("a");
valuesArray.add("b");
valuesArray.add("c");
valuesArray.add("d");
valuesArray.add("e");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1, valuesArray);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
positionID = (int) id;
}
});
}
public void onClickDelete(View v) {
//need to check if an item is selected. if so, run code below
valuesArray.remove(positionID);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, valuesArray);
listview.setAdapter(adapter);
}
Based on the code you've provided, this is likely happening because the default initialized value for positionID is set to 0. To fix this, you could initialize int positionID = -1 and then in your onClickDelete method, do a check to make sure the positionID is not invalid. Like this:
public void onClickDelete(View v) {
if (positionID < 0) return;
// continue your code here
}
By the way, a few other things you should fix. You should actually interact with adapter directly, so instead of valuesArray.remove(positionID) you should do adapter.remove(positionID). This will automatically update the adapter and refresh the ListView for you so you can get rid of the last two lines of your onClickDelete method.
You can just make valuesArray a local variable in your onCreate method, unless you plan on manipulating it directly elsewhere in your code. If you choose to do that, you can call adapter.notifyDataSetChanged() to make the adapter refresh your ListView.
I have problems with my list . I had an Activity I get some Data from.
The data must accessed in variables in my class :
Mylist.java class
public String Job,Ship,Location,Shift,Date;
public String workingHour;
Mylist(String job,String loc,String shp,String shft,String dat,String wh){
Job=job;
Location=loc;
Ship=shp;
Shift=shft;
Date=dat;
workingHour=wh;
}
and by pressing Save Button The list must add an item.My problem is when I add another items the list have only one item How to fix this ?
Adding Class :
AddOredit.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_oredit);
final ArrayList<Mylist>list =new ArrayList<>();
final ArrayList<String> Job=new ArrayList<>();
String selecteditem1, selecteditem2,getlocation,getship,getdate,gethours;
Spinner type=(Spinner)findViewById(R.id.s1);
Spinner shift=(Spinner)findViewById(R.id.s2);
EditText location=(EditText)findViewById(R.id.loc);
EditText ship=(EditText)findViewById(R.id.ship);
EditText date=(EditText)findViewById(R.id.date);
EditText workinghours=(EditText)findViewById(R.id.hours);
Button Save = (Button) findViewById(R.id.editbtn);
Button cancel = (Button) findViewById(R.id.cancelbtn);
selecteditem1 = type.getSelectedItem().toString(); //for first spinner
selecteditem2 = shift.getSelectedItem().toString();//for second spinner
getlocation=location.getText().toString();
getship=ship.getText().toString();
getdate=date.getText().toString();
gethours=workinghours.getText().toString();
list.add(new Mylist(selecteditem1,getlocation,getship,selecteditem2,getdate,gethours));
Log.e(TAG, String.valueOf(list.size()));
for(int i=0;i<list.size();i++){
Job.add("Job "+(i+1));
}
//When pressing save Button
Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//list.add(new Mylist(selecteditem1, getlocation, getship, selecteditem2, getdate, gethours));
Intent intent = new Intent(AddOredit.this, MainActivity.class);
intent.putStringArrayListExtra("MyList", Job);
startActivity(intent);
}
});
}
MainActivity.java this class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv= (ListView) findViewById(R.id.listView);
Button ADD=(Button)findViewById(R.id.addbtn);
Button DELETE=(Button)findViewById(R.id.deletebtn);
Button PROFILE=(Button)findViewById(R.id.profilebtn);
Intent intent=getIntent();
ArrayList<String> Job ;
Job=intent.getStringArrayListExtra("MyList");
if(Job!=null){
ListAdapter adapter= new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, Job);
lv.setAdapter(adapter);
//when user click on add button
}
ADD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//go to AddOreditpage
Intent i = new Intent(MainActivity.this, AddOredit.class);
startActivity(i);
}
});
**Note :- ** Add Button is for Adding items in the list and Save Button is for saving data entered at AddOredit class.
**Note :- ** By clicking Add Button , getting to the AddOredit Activity .
By Clicking Save Button, getting back to the main activity with the item added
You are assigning a new List for list object on your second activity created. Try to assign the list with an existing object and add your new object.
EDIT:
Try to Declare this globally as,
private static ArrayList list =new ArrayList<>();
and with in onCreate() remove it. Let me know if it still do not work.
in android application, i'm filling my spinner with some data coming from EditText object.
And when i'm trying to add it with adapter.add(somestring) method it crashes, so i need help.
...here's the code
public class OptionsMenu extends Activity implements View.OnClickListener{
Spinner users;
EditText input;
Button add,remove;
public static String filename = "savedData";
SharedPreferences sharedData;
String stringUsers;
ArrayAdapter<CharSequence> adapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options_menu);
Create();
sharedData = getSharedPreferences(filename, 0);
}
private void Create() {
// TODO Auto-generated method stub
users = (Spinner) findViewById(R.id.sp_op_users);
input = (EditText) findViewById(R.id.tb_op_inputUsers);
add = (Button) findViewById(R.id.bt_op_add);
remove = (Button) findViewById(R.id.bt_op_remove);
add.setOnClickListener(this);
remove.setOnClickListener(this);
//------------ADAPTER-----------------
adapter = ArrayAdapter.createFromResource(this, R.array.users,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
users.setAdapter(adapter);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.bt_op_add:
if (!input.getText().toString().equals("")) {
CharSequence inputData = input.getText().toString();
adapter.add(inputData);
adapter.notifyDataSetChanged();
users.setAdapter(adapter);
}
input.setText("");
users.setSelection(Adapter.NO_SELECTION);
break;
case R.id.bt_op_remove:
break;
}
}
Not very sure why you are getting the error but your if condition is wrong.
Change the following line:
if (input.getText().toString() != "")
to
if (!input.getText().toString().equals(""))
You don't compare strings using a = sign.
EDIT
Maybe you could first get the array from the resource file and create a local version of it:
String[] usersList=getResources().getStringArray(R.array.users);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, usersList)
and use this usersList as the list of data for your adapter.
You created the adapter using createFromResource() and provided it with the data from your resource. If you do it this way the list is fixed and you cannot add to or remove elements from it. This is why it crashed when you try to call adapter.add().
If you want to have the spinner contain dynamic data, then you'll have to add all the elements to it using add() and not create it from a resource.
EDIT: Add code example
in onCreate() we create and initialize the spinner adapter
List<String> items = ... // These are your items you get from a resource or read
// from a file or whatever
// Create the adapter, initializing it with the list of items, attach to spinner
adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
for (String item : items) {
adapter.add(item);
}
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
users.setAdapter(adapter);
in onClick(), to add an item to the spinner:
case R.id.bt_op_add:
if (!input.getText().toString().equals("")) {
CharSequence inputData = input.getText().toString();
adapter.add(inputData);
// You shouldn't need to reset the adapter on the spinner, nor call
// notifyDataSetChanged() here
}
input.setText("");
users.setSelection(Adapter.NO_SELECTION);
break;