Why do "selectedCountry", "selectedAge", "selectedGender" return null? - java

When I run my app and go to the "EditProfile" activity. And then, I will immediately receive the toast message "Something is wrong" which means, the variables "selectedCountry", "selectedAge", and "selectedGender" are null.
public class EditProfile extends AppCompatActivity {
UserInfo userInfo;
UserInfo profileDetails;
Spinner spinnerFrom;
Spinner spinnerAge;
Spinner spinnerGender;
EditText hobbyEdit;
Button btnDone;
TextView textView;
String selectedCountry;
String selectedAge;
String selectedGender;
DatabaseHelper mydb = new DatabaseHelper(this, "MyUsers", null, 5);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Profile.class);
intent.putExtra("id", userInfo.getId());
intent.putExtra("username", userInfo.getUsername());
startActivity(intent);
}
});
Bundle extras = getIntent().getExtras();
int id = extras.getInt("id");
final String username = extras.getString("username");
// Username
userInfo = new UserInfo(id, username);
textView = (TextView) findViewById(R.id.usernameUnedit);
textView.setText(username);
// Country
spinnerFrom = (Spinner) findViewById(R.id.spinnerFrom);
Locale[] locales = Locale.getAvailableLocales();
final ArrayList<String> countries = new ArrayList<String>();
countries.add("-");
for (Locale locale : locales) {
String country = locale.getDisplayCountry();
if (country.trim().length() > 0 && !countries.contains(country)) {
countries.add(country);
}
}
Collections.sort(countries);
ArrayAdapter<String> countryAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, countries);
countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerFrom.setAdapter(countryAdapter);
spinnerFrom.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedCountry = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Age
spinnerAge = (Spinner) findViewById(R.id.spinnerAge);
final ArrayList<String> ages = new ArrayList<String>();
ages.add("-");
for (int i = 18; i < 100; i++) {
ages.add(String.valueOf(i));
}
ArrayAdapter<String> ageAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, ages);
ageAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerAge.setAdapter(ageAdapter);
spinnerAge.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedAge = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Gender
spinnerGender = (Spinner) findViewById(R.id.spinnerGender);
final ArrayList<String> genders = new ArrayList<String>();
genders.add("-");
genders.add("Male ♂");
genders.add("Female ♀");
genders.add("Other");
ArrayAdapter<String> genderAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, genders);
genderAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGender.setAdapter(genderAdapter);
spinnerGender.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedGender = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Hobby
hobbyEdit = (EditText) findViewById(R.id.hobbyEdit);
// Button done
btnDone = (Button) findViewById(R.id.btnDone);
btnDone.setEnabled(false);
/* Stuck at this if statement below */
if (selectedCountry != null && selectedAge != null && selectedGender != null) {
if (!mydb.isStoredProfileDetails(username, selectedCountry, selectedAge, selectedGender, hobbyEdit.getText().toString())) {
btnDone.setEnabled(true);
btnDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
profileDetails = new UserInfo(selectedCountry, selectedAge, selectedGender, hobbyEdit.getText().toString());
mydb.updateTable(username, profileDetails);
}
});
} else {
Toast.makeText(this, "Something is wrong 2.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "Something is wrong.", Toast.LENGTH_LONG).show();
}
}
}
I expect that after choosing an item from those 3 dropdown lists (spinners) and the values of the chosen items do not exist in database, then the "Done" button would be clickable. Once the button is clicked, it would store the selected values from the dropdown lists (spinners) into database by updating it.
Unfortunately, I am stuck at the if statement as stated in the given code as it keeps returning the "else" statement.

Set your variable as...
String selectedCountry = "";
String selectedAge = "";
String selectedGender = "";
And check condition as...
if (!selectedCountry.equals("") && !selectedAge.equals("") && !selectedGender.equals("")) {
//your code goes here
}

