Android adapter.add() crashing my application - java

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;

Related

Android, how do I dynamically update a ListView item and all subsequent items?

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());
}

Unable to start activity ComponentInfo.....java.lang.IllegalStateException: Already attached

I m getting that error ,as you can see i m adding the data that i grabbed from the first activity and storing it into the my array in the second activity .
Then i use the array to populate the list view .So the problem is whenever i click to the save button on the first view
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
super.onCreate(savedInstanceState);
// setContentView(Your_Layout);
//Bundle extras = null;
//if(getIntent().getExtras() != null){
// extras = getIntent().getExtras();
//}
Intent intent = getIntent();
// ListView lv = (ListView) findViewById(R.id.View);
String data = intent.getStringExtra("data");
String first = intent.getStringExtra("stringOne");
String second = intent.getStringExtra("stringTwo");
String Third = intent.getStringExtra("stringThree");
String Fourth = intent.getStringExtra("stringFour");
String Fifth = intent.getStringExtra("stringFive");
String Sixth = intent.getStringExtra("stringSix");
// Find the ListView resource.
ListView lv = (ListView) findViewById( R.id.View );
// Create and populate a List of planet names.
String[] dataUser = new String[] { first,second,Third,Fourth,Fifth,Sixth};
ArrayList<String> dataList = new ArrayList<String>();
dataList.addAll(Arrays.asList(dataUser));
// Create ArrayAdapter using the planet list.
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList);
// Set the ArrayAdapter as the ListView's adapter.
lv.setAdapter(listAdapter);
}
}
You have 2 super.onCreate(savedInstanceState); in your code, remove one of them.
So I did remove the extrat super.onCreate(savedInstanceState); that i had but it looks like one of my edit text is passing a nul value .So i went trough every line but as you can see all the edixtext are passing a diffrent of null
http://pastebin.com/mys3R8QQ

Trouble adding a Spinner in Android Studio

