I have a activity, in which it has a button, on click of the button the app crashes problem is on line adapter.remove(list.get(i));
Logcat detail mention NullPointerException on the given line adapter.remove(list.get(i));
package com.example.veeresh.myphotogallery;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;
public class MainActivity extends ListActivity {
/** Items entered by the user is stored in this ArrayList variable */
ArrayList list = new ArrayList();
/** Declaring an ArrayAdapter to set items to ListView */
ArrayAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Setting a custom layout for the list activity */
setContentView(R.layout.activity_main);
/** Reference to the add button of the layout main.xml */
Button btn = (Button) findViewById(R.id.btnAdd);
/** Reference to the delete button of the layout main.xml */
Button btnDel = (Button) findViewById(R.id.btnDel);
/** Defining the ArrayAdapter to set items to ListView */
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_multiple_choice, list);
adapter.add("Item 1");
/** Defining a click event listener for the button "Add" */
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
EditText edit = (EditText) findViewById(R.id.txtItem);
list.add(edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
};
/** Defining a click event listener for the button "Delete" */
OnClickListener listenerDel = new OnClickListener() {
#Override
public void onClick(View v) {
/** Getting the checked items from the listview */
SparseBooleanArray checkedItemPositions = getListView().getCheckedItemPositions();
int itemCount = getListView().getCount();
for(int i=itemCount-1; i >= 0; i--)
{
if(checkedItemPositions.get(i)){
adapter.remove(list.get(i));
}
}
checkedItemPositions.clear();
adapter.notifyDataSetChanged();
}
};
/** Setting the event listener for the add button */
btn.setOnClickListener(listener);
/** Setting the event listener for the delete button */
btnDel.setOnClickListener(listenerDel);
/** Setting the adapter to the ListView */
setListAdapter(adapter);
}
}
Your adapter contains a list, and your MainActivity contains another list.
You are adding items to your Adapter, however this does not add items to the list in your Mainactivity. The list in your Adapter contains "Item 1", but the list in MainActivity does not.
OnClick you are trying to retrieve an item from the list in your MainActivity, which doesn't contain the item you are trying to retrieve, hence the NullpointerException
You should add or remove items from the list and then call adapter.notifyDataSetChanged();
Try:
//add an item
list.add("item 1");
adapter.notifyDataSetChanged();
//remove an item
list.remove(i);
adapter.notifyDataSetChanged();
I believe you should change your problematic line with this:
adapter.remove(list.getAdapter().getItem((checkedItemPositions.keyAt(i)));
Related
Here's my MainActivity.java, in the onClick() method I want to swap the values between the spinners and also automatically do an internal button press when buttonSwap is pressed. I can swap the Spinners and texts values but can not do inner call to buttonConvert for auto conversion upon buttonSwap press . Please Help:
MainActivity.java file code :
package com.gazzali.spinitmeow;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
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.TextView;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener, View.OnClickListener{
Spinner spinnerMainChoice;
Spinner spinnerInputChoice;
Spinner spinnerOutputChoice;
EditText InputValueEditText;
Double inputValue;
TextView outputValueTextView;
Button buttonConvert;
Button buttonReset;
Button buttonSwap;
String selectedMainChoice;
String inputValueString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* ------------ Main code Starts Here ----------------*/
/* Main conversion Type choice with Spinner (Drop Down menu)*/
spinnerMainChoice = findViewById(R.id.spinnerIDMainChoice);
// [IMPORTANT] Set Spinner Click Listener
spinnerMainChoice.setOnItemSelectedListener(this);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapterMainChoice = ArrayAdapter.createFromResource(this,
R.array.MainChoices_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapterMainChoice.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinnerMainChoice.setAdapter(adapterMainChoice);
/* Input Conversion type choice with Spinner */
spinnerInputChoice = findViewById(R.id.spinnerIDInputChoice);
/* Output Conversion type choice with Spinner */
spinnerOutputChoice = findViewById(R.id.spinnerIDOutputChoice);
/* for input and output fields */
InputValueEditText = findViewById(R.id.editTextIDInputValue);
/* ---- Setting Button Properties -----*/
buttonConvert = findViewById(R.id.buttonIDConvert);
buttonConvert.setOnClickListener(this);
buttonReset = findViewById(R.id.buttonIDReset);
buttonReset.setOnClickListener(this);
buttonSwap = findViewById(R.id.buttonIDSwap);
buttonSwap.setOnClickListener(this);
/* --- Setting Output TextView field ----*/
outputValueTextView = findViewById(R.id.textViewIDoutputValue);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// An item was selected. retrieve the selected item
selectedMainChoice = parent.getSelectedItem().toString();
Log.i("Selected", selectedMainChoice);
/* Toast.makeText(MainActivity.this, String.valueOf(inputValue), Toast.Weight_SHORT).show();*/
/* Implement object of spinnerSelects class*/
spinnerSelects spinnerSelectsInMain = new spinnerSelects(this, spinnerInputChoice, spinnerOutputChoice);
/* the main EVIL '(context) this' in the 2nd paraKilogram, 5 hours wasted, but I learnt many more */
spinnerSelectsInMain.setInputOutputSpinners(selectedMainChoice);
/* calling test for converter class */
/*testOnConverter();*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
public void testOnConverter(){
converter converterInMain = new converter(selectedMainChoice);
}
#Override
public void onClick(View view)
{
if (view == buttonConvert) {
inputValueString = InputValueEditText.getText().toString();
inputValue = Double.parseDouble(inputValueString);
/*Toast.makeText(this, String.valueOf(inputValue), Toast.Weight_SHORT).show();*/
converter converterInMain = new converter(selectedMainChoice);
double convertedValue = converterInMain.convert(inputValue);
outputValueTextView.setText(String.valueOf(convertedValue));
}
else if(view == buttonReset)
{
InputValueEditText.getText().clear();
outputValueTextView.setText("0.00");
}
else if(view == buttonSwap)
{
/* Swap between spinners choice */
spinnerSelects spinnerSelectsInMainToSwap= new spinnerSelects();
spinnerSelectsInMainToSwap.swapEverything();
/* Here I want to simulate as the buttonConvert has been pressed */
/* performClick() or callOnClick() doesn't simulate the convert button press programmatically */
}
}
}
Create three functions
void buttonConvert(){
...code for buttonconvert();
}
void buttonSwap(){
...code for buttonswap();
}
void buttonReset(){
...code for buttonreset();
}
then in the condition blocks
if(buttonConvert){
buttonConvert();
}
else if(buttonSwap){
buttonSwap();
buttonConvert();
}
else if(buttonReset){
buttonReset();
}
You can simulate click by doing buttonConvert.performClick();.
Or you can call manually onClick method and pass buttonCovert view like onClick(buttonConvert);
Hope you guys can help.
I have a activity which handles all the 10 image button clicks and list view intents. What i am looking to do is have 1 layout for all the list view button clicks. And in this layout call different data to it. When i started this project i had many activitys until a great stack overflow user pointed out that i can make it simpler which i did and made it a lot clear.
package com.example.testtest;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class Listviewact extends Activity {
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.listview_layout);
Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/AlexBrush-Regular-OTF.otf");
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setTypeface(tf);
}
public void onResume() {
super.onResume();
int buttonId = getIntent().getIntExtra("buttonId", 0);
int buttonIdx = getButtonIdx(buttonId);
// find and set image according to buttonId
int imageId = IMAGE_IDS[buttonIdx]; // image to show for given button
ImageView imageView = (ImageView)findViewById(R.id.imageView1);
imageView.setImageResource(imageId);
// find and set listview imtes according to buttonId
String[] items = LISTVIEW_DATA[buttonIdx]; // listview items to show for given button
ListView listView = (ListView)findViewById(R.id.listView1);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
}
private void setListAdapter(ArrayAdapter adapter) {
// TODO Auto-generated method stub
}
// a little helper to map ids to array indices
// to be able to fetch the correct image and listview data later
private final static int[] BUTTON_IDS = new int[] {
R.id.imageButton1,
R.id.imageButton2,
R.id.imageButton3,
R.id.imageButton4,
R.id.imageButton5,
R.id.imageButton6
};
// 6 images
private final static int[] IMAGE_IDS = new int[] {
R.drawable.bmw,
R.drawable.ford,
R.drawable.honda,
R.drawable.toy,
R.drawable.vok2,
R.drawable.ic_launcher
};
// 6 different sets of strings for the listviews
private final static String[][] LISTVIEW_DATA = new String[][] {
{"First A", "First B", "First C", "First D","First E","First F"},
{"Second A", "Second B", "Second C"},
{"Third A", "Third B", "Third C"},
{"Forth A", "Forth B", "Forth C"},
{"Fifth A", "Fifth B", "Fifth C"},
{"Sixth A", "Sixth B", "Sixth C"},
};
// map button id to array index
static private int getButtonIdx(int id) {
for(int i = 0; i<BUTTON_IDS.length; i++) {
if (BUTTON_IDS[i] == id) return i;
}
return 0; // should not happen
}
}
It would be great if someone can show me how to make a class which i can call all the item clicks from all list views too from my code here.
package com.example.testtest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
public class MainActivity extends Activity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_of_button);
ImageButton btn1 = (ImageButton)findViewById(R.id.imageButton1);
ImageButton btn2 = (ImageButton)findViewById(R.id.imageButton2);
ImageButton btn3 = (ImageButton)findViewById(R.id.imageButton3);
ImageButton btn4 = (ImageButton)findViewById(R.id.imageButton4);
ImageButton btn5 = (ImageButton)findViewById(R.id.imageButton5);
ImageButton btn6 = (ImageButton)findViewById(R.id.imageButton6);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
// if one of the image buttons is pressed...
case R.id.imageButton1:
case R.id.imageButton2:
case R.id.imageButton3:
case R.id.imageButton4:
case R.id.imageButton5:
case R.id.imageButton6:
Intent intent = new Intent(this, Listviewact.class);
// pass ID of pressed button to listview-activity
intent.putExtra("buttonId", v.getId());
startActivity(intent);
break;
// here you could place handling of other clicks if necessary...
}
}
private void setListAdapter(ArrayAdapter<String> arrayAdapter) {
// TODO Auto-generated method stub
}
private ListView getListView() {
// TODO Auto-generated method stub
return null;
}
}
CHEERS.
http://img40.imageshack.us/img40/705/f6h9.png
If I understand what you want, you could create a class with something like a static Arraylist to be appended each time an item is clicked. So create a class something like
public class Data class
{
static ArrayList<String> dataArray = new ArrayList<String>();;
public Data()
{
// empty constructor but could be used if needed
}
Then you can add different getters/setters or whatever you need here. When you click on an item you just call something like
Data.dataArray.add("stuff");
then retrieve items in here in your next Activity.
If that is too complicated or more than you need then you can just pass an ArrayList or whatever object you need through the Intent
Intents
Also, just a preference but since all of your Buttons do the same thing, you can do away with initializing them and setting listeners on all of them. In xml just add
`android:onClick="someFunctionName"`
to each Button then use that function name
public void someFunctionName(View v) {
switch(v.getId()) {
// if one of the image buttons is pressed...
Intent intent = new Intent(this, Listviewact.class);
// pass ID of pressed button to listview-activity
intent.putExtra("buttonId", v.getId());
startActivity(intent);
break;
// here you could place handling of other clicks if necessary...
}
There is also no need for the case statements since they all do the same thing and you don't need implements OnClickListener in the Activity declaration
You're using the ListView but not using any of it's callbacks? Here, this is my code that I use for my ListView. I'm putting activities in my array, but you could put anything. Modifying the R.layout.mfd_view allows you to put whatever you want for each list item. A Button if that's what you need. Hope this helps. I'm still learning myself.
import android.app.Activity;
import android.app.ListFragment;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
public class MyListFragment extends ListFragment {
String fragmentBackStack;
MyMapHandler handler;
OnViewSelectedListener mListener;
/**
* An array of POJOs used to hold the info about the fragments we'll be
* swapping between This should be inserted into an array adapter of some
* sort before being passed onto ListAdapter
*/
private static final ViewDetails[] ACTIVITY_DETAILS = {
new ViewDetails(R.string.action_largeTach,
R.string.largeTach_description, LargeTachActivity.class),
new ViewDetails(R.string.action_map, R.string.map_description,
MyMapHandler.class),
new ViewDetails(R.string.action_navigation,
R.string.navigation_description, NavigationActivity.class),
new ViewDetails(R.string.action_raceMode,
R.string.raceMode_description, RaceModeActivity.class),
new ViewDetails(R.string.action_settings,
R.string.settings_description, SettingsFragment.class),
new ViewDetails(R.string.action_extraInfo,
R.string.extraInfo_description, ExtraInfoActivity.class) };
/**
* #author PyleC1
*
* A POJO that holds a class object and it's resource info
*/
public static class ViewDetails {
private final Class<? extends Activity> viewActivity;
private int titleId;
private int descriptionId;
/**
* #param titleId
* The resource ID of the string for the title
* #param descriptionId
* The resource ID of the string for the description
* #param activityClass
* The fragment's class associated with this list position
*/
ViewDetails(int titleId, int descriptionId,
Class<? extends Activity> viewActivity) {
super();
this.titleId = titleId;
this.descriptionId = descriptionId;
this.viewActivity = viewActivity;
}
public Class<? extends Activity> getViewActivity() {
return viewActivity;
}
}
/**
* #author PyleC1
*
* Extends the ArrayAdapter class to support our custom array that
* we'll insert into the ListAdapter so the user can pick between
* MFD screens at boot time.
*/
private static class CustomArrayAdapter extends ArrayAdapter<ViewDetails> {
public CustomArrayAdapter(Context context, ViewDetails[] activities) {
super(context, R.layout.mfd_view, R.id.mfdTitle, activities);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MFDView mfdView;
if (convertView instanceof MFDView) {
mfdView = (MFDView) convertView;
} else {
mfdView = new MFDView(getContext());
}
ViewDetails details = getItem(position);
mfdView.setTitleId(details.titleId);
mfdView.setDescriptionId(details.descriptionId);
return mfdView;
}
}
public void onAttach(Activity activity) {
super.onAttach(activity);
ListAdapter listAdapter = new CustomArrayAdapter(getActivity(),
ACTIVITY_DETAILS);
setListAdapter(listAdapter);
try {
mListener = (OnViewSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnViewSelectedListener!");
}
}
#Override
public void onResume() {
super.onResume();
}
public interface OnViewSelectedListener {
public void onViewSelected(Class<? extends Activity> activityClass);
}
public void onListItemClick(ListView l, View v, int position, long id) {
ViewDetails details = (ViewDetails) getListAdapter().getItem(position);
mListener.onViewSelected(details.viewActivity);
}
}
Note that whatever activity calls this fragment must implement the OnViewSelectedListener interface. If you added this to your main activity as a subclass, this wouldn't be required. The public void onListItemClick(arg0, arg1, arg2, arg3) callback is fine. You just swap fragments or call activities from inside there.
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!
I'm trying to use 2 spinners on my view and at the moment implementing the "OnItemSelected" method . I have a switch statement set up to tell the spinners apart, but it doesn't seem to be working for some reason.
Here is my code:
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import java.util.ArrayList;
import android.widget.AdapterView.OnItemSelectedListener;
/**
* This is the activity for feature 1 in the dashboard application.
* It displays some text and provides a way to get back to the home activity.
*
*/
public class F1Activity extends DashboardActivity implements OnItemSelectedListener
{
/**
* onCreate
*
* Called when the activity is first created.
* This is where you should do all of your normal static set up: create views, bind data to lists, etc.
* This method also provides you with a Bundle containing the activity's previously frozen state, if there was one.
*
* Always followed by onStart().
*
* #param savedInstanceState Bundle
*/
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView (R.layout.activity_f1);
setTitleFromActivityLabel (R.id.title_text);
//declaring variables
Button submitButton = (Button) findViewById(R.id.button1);
Button cancelButton = (Button) findViewById(R.id.button2);
//getting arrays from strings file
String[] regions = getResources().getStringArray(R.array.regions_array);
String[] grids = getResources().getStringArray(R.array.grids_array);
Spinner gridSpinner = (Spinner) findViewById(R.id.gridSpinner);
Spinner regionSpinner = (Spinner) findViewById(R.id.regionSpinner);
//creating adapters for both spinners
ArrayAdapter<String> dataAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, grids);
ArrayAdapter<String> regionAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, regions);
// drop down layout style with radio button type.
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
regionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapters to spinners
gridSpinner.setAdapter(dataAdapter);
regionSpinner.setAdapter(regionAdapter);
gridSpinner.setOnItemSelectedListener(this);
regionSpinner.setOnItemSelectedListener(this);
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
Intent changeAdd = new Intent();
setResult(RESULT_OK, changeAdd);
EditText nameText = (EditText) findViewById(R.id.nameTextBox);
EditText passText = (EditText) findViewById(R.id.passwordTextBox);
if(nameText.getText().toString().length() > 0 &&
passText.getText().toString().length() > 0) //TAKE CARE OF LISRVIEW/DROPDOWN
{
Toast.makeText(getApplicationContext(),
"Loading...", Toast.LENGTH_LONG).show();
// make an intent to start the virtual world activity..................like in addGridActivity/screen switch!
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Sorry, you have to complete all the fields",
Toast.LENGTH_SHORT).show();
}
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
Intent changeAdd = new Intent();
setResult(RESULT_OK, changeAdd);
// cancelled and went back to home screen
finish();
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long arg3) {
// to handle the selection of the gridSpinner or the regionSpinner
int id = parent.getId();
switch(id)
{
case R.id.gridSpinner:
Toast.makeText(parent.getContext(), "you selected" +
parent.getItemAtPosition(pos).toString() + "from the grid spinner", Toast.LENGTH_LONG);
break;
case R.id.regionSpinner:
Toast.makeText(parent.getContext(), "you selected" +
parent.getItemAtPosition(pos).toString() + "from the region spinner", Toast.LENGTH_LONG);
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
} // end class
<code>
Your switch is working fine. The reason it seems to be not working is because your code to display the Toast is missing the show() calls.
Instead of:
Toast.makeText(parent.getContext(), ..., Toast.LENGTH_LONG);
do this:
Toast.makeText(parent.getContext(), ..., Toast.LENGTH_LONG).show();
I make the same mistake all the time myself :)
Replace int id = parent.getId(); to int id = view.getId();
You need to switch based on the id of the view not the view adapter. Try changing int id = parent.getId(); to int id = view.getId();.
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);
}
});