You have to check your both conditions in Spinner's OnItemSelectedListener, If both conditions will return true then enable your button. and call setonClickListener on button in onCreateView, like this.
spinnerGender.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedGender = parent.getItemAtPosition(position).toString();
//Conditions to enable button
if (selectedCountry != null && selectedAge != null && selectedGender != null) {
if (!mydb.isStoredProfileDetails(username, selectedCountry, selectedAge, selectedGender, hobbyEdit.getText().toString())) {
btnDone.setEnabled(true);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
add these lines in all spinners.

In your onCreate method, you have instantiated the views and attached listeners to them. That is perfectly fine. However, this does not mean that the logic in those listeners will be execute at the same time and order. You have just defined the behaviour of the listeners. After all that initialisation, your code directly checks the values of the three Strings mentioned in your question. It does not wait for a user to interact with the spinners.
What you want is to trigger the change in the "done" button when a user selects something from the spinner. So the logic of setting the strings and thereby checking if you could enable the "done" button must go in the listeners of the spinners.
I am not giving you a direct code solution to the problem, but an approach which you could employ.

Related

How do i copy an item in an list into a list in another activity?

Been trying to add a favorites system to this notes app where I can tap and hold an item in the list view to add it to another activity with a list view. Here is the activity with the first list.
Items are added via the MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.savebutton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editTextHeading = (EditText) findViewById(R.id.editTextTextPersonName);
EditText editTextContent = (EditText) findViewById(R.id.contentfield);
String heading = editTextHeading.getText().toString().trim();
String content = editTextContent.getText().toString().trim();
if (!heading.isEmpty()) {
if(!content.isEmpty()) {
try {
FileOutputStream fileOutputStream = openFileOutput(heading + ".txt", Context.MODE_PRIVATE); //heading will be the filename
fileOutputStream.write(content.getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else {
editTextContent.setError("Content can't be empty!");
}
}else{
editTextHeading.setError("Heading can't be empty!");
}
editTextContent.setText("");
editTextHeading.setText("");
}
});
Button button2 = (Button) findViewById(R.id.btn_gotosaved);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, saved.class));
}
});
Button button3 = (Button) findViewById(R.id.btn_faves);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, favorites.class));
}
});
}
}
Items added will be viewed here
public class saved extends MainActivity {
public static final String EXTRA_MESSAGE = "com.example.notes.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved);
File files = getFilesDir();
String[] array = files.list();
ArrayList<String> arrayList = new ArrayList<>();
final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
for (String filename : array) {
filename = filename.replace(".txt", "");
System.out.println(filename);
adapter.add(filename);
}
final ListView listView = (ListView) findViewById(R.id.lv_saved);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
Intent intent = new Intent(getApplicationContext(), Note.class);
intent.putExtra(EXTRA_MESSAGE, item);
startActivity(intent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
}
});
}
}
And tapping and holding an item from there should "favorite" it and copy it to this new activity with another listview
public class favorites extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorites);
ListView listView = (ListView) findViewById(R.id.lv_favorites);
}
}
How should I approach this?
With your implementation of creating an individual .txt file in the default directory for each note, this is how you could implement:
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
Boolean isItemFavorite = item.contains("_favorite");
if (!isItemFavorite){
File itemFile = new File(item + ".txt");
File favoriteItemFile = new File(item + "_favorite.txt");
itemFile.renameTo(favoriteItemFile);
}
}
});
Then in your "favorites" activity you could access all of your note .txt file the same as you do in your "saved" activity - just filtering out any items that don't contain "_favorite" in your "String[] array = files.list();"
Also, some tips: follow naming convention with your activities. "saved" should at least start with an uppercase letter and really should be named something like "SavedNotesListActivity". Also, you should use a room database to keep track of your notes. You should have a favorites table in your room database to keep track of all of your favorites.

Delete a listview item with a button in it self in android studio

