I have a textView which is a DropDownList. Under this textview, there will be multiple options with checkboxes beside it. The User can choose one or more from the options.
I include my code for this dropdownlist and how did I populate it with my array.
MainActivity.java
private void initializeCustomerSegment()
{
final ArrayList<String> consumerSegments = new ArrayList<String>();
List<String> consumerSegment = databaseHandler.setItemOnConsumerSeg();
consumerSegments.addAll(consumerSegment);
checkSelectedConsumerSegment = new boolean[consumerSegments.size()];
//initialize all values of list to 'unselected' initially
for (int i = 0; i < checkSelectedConsumerSegment.length; i++) {
checkSelectedConsumerSegment[i] = false;
}
final TextView tv_ConsumerSegment = (TextView) findViewById(R.DropDownList.tv_ConsumerSegment);
tv_ConsumerSegment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!expandedConsumerSegment){
//display all selected values
String selected = "";
int flag = 0;
for (int i = 0; i < consumerSegments.size(); i++) {
if (checkSelectedConsumerSegment[i] == true) {
selected += consumerSegments.get(i);
selected += ", ";
flag = 1;
}
}
if(flag==1)
tv_ConsumerSegment.setText(selected);
expandedConsumerSegment =true;
}
else{
//display shortened representation of selected values
tv_ConsumerSegment.setText(BrandListAdapter.getSelected());
expandedConsumerSegment = false;
}
}
});
//onClickListener to initiate the dropDown list
TextView tv_customerSegment = (TextView)findViewById(R.DropDownList.tv_ConsumerSegment);
tv_customerSegment.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
initiatePopUpCustomerSegment(consumerSegments,tv_ConsumerSegment);
}
});
}
private void initiatePopUpCustomerSegment(ArrayList<String> customerSegments, TextView tv_CustomerSegment){
LayoutInflater inflater = (LayoutInflater)S_10th_IReportMain.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//get the pop-up window i.e. drop-down layout
LinearLayout layoutCustomerSegment = (LinearLayout)inflater.inflate(R.layout.pop_up_window_customersegment, (ViewGroup)findViewById(R.id.PopUpView1));
//get the view to which drop-down layout is to be anchored
RelativeLayout layout4 = (RelativeLayout)findViewById(R.id.relativeLayout4);
pwConsumerSegment = new PopupWindow(layoutCustomerSegment, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
//Pop-up window background cannot be null if we want the pop-up to listen touch events outside its window
pwConsumerSegment.setBackgroundDrawable(new BitmapDrawable());
pwConsumerSegment.setTouchable(true);
//let pop-up be informed about touch events outside its window. This should be done before setting the content of pop-up
pwConsumerSegment.setOutsideTouchable(true);
pwConsumerSegment.setHeight(LayoutParams.WRAP_CONTENT);
//dismiss the pop-up i.e. drop-down when touched anywhere outside the pop-up
pwConsumerSegment.setTouchInterceptor(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
pwConsumerSegment.dismiss();
return true;
}
return false;
}
});
//provide the source layout for drop-down
pwConsumerSegment.setContentView(layoutCustomerSegment);
//anchor the drop-down to bottom-left corner of 'layout1'
pwConsumerSegment.showAsDropDown(layout4);
//populate the drop-down list
final ListView listCustomerSegment = (ListView) layoutCustomerSegment.findViewById(R.DropDownList.dropDownCustomerSegment);
ConsumerSegmentListAdapter adapter = new ConsumerSegmentListAdapter(this, customerSegments, tv_CustomerSegment);
listCustomerSegment.setAdapter(adapter);
}
I also have this line of code in order for me to save the data...
String cSegment = checkSelected.toString();
Cursor rcSegment = databaseHandler.getReport_SubBrandCode(subBrand);
String SubBrandCode = rcSegment.getString(rcSegment.getColumnIndex(Constants.CONSUMERSEGMENT_CODE));
My question is, how can I save those multiple data in a single column in SQLite?
first, you need to get the value of the selected item on your multi select spinner. Try this:
ArrayList<String> content = new ArrayList<String>();
for (int j = 0; j < checkSelected.length; j++)
{
if(checkSelected[j]==true)
{
String values = BrandListAdapter.mListItems.get(j);
content.add(values);
}
}
Toast.makeText(getApplicationContext(), content.toString(), Toast.LENGTH_SHORT).show();
I toast the arraylist content just to check if it really contains the value I select. Then when you see the right value on your toast then you could save it on your database. Hope it helps! charot :D
Related
In spinner, whenever I selected an item it should be inactive or stop user from selecting again and whenever the user deletes the selected item that item should be active and user can select again. Items in the list should be added and deleted dynamically. Can anyone tell me how to do this?
Any help will be appreciated. If you can't understand the question please comment here
my code for adding new item and removing that item given below:
public void add_click()
{
add.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
spin = findViewById(R.id.spinnerLayout);
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addview = (layoutInflater).inflate(R.layout.spinner, null);
addview.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup
.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
game_name_Spinner = addview.findViewById(R.id.gamename);
player_level_Spinner = addview.findViewById(R.id.level);
remove = addview.findViewById(R.id.delete_button);
s_game = name1.getSelectedItem().toString();
s_level = level1.getSelectedItem().toString();
game_name_Spinner.setText(s_game);
player_level_Spinner.setText(s_level);
remove.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String last_removed;
((LinearLayout) addview.getParent()).removeView(addview);
gamename.addAll(removed_item);
adap1 = new ArrayAdapter<String>(PlayerProfile.this, android.R.layout
.simple_spinner_dropdown_item, gamename);
name1.setAdapter(adap1);
adap1.notifyDataSetChanged();
}
});
if (name1.getSelectedItemPosition()>0)
{
int count = removed_item.size();
for (int i = 0; i<=count; i++)
{
game_name_Spinner.setId(i);
}
idl = game_name_Spinner.getId();
game_removed = name1.getSelectedItem().toString();
removed_item.add(game_removed);
LinkedHashSet<String> hashSet = new LinkedHashSet<String>();
hashSet.add(game_removed);
removed_item.clear();
removed_item.add(game_removed);
adap1.remove(name1.getSelectedItem().toString());
}
container = findViewById(R.id.container);
container.addView(addview);
name1.setSelection(0);
level1.setSelection(0);
}
});
}
I'm Very new to Java and android... I'm Try to create an ListView using BaseAdapter List being created successfully i have a EditText along with button for each list item but the real problem is when i put some data into editText Field and scroll down to change value of last list item then i go back to the top it refreshes the data to default value it doesn't contain the value which was entered by user before scrolling down
My BaseAdaper Code
class CoustomAdptr extends BaseAdapter{
String[] dates;
Integer[] inventory;
Integer totalrooms;
public CoustomAdptr(RoomFragment roomFragment, String[] dates, Integer[] inventory, Integer totalrooms) {
this.dates = dates;
this.inventory = inventory;
this.totalrooms = totalrooms;
}
#Override
public int getCount() {
return dates.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
view = getLayoutInflater().inflate(R.layout.inventory_listview,null);
TextView textView = (TextView) view.findViewById(R.id.roomListViewText);
final EditText editText = (EditText) view.findViewById(R.id.roomListInventory);
final Button updateButton = (Button) view.findViewById(R.id.roomListViewInventoryUpdateButton);
if(inventory[i] == 0){
editText.setBackgroundColor(getResources().getColor(R.color.SoldOut));
editText.setTextColor(getResources().getColor(R.color.SoldOutTextColor));
} else if(inventory[i] < totalrooms){
editText.setBackgroundColor(getResources().getColor(R.color.invetory));
editText.setTextColor(getResources().getColor(R.color.invetoryTextColor));
} else if(inventory[i] == totalrooms){
editText.setBackgroundColor(getResources().getColor(R.color.fullInventory));
editText.setTextColor(getResources().getColor(R.color.fullInventoryTextColor));
}
editText.setText(String.valueOf(inventory[i]));
textView.setText(dates[i]);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//String name = editText.getText().toString();
//String name1 = dates[i];
//String name2 = getArguments().getString("room_id");
updateButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_done_black_24dp,0,0,0);
//updateButton.setBackgroundColor(getResources().getColor(R.color.SoldOut));
updateButton.setText("Updated");
updateButton.setEnabled(false);
Toast.makeText(getContext(), "Update Inventory Button Clicked", Toast.LENGTH_LONG).show();
}
});
return view;
}
}
This is How Im Passing Data to My Adapter
JSONObject jObj = parentObject.getJSONObject("success");
JSONObject jObj2 = jObj.getJSONObject("data");
JSONArray arrajson = jObj2.getJSONArray("inventories");
String arrayCount = Integer.toString(arrajson.length());
String[] dates = new String[arrajson.length()];
Integer[] inventory = new Integer[arrajson.length()];
Integer totalrooms = new Integer(jObj2.getInt("total_room"));
for (int i=0; i<arrajson.length();i++){
JSONObject jsonObject = arrajson.getJSONObject(i);
dates[i] = jsonObject.getString("date");
inventory[i] = jsonObject.getInt("inventory");
}
CoustomAdptr coustomAdptr = new CoustomAdptr(RoomFragment.this,dates,inventory,totalrooms);
listView.setAdapter(coustomAdptr);
Help Needed :- I Want to retain same visible and Value of edittext as users enters on scroll up or down... i hope i was able to explain my problem clearly
After clicking a button, save it's state in a boolean array or somewhere else. And inside getView method, check if this button was previously clicked or not then setup your view accordingly.
It would be better if you create a model class for rows.
If I programmatically create checkboxes as follows:
private Fruits fruits = new Fruits();
final String color = ... //user input from another control
final List<String> listFruits = fruits.getFruits(color);
final LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
...
for (int i = 0; i < listFruits.size(); i++)
{
final CheckBox chkFruits = new CheckBox(Main_Activity.this);
chkFruits.setText(listFoods.get[i]);
ll.addView(chkFruits);
//insert code here on how to pass data of checked checkboxes to my next Activity_2
}
And my Fruits class is as follows:
public class Fruits {
List<string> getFruits(String color) {
List<String fruits = new ArrayList<String>();
if (color.equals="red"){
fruits.add("Apple");
fruits.add("Strawberry");
}
else if (color.equals="yellow"){
fruits.add("Banana");
fruits.add("Pineapple");
}
return fruits;
}
}
How do I check for which generated checkboxes have been checked by the user AND THEN pass it's information (i.e. setText(listFoods.get[0] will give "Apple" if color="red") to my next Activity_2?
I tried using Intent:
final String[] passThis = new String[1];
Button btn = (Button) findViewById(R.id.btn);
...
btn.setOnClickListener(new View.OnClickListener(){
...
Intent intent = new Intent (getBaseContext(), Activity_2.class);
intent.putExtra("checkedFruits", passThis[0]);
startActvity(intent);
But it returns a NULL. How do I get the text/value of my generated checkboxes into my next Activity_2?
EDIT: How do I push whatever checked CheckBoxes into my passThis[] array so that I can pass them onto my next Activity?
Create a list of texts of checkboxes checked and need to add clickListener on each checkbox. Try something like this:
List checked<String> = new ArrayList()// stores checked checkboxes text
for (int i = 0; i < listFruits.size(); i++)
{
final CheckBox chkFruits = new CheckBox(Main_Activity.this);
chkFruits.setText(listFoods.get(i));
chkFruits.setTag(i); // to identify checkboxes
//add click listener to your checkboxes
chkFruits.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox checkbox=(CheckBox)v;
if(checkbox.isChecked())
{
int pos=(int)checkbox.getTag();
checkbox.setChecked(false);
checked.remove(pos);
}else
{
checkbox.setChecked(true);
checked.add(checkbox.getText());
}
}
});
ll.addView(chkFruits);
}
you can pass checked list to next Activity.
I've been stuck with this for a long while and it's really frustrating. Basically the app starts off with a ListView containing Movie Titles, their Gross, and Year.
The user then can add a new movie, gross, and year using a different activity from the menu. The values are then returned back to the first activity and is placed at the bottom of the list.
This is where my problem begins. The first problem I had is that the app Force Closes when it's about to display the new item. Now, it doesn't want to display at all. Here's the Code:
public class Lab7_084106 extends ListActivity {
private SampleCustomAdapter adapter;
private ArrayList<MyMovies> movieList;
public static boolean Flag = false;
#SuppressWarnings("null")
#Override
public void onCreate(Bundle savedInstanceState) {
//create stuff
super.onCreate(savedInstanceState);
movieList = new ArrayList<MyMovies>();
Intent data = getIntent();
//Flag = data.getStringExtra("Flag");
String[] oldMovieList = getResources().getStringArray(R.array.movieArray);
String[] oldGrossList = getResources().getStringArray(R.array.worldwideGross);
String[] oldYearList = getResources().getStringArray(R.array.yearArray);
//if there's no new movie to display
if(!Flag){
for (int i = 0; i < oldMovieList.length; i++) {
MyMovies newMovie = new MyMovies();
newMovie.setMovie(oldMovieList[i] + "NEW");
newMovie.setGross(oldGrossList[i]);
newMovie.setYear(oldYearList[i]);
movieList.add(newMovie);
}
//adapter = new SampleCustomAdapter(movieList);
//setContentView(R.layout.row);
//setListAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "Else Entered", Toast.LENGTH_SHORT).show();
int newLength = 50; //oldMovieList.length + 1;
//create new array to store the new value
String[] newMovieArray = new String[newLength];
String[] newGrossArray = new String[newLength];
String[] newYearArray = new String[newLength];
//populate the new list with the old one plus the new one
for (int i = 0; i < newLength; i++) {
if( i != newLength - 1){
newMovieArray[i] = oldMovieList[i];
newGrossArray[i] = oldGrossList[i];
newYearArray[i] = oldYearList[i];
}
else{
newMovieArray[i] = data.getStringExtra("Title");
newGrossArray[i] = data.getStringExtra("Gross");
newYearArray[i] = data.getStringExtra("Year");
}
}
//populate the old one using the new list
for (int i = 0; i < newLength; i++) {
oldMovieList[i] = newMovieArray[i];
oldGrossList[i] = newGrossArray[i];
oldYearList[i] = newYearArray[i];
}
//display stuff
for (int i = 0; i < newLength; i++) {
MyMovies newMovie = new MyMovies();
newMovie.setMovie(oldMovieList[i]);
newMovie.setGross(oldGrossList[i]);
newMovie.setYear(oldYearList[i]);
movieList.add(newMovie);
}
//adapter = new SampleCustomAdapter(movieList);
//setListAdapter(adapter);
}
adapter = new SampleCustomAdapter(movieList);
setListAdapter(adapter);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
//set stuff such that Page2 sends back a result to page 1
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView t = (TextView) view.findViewById(R.id.title);
String name = (String) t.getText();
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
}
});
}
private class SampleCustomAdapter extends BaseAdapter {
private ArrayList<MyMovies> internalList;
String[] oldMovieList = getResources().getStringArray(R.array.movieArray);
String[] oldGrossList = getResources().getStringArray(R.array.worldwideGross);
String[] oldYearList = getResources().getStringArray(R.array.yearArray);
private ArrayList<MyMovies> GetSearchResults(){
ArrayList<MyMovies> results = new ArrayList<MyMovies>();
// make sure the arrays have the same length
for (int i = 0; i < oldMovieList.length; i++) {
MyMovies sr = new MyMovies();
sr.setMovie(oldMovieList[i]);
sr.setGross(oldGrossList[i]);
sr.setYear(oldYearList[i]);
results.add(sr);
}
return results;
}
public SampleCustomAdapter(ArrayList<MyMovies> contacts){
internalList = contacts;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return internalList.size();
}
#Override
public Object getItem(int index) {
// TODO Auto-generated method stub
return internalList.get(index);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// NOTE: you can only do this if you have access to the Activity object
// which is why this is an inner class
LayoutInflater inflater = getLayoutInflater();
View view;
//System.out.println(parent.getClass().getName());
//System.out.println(position);
if (convertView==null){
view = inflater.inflate(R.layout.row, null);
}
else{
view = convertView;
}
// extract the views to be populated
TextView movie = (TextView) view.findViewById(R.id.title);
TextView gross = (TextView) view.findViewById(R.id.gross);
TextView date = (TextView) view.findViewById(R.id.date);
// extract the object that will fill these
MyMovies movies = GetSearchResults().get(position);
//MyMovies movies = internalList.get(position);
movie.setText(movies.getMovie());
gross.setText(movies.getGross());
date.setText(movies.getYear());
// return the view
return view;
}
}
//menu lawl
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menupage1, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//Handle item selection using item.getItemId()
switch(item.getItemId()){
case R.id.addMovie:
AddMovie();
break;
}
return true;
}
//end menu stuff lol
public void AddMovie(){
Intent intent2 = new Intent(this, com.Android.Lab7.addMovie.class);
startActivity(intent2);
finish();
}
}
The Flag Boolean variable basically tells if the user added a movie. If the user added a movie, it will enter the else statement and update from there. I'm really confused where to put this if-else statement.
I ran a few experiments with the GetSearchResult function of SampleCustomAdapter and found out that it directly affects the output of the ListView. I tried placing the if-else statement there but I ended up with a LOT of items in the ListView.
Using adapter.notifyDataSetChanged(); gives a NullPointerException error and points to where I placed it. So even if do something like:
MyMovies newMovie = new MyMovies();
newMovie.setMovie(data.getStringExtra("Title"));
newMovie.setGross(data.getStringExtra("Gross"));
newMovie.setYear(data.getStringExtra("Year"));
movieList.add(newMovie);
adapter.notifyDataSetChanged();
As the else block, it does not work. I think it has something to do with the fact that I'm getting my initial values from the string.xml resource folder and not via hardcode or user input.
This problem has been frustrating me ever since 2-3 days ago and help is really appreciated. Thanks.
you just have to notify the data set Changed on your adapter
movieList.add(newMovie);
adapter.notifyDataSetChanged();
the listview will be updated automatically
UPDATE
you can always use the following it'll work but I prefer notifying the adapter.
movieList.add(newMovie);
adapter = new SampleCustomAdapter(movieList);
setListAdapter(adapter);
you should use adapter.notifyDataSetChanged(). CheckThis Link
I'm using below code to travers my list it is working fine if List Items are visible.
If List is scrollable then non visible items are not accessing using this code. How to traverse all the list items which are visble + non visible items.
for(int i=0;i<list.getCount;i++)
{
View v = list.getChildAt(i);
TextView tv= (TextView) v.findViewById(R.id.item);
Log.d("","ListItem :"+tv.getText());
}
Here is how you can get your ListView in the Activity and traverse it.
ListView myList = getListView();
int count = myList.getCount();
for (int i = 0; i < count; i++)
{
ViewGroup row = (ViewGroup) myList.getChildAt(i);
TextView tvTest = (TextView) row.findviewbyid(R.id.tvTestID);
// Get your controls from this ViewGroup and perform your task on them =)
}
I hope this will help
Recently i did this thing.
Suppose i want to invisible a button on a listItem. Then in the getView of the list adapter add that button in a global vector. like below.
Button del_btn = viewCache.getFrame();
view_vec.add(del_btn);
Here viewCache is a object of ViewCache class, which is sumthing like below -
class ViewCache
{
private View baseView;
private Button button;
public ViewCache(View baseView)
{
this.baseView = baseView;
}
public Button getButton() {
if(button == null) {
button = (Button) baseView.findViewById(R.id.DeleteChatFrndBtn);
}
return button;
}
}
//it is necessary sometimes because otherwise in some cases the list scroll is slow.
Now you like to visible the listItem's button onClicking some other button. Then the code is like below -
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()) {
case R.id.EditChatFrndBtn:
length = view_vec.size();
for(int i = 0; i < length; i++) {
Button btn = (Button) view_vec.elementAt(i);
btn.setVisibility(View.VISIBLE);
}
doneBtn.setVisibility(View.VISIBLE);
editBtn.setVisibility(View.INVISIBLE);
break;
}
}
Instead of R.id.EditChatFrndBtn put your button id on clicking of which you will invisible/visible the listItem's button.