KEEPING FOR HISTORIC. SKIP TO EDIT.
I am having trouble adding a spinner to an android app I'm developing. I haven't developed the code yet to go in the app, but just to do some testing I have it sending a toast message to let me know it works. According to this page: http://developer.android.com/guide/topics/ui/controls/spinner.html You can use User to create events by having OnItemSelected be called in another class.
public class SpinnerActivity extends EditJobActivity implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
Toast.makeText(SpinnerActivity.this, "It worked", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
That's it's own class. I call it with this:
//Prepare the first (Job Discovery) spinner
Spinner mJobDiscovery = (Spinner) findViewById(R.id.SpinJobDiscovered);
// Create an ArrayAdapter using the string array and a default spinner layout
JobDiscoveryAdapter = ArrayAdapter.createFromResource(this,
R.array.spin_JobDiscoveryHome, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
JobDiscoveryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
mJobDiscovery.setAdapter(JobDiscoveryAdapter);
mJobDiscovery.setOnItemSelectedListener(this);
However, I get this error:
SetOnItemSelectedListener(android...) in AdapterView cannot be applied to (com...Activity)
It asks me to cast it to (AdapterView.OnItemSelectedListener) but when I do I get errors because I can't cast the activity to an OnItemSelectedListener. What am I missing here? I'm a bit new to Android Programming, so I'm sorry if this is an easy answer...
EDIT:
After speaking with Bhush_techidiot, he sent me to some resources that helped, however I'm having trouble finalizing my implementation. Now my SpinnerActivity temporarily looks like this:
public class SpinnerActivity extends EditJobActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_job);
/*for fill your Spinner*/
List<String> SpinnerArray = new ArrayList<String>();
SpinnerArray.add("Item 1");
SpinnerArray.add("Item 2");
SpinnerArray.add("Item 3");
SpinnerArray.add("Item 4");
SpinnerArray.add("Item 5");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, SpinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spinner = (Spinner) findViewById(R.id.SpinJobDiscovered);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Object item = arg0.getItemAtPosition(arg2);
if (item != null) {
Toast.makeText(EditJobActivity.this, item.toString(),
Toast.LENGTH_SHORT).show();
}
Toast.makeText(EditJobActivity.this, "Selected",
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
but I don't know how to call SpinnerActivity from my EditJobActivity, so I'm getting the error: "... is not an enclosing class" on EditJobActivity. Should I be making a new layout for this spinner?
Check the following links. Make sure you keep your solutions as simple as you can also don't hesitate to try complicated things once you get the simple one working :) Understand the extending and implementing classes and you are good to go!
Android Spinner - onItemSelected / setOnItemSelectedListener not triggering
setOnItemSelectedListener of Spinner does not call
How to get the value of a selected item in a spinner?
All the best!

Android: problems with getSelectedItem on a spinner

I have a Spinner, and put the selected item in the body of a mail.
this is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modulo);
Spinner spinnerTaglia = (Spinner) findViewById(R.id.spinnerTaglia);
// Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.Taglie, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerTaglia.setPrompt("Seleziona la taglia!");
// Apply the adapter to the spinner
spinnerTaglia.setAdapter(new NothingSelectedSpinnerAdapter(
adapter,
R.layout.contact_spinner_row_nothing_selected,
// R.layout.contact_spinner_nothing_selected_dropdown, // Optional
this));
final String taglia = spinnerTaglia.getSelectedItem().toString();
Button btnCompilaOrdine = (Button) findViewById(R.id.btnCompilaOrdine);
btnCompilaOrdine.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"MAIL#gmail.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "MAIL OBJECT");
i.putExtra(Intent.EXTRA_TEXT , "Taglia: "+taglia);
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(Modulo.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
});
}
The application start correctly in the emulator and the debugger show me nothing (I'm using Android Studio) but when i click on the button that take me in this activity the application crash and the Android Studio's Debugger show me a java.lang.NullPointerException in the row:
final String taglia = spinnerTaglia.getSelectedItem().toString();
how can i fix this?
getSelectedItem() returns null if there is nothing selected on your spinner and calling toString() is making your application crash. Get rid of
final String taglia = spinnerTaglia.getSelectedItem().toString();
and in your onClick do:
if (spinnerTaglia.getSelectedItem() == null) {
return;
}
String taglia = spinnerTaglia.getSelectedItem().toString();
// the other code
Move the line
final String taglia = spinnerTaglia.getSelectedItem().toString();
to inside your OnClickListener
Currently, you're trying to read the selected item before anything has been selected. You should also ensure that getSelectedItem() isn't returning null because, unless you enable / disable the btnCompilaOrdine button (when an item is selected), the user can press the button without selecting an item in the spinner.
Maybe you should OnItemSelectedListener inseatead of a button.
Android Spinner
It seems that Item is returned with NULL value try to Invoking the method from a null object.
TheNullPointerException is a RuntimeException and thus, the Javac compiler does not force you to use a try-catch block to handle it appropriately.
Hope this will help you to solve your issue.
for further reference visit the link below:-
http://examples.javacodegeeks.com/java-basics/exceptions/java-lang-nullpointerexception-how-to-handle-null-pointer-exception/
Your are getting the selected item before the actual rendering of the spinner. It depends on device to device that how fast it renders the screen.
Rather then getting the selected item in getSelectionItem() in the onCreate() method try out to do it in the onClickListener() of your Button.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modulo);
Spinner spinnerTaglia = (Spinner) findViewById(R.id.spinnerTaglia);
// Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.Taglie, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerTaglia.setPrompt("Seleziona la taglia!");
// Apply the adapter to the spinner
spinnerTaglia.setAdapter(new NothingSelectedSpinnerAdapter(
adapter,
R.layout.contact_spinner_row_nothing_selected,
// R.layout.contact_spinner_nothing_selected_dropdown, // Optional
this));
Button btnCompilaOrdine = (Button) findViewById(R.id.btnCompilaOrdine);
btnCompilaOrdine.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
//Get the Selected item from the spinner
final String taglia = spinnerTaglia.getSelectedItem().toString();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"MAIL#gmail.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "MAIL OBJECT");
i.putExtra(Intent.EXTRA_TEXT , "Taglia: "+taglia);
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(Modulo.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
});
}
mSpinner.setSelected(true);
If you implement this with your spinner, it will not give null.

ListView doesn't show items when updated from a fucntion

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.

Categories