As I am very new to java pls help me on this. I have a custom list view in my main activity and a Custom adapter with it. In my every list item there is a delete button that should delete that item when it clicked. I can not remove data from my arraylist when i am inside my custom adapter. Pls helm me in coding this delete button.
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText getItem;
Button AddButton;
Button DellButton;
public static ArrayList<String> myData = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list = (ListView)
findViewById(R.id.listView);
getItem = (EditText) findViewById(R.id.newItem);
AddButton = (Button) findViewById(R.id.AddButton);
MyAdapter adapter = new MyAdapter(this, myData);
list.setAdapter(adapter);
AddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String result = getItem.getText().toString();
myData.add(result);
adapter.notifyDataSetChanged();
}
});
}
MyAdapter.java
public class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, ArrayList<String> records) {
super(context, 0, records);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String item = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.listview_custom, parent, false);
}
final TextView lst_txt = (TextView) convertView.findViewById(R.id.list_Txt2);
Button plusbut = (Button) convertView.findViewById(R.id.plusbut);
Button minusbut = (Button) convertView.findViewById(R.id.minusbut);
final TextView sum = (TextView) convertView.findViewById(R.id.sum);
Button cal = (Button) convertView.findViewById(R.id.calButton);
Button delete = (Button) convertView.findViewById(R.id.btnDel);
lst_txt.setText(item);
minusbut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int sumAll = Integer.parseInt(sum.getText().toString());
int sum1 = sumAll - 1;
sum.setText(String.valueOf(sum1));
}
});
plusbut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int sumAll = Integer.parseInt(sum.getText().toString());
int sum1 = sumAll + 1;
sum.setText(String.valueOf(sum1));
}
});
cal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s = sum.getText().toString();
Intent intent = new Intent(getContext(), calll.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("sumFL", s);
getContext().startActivity(intent);
}
});
return convertView;
}
}
Please first try to remove object from list by using the position of item with check the validation with list size and then call notifyItemadapter to update the list view.
Use ViewHolder class for all view like textview, button etc. And initialize them inside the condition
if(convert view==null){
Initialize holder object here and
Inflate your layout and
Initialize button like
holder.deletebutton = convert view.findviewbyid from xml
settag(holder)
}
Again get the holdet using the gettag in
else{
//Here
}
Put All click event and text update etc. Outside of above condition
holder.deletbutton.setonclicklistener{
int pos = view.getag
list.remove(pos)
Notifyadapter here
}
holder.deletebutton.settag(position)

Cannot get a value from EditText

i have a little problem, i have been solved my problem before thanks to Alex Mamo, and now i have another problem.
Here i attach my firebase realtime database screenshoot
Well at the ima i attach, te Cart should have a child refer to table number, i get a table number from edittext sing getText function, and i send it, to another activity, but, when i send it to another activiy and get it, it seems not getting any value. I try to Log, and it doesn't show anything, try to print too, and the reslut is same. My question is, how i can get a value from edittext in other way?
Here i attach my code fo getText function
DineIn.java
EditText txtTable;
ArrayList<Menu> menuItems = new ArrayList<Menu>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dine_in);
txtTable = findViewById(R.id.txtTable);
String tables = txtTable.getText().toString();
Log.e("Nomormeja", tables);
And this cod is for send it to another activity
DineIn.java (this code is outter from onCreate() method)
class CustomAdaptor extends BaseAdapter {
private Activity mContext;
private ArrayList<Menu> mItems;
public CustomAdaptor(Activity context, ArrayList<Menu> list) {
mContext = context;
mItems = list;
}
#Override
public int getCount() {
return menuItems.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.order_items, null);
TextView menuName = (TextView) convertView.findViewById(R.id.menuName);
TextView menuType = (TextView) convertView.findViewById(R.id.menuType);
TextView menuPrice = (TextView) convertView.findViewById(R.id.menuPrice);
ImageButton addcart = (ImageButton) convertView.findViewById(R.id.addBtn);
final String menuNames = menuItems.get(position).getMenuName();
final String tables = txtTable.getText().toString();
addcart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Like a Session variable ..it passes the dishName from the row that was clciked
SharedPreferences sharedPreferences=getSharedPreferences("shared preferences",MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("menuNames",menuNames);
editor.putString("tables", tables);
editor.commit();
startActivity(new Intent(DineIn.this,ProductDetails.class));
}
});
And this code is to get the value on destination activity
Product.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
txtNama = findViewById(R.id.tvNama);
txtQuantity = findViewById(R.id.tvQuantity);
btnMin = findViewById(R.id.btnMin);
btnPls = findViewById(R.id.btnPls);
btnAdd = findViewById(R.id.btnAdd);
SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences sharedPreferences=getSharedPreferences("shared preferences",MODE_PRIVATE);
menuName = sharedPreferences.getString("menuNames", ""); // taking dishname from menu when clicked a
tables = sharedPreferences.getString("tables", "");
Log.d("meja", tables);
Log.d("menu", menuName);
And i set the vale for child at my Cart entry
if(invalid==false){
writeNewEntry(tables, menuName, date, quantity);
finish();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
}
private void writeNewEntry(String table, String name, String dates, int q){
Cart entry = new Cart(table, name, dates, q);
FirebaseDatabase.getInstance().getReference("Cart").child(tables).push().setValue(entry);
}
Thank you so much for every help
First of all, you should not pass content to another activity by SharedPreferences.
try send it through Intent...
Sender:
Intent intent = new Intent(DineIn.this,ProductDetails.class);
intent.putExtra("tables", tables);
startActivity(intent)
Receiver(Activity case):
Intent intent = getIntent();
tables = intent.getStringExtra("tables", "");

cannot be cast to java.lang.String

chatMessages = new ArrayList<>();
listView = findViewById(R.id.list_of_messages);
Message(topic_id);
listView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
listView.setAdapter(chatAdapter);
buttonSend = findViewById(R.id.send);
fileSend = findViewById(R.id.file_send);
chatText = (EditText) findViewById(R.id.mychat);
// delete_btn = findViewById(R.id.);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
// View select;
#Override
public boolean onItemLongClick(AdapterView<?> parent, final View view, final int position, long id) {
if ( view != null){
view.setBackgroundColor(0xFFB2DFDB);
}
String value = (String) listView.getItemAtPosition(position);
msgid = chatMessages.get(position).getMessageID();
message = chatMessages.get(position).getMessageText();
userid1 = chatMessages.get(position).getUserId();
username = chatMessages.get(position).getMessageUser();
replyuser = chatMessages.get(position).getReply_user();
if (sno.equals(userid1)) {
view.setBackgroundColor(0xFFB2DFDB);
// Toast.makeText(getApplicationContext(),"Hello"+userid1+msgid,Toast.LENGTH_SHORT).show();
// ImageView edit = (ImageView) findViewById(R.id.delete_icon);
// edit.setVisibility(View.VISIBLE);
// );
topic.setText(getString(R.string.edit));
myToolbar.setLogo(R.drawable.edit);
// view.setBackgroundColor(Color.WHITE);
topic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chatMessages.remove(position);
view.setBackgroundColor(Color.TRANSPARENT);
userid1 = null;
chatAdapter.notifyDataSetChanged();
chatText.setText(message);
}
});
myToolbar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chatMessages.remove(position);
userid1 = null;
chatAdapter.notifyDataSetChanged();
chatText.setText(message);
}
});
} else {
view.setBackgroundColor(0xFFB2DFDB);
// Toast.makeText(getApplicationContext(),"Hello"+userid1+msgid,Toast.LENGTH_SHORT).show();
topic.setText(getString(R.string.reply));
myToolbar.setLogo(R.drawable.replay);
// view.setBackgroundColor(Color.WHITE);
// reply = (ImageView) findViewById(R.id.reply_icon);
// reply.setVisibility(View.VISIBLE);
topic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
replylayout = (LinearLayout) findViewById(R.id.reply_layout);
replylayout.setVisibility(View.VISIBLE);
TextView replay_name = (TextView) findViewById(R.id.reply_user);
TextView replay_text = (TextView) findViewById(R.id.reply_text);
ImageButton cancell = (ImageButton) findViewById(R.id.cancell_btn);
replay_name.setText(username);
replay_text.setText(message);
cancell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
replylayout.removeAllViews();
startActivity(getIntent());
}
});
}
});
myToolbar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
replylayout = (LinearLayout) findViewById(R.id.reply_layout);
replylayout.setVisibility(View.VISIBLE);
TextView replay_name = (TextView) findViewById(R.id.reply_user);
TextView replay_text = (TextView) findViewById(R.id.reply_text);
ImageButton cancell = (ImageButton) findViewById(R.id.cancell_btn);
replay_name.setText(username);
replay_text.setText(message);
cancell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
replylayout.removeAllViews();
startActivity(getIntent());
}
});
}
});
}
return true;
}
});
I want to implement setOnItemLongClickListener on list view when long press on list item then perform other activity like delete and edit functionality. when press long click then give error cannot be cast to java.lang.String
Replace your code with this
String value = (String) listView.getItemAtPosition(position);
With This
String value = String.valueOf(listView.getItemAtPosition(position));
The main problem is in this line
String value = (String) listView.getItemAtPosition(position);
I definitely not sure that your listview is filled with String items as later in the code you call
chatMessages.get(position).getMessageID()
So your value should be something like
ChatMessage value = (ChatMessage) listView.getItemAtPosition(position);
And in your adapter you need to change these methods (if they are not changed already):
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
String value = (String) listView.getItemAtPosition(position);
View cant be cast into string. I think above code should be (presume the item content on your list view is text):
String value = listView.getItemAtPosition(position).toString();

Why my listview is empty?

I have a arraylist in which users can input their text. And it is displayed in the screen as a listview. That works, but when i try to get the values of the arraylist it says that: Invalid index 0, size is 0. So im guessing for some reason the listview isnt populating?
This is how I add values to the list:
public class ZaidejaiActivity extends ActionBarActivity implements View.OnClickListener{
public Button mBtnIstrinti;
public Button mBtnPrideti;
public Button mBtnPradeti;
public EditText mYrasytiVarda;
public ListView mZaidejai;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zaidejai);
mBtnPrideti = (Button) findViewById(R.id.pridėtiBtn);
mBtnPrideti.setOnClickListener(this);
mYrasytiVarda = (EditText) findViewById(R.id.VardoYrasymoBtn);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, list);
// set the mZaidejai variable to your list in the xml
mZaidejai = (ListView) findViewById(R.id.sarašas);
mZaidejai.setAdapter(adapter);
mZaidejai.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// remove item from List.
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
list.remove(position);
AlertDialog.Builder builder = new AlertDialog.Builder(ZaidejaiActivity.this);
builder.setMessage("Delete?");
builder.setTitle("Confirm Action");
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
adapter.notifyDataSetChanged();
}
//checked.clear();
});
builder.setNegativeButton("Cancel", null);
builder.create();
builder.show();
}
});
mBtnPradeti = (Button) findViewById(R.id.žaistiBtn);
mBtnPradeti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// count items
int i;
for (i = adapter.getCount() - 1; i >= 0; i--) {
String obj = adapter.getItem(i);
// send items to other activity
Intent pradetiZaidima = new Intent(v.getContext(), ZaidimasActivity.class);
pradetiZaidima.putExtra("playerList", obj);
startActivity(pradetiZaidima);
}
}
});
}
#Override
public void onClick(View v) {
String input = mYrasytiVarda.getText().toString();
if(input.length() > 0)
{
// add string to the adapter, not the listview
adapter.add(input);
// no need to call adapter.notifyDataSetChanged(); as it is done by the adapter.add() method
}else{
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Klaida:");
alertDialog.setMessage("Blogai yrašytas vardas");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
}
});
alertDialog.show();
}
}
EDIT
In this activity I want to get the values of the list:
public class ZaidimasActivity extends ZaidejaiActivity {
public TextView mZaidejas;
public TextView mKlausimas;
public Button mKitasKlausimas;
public Button mGryzti;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zaidimas);
/** //get the player list from ZaidejaiActivity
Bundle recdData = getIntent().getExtras();
String myVal = recdData.getString("playerList"); */
//show the first players name
mZaidejas = (TextView)findViewById(R.id.ZaidejoVardas);
mZaidejas.setText(list.get(0));
/** mGryzti = (Button)findViewById(R.id.GryztiMeniuBtn);
mKitasKlausimas = (Button)findViewById(R.id.KitasBtn);
mKitasKlausimas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
*/
Unfortunately your list==empty. So add some values on it.
list.add("ABC");
list.add("XYZ");
and then setAdapter
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, list);
mZaidejai = (ListView) findViewById(R.id.sarašas);
mZaidejai.setAdapter(adapter);
Your not adding any values to it. And your list is empty and add some values to it like list.add("hyd");
list.add("city");
and pass those values to adapter
Rather doing
adapter.add(input);
Do
list.add(input);
adapter.notifyDataSetChanged();
So, as others have said you should change the adapter.add(input); on the onClick method to
list.add(input);
adapter.notifyDataSetChanged();
Also, on an unrelated matter, you should really move the list.remove(position); call to the following onClick method of the positive button, before the adapter.notifyDataSetChanged(); call, so it wont be removed if the user cancels the action :)
at the first time your list adapter is empty (getCount() = 0) and you do -1 in the for
mBtnPradeti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// count items
int i;
if (adapter.getCount() > 0)
{
for (i = adapter.getCount() - 1; i >= 0; i--) {
String obj = adapter.getItem(i);
// send items to other activity
Intent pradetiZaidima = new Intent(v.getContext(), ZaidimasActivity.class);
pradetiZaidima.putExtra("playerList", obj);
startActivity(pradetiZaidima);
}
}
}
});
and for this code :
mZaidejas.setText(list.get(0));
but on Create your list is empty !!!

Categories

Resources