There is probably a simple answer for this: when my alert box shows, I try to store the contents of a EditText in a string but, the string is always empty.
contents = inputElement.getText().toString();
code:
public class MainActivity extends Activity {
EditText inputElement;
Spinner spinner;
MySQLiteAdapters adapter;
MySQLiteHelper helper_ob;
AlertDialog dialog;
List<String> lables;
String contents;
ArrayAdapter<String> dataAdapter;
public static final String PREFS = "examplePrefs";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button start = (Button) findViewById(R.id.start);
//start.setVisibility(View.GONE);
spinner = (Spinner) findViewById(R.id.spinner1);
inputElement = new EditText(this);
adapter = new MySQLiteAdapters(getApplicationContext());
lables = adapter.getAllLabels();
exmaplePrefs = getSharedPreferences(PREFS, 0);
editor = exmaplePrefs.edit();
final AlertDialog firstTimeUse = new AlertDialog.Builder(this)
.setView(inputElement)
.setTitle("TITLE")
.setCancelable(false)
.setPositiveButton(android.R.string.ok, null).create();
firstTimeUse.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
Button b = firstTimeUse.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
contents = inputElement.getText().toString();
if (contents.matches("")){
showAlertbox("You Must Enter a Team");
}else{
adapter.insertTeamDetails(contents);
List<String> lables = adapter.getAllLabels();
dataAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item, lables);
spinner.setAdapter(dataAdapter);
lables.add("Add New Team...");
firstTimeUse.dismiss();
}
}
});
}
});
if (lables.isEmpty())
{
firstTimeUse.show();
}
else{
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
lables.add("Add New Team...");
}
Thanks in advance
You create a new instance of inputElement in onCreate:
inputElement = new EditText(this);
So the text in it is always empty as you don't add it to the layout.
Instantiate it from the layout using findViewById or add it to the layout in the code.
SetView(View view) takes view element, I am not sure how you are adding EditText there. You can add edit text in layout file itself something like this:
and declare in onCreate something like this:
inputElement = (EditText) findViewById(R.id.EditTextPassword);
You can get string like this:
inputElement.getText().toString();
Related
I am developing an e-commerce android application using Firebase real-time database and i am using spinners to show my products category wise in multiple spinners. What i want is when user selects something from first spinner and press add button then that value comes in an array-list named current_products and then user selects something or not from rest of spinners and these values should keep coming to current_products(array-list). I have add button for every spinner so when user press add button for a specific spinner it should get the selected product from that spinner and add into current_products. I am trying to do the same thing the problem i am facing is when a user selects something from a spinner and presses add button the value gets added in current_products but when again user open that spinner and select a different product then this product is also added in current_products instead of removing the previous product from that spinner and adding the newly selected product.
Here is look of my database for further understanding
here is my code:
private Spinner scarfs_spinner, buttons_spinner, pins_spinner, laces_spinner;
private Button addScarfBtn, addButtonBtn, addPinsBtn, addLacesBtn;
private DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
private ArrayList<String> scarfsList = new ArrayList<>();
private ArrayList<String> buttonsList = new ArrayList<>();
private ArrayList<String> lacesList = new ArrayList<>();
private ArrayList<String> pinsList = new ArrayList<>();
private ArrayList<Products> all_products = new ArrayList<>();
private ArrayList<String> current_products = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customization);
scarfs_spinner = (Spinner) findViewById(R.id.scarfs_spinner);
buttons_spinner = (Spinner) findViewById(R.id.buttons_spinner);
pins_spinner = (Spinner) findViewById(R.id.pins_spinner);
laces_spinner = (Spinner) findViewById(R.id.laces_spinner);
addScarfBtn = (Button) findViewById(R.id.addScarfBtn);
addButtonBtn = (Button) findViewById(R.id.addButtonsBtn);
addPinsBtn = (Button) findViewById(R.id.addPinsBtn);
addLacesBtn = (Button) findViewById(R.id.addLacesBtn);
showDataSpinner();
}
private void showDataSpinner()
{
databaseReference.child("Products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
for(DataSnapshot item : dataSnapshot.getChildren()) {
if (item.child("category").getValue(String.class).equals("Scarfs"))
{
scarfsList.add(item.child("pname").getValue(String.class));
}
if (item.child("category").getValue(String.class).equals("Buttons"))
{
buttonsList.add(item.child("pname").getValue(String.class));
}
if (item.child("category").getValue(String.class).equals("Pins"))
{
pinsList.add(item.child("pname").getValue(String.class));
}
if (item.child("category").getValue(String.class).equals("Laces"))
{
lacesList.add(item.child("pname").getValue(String.class));
}
all_products.add(item.getValue(Products.class));
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(CustomizationActivity.this, R.layout.style_spinner, scarfsList);
ArrayAdapter<String> arrayAdapter1 = new ArrayAdapter<>(CustomizationActivity.this, R.layout.style_spinner, buttonsList);
ArrayAdapter<String> arrayAdapter2 = new ArrayAdapter<>(CustomizationActivity.this, R.layout.style_spinner, pinsList);
ArrayAdapter<String> arrayAdapter3 = new ArrayAdapter<>(CustomizationActivity.this, R.layout.style_spinner, lacesList);
scarfs_spinner.setAdapter(arrayAdapter);
buttons_spinner.setAdapter(arrayAdapter1);
pins_spinner.setAdapter(arrayAdapter2);
laces_spinner.setAdapter(arrayAdapter3);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
addScarfBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
current_products.add(scarfs_spinner.getSelectedItem().toString());
}
});
addButtonBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
current_products.add(buttons_spinner.getSelectedItem().toString());
}
});
addPinsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
current_products.add(pins_spinner.getSelectedItem().toString());
}
});
addLacesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
current_products.add(laces_spinner.getSelectedItem().toString());
}
});
}
Assign the item to a particular array position and before adding an item from the spinner, check if that position in the database is empty then populate it else clear the position content before adding (replacing) the new item.
Im trying to simply add a Item to a Listview and display it. But if I add it it just shows me the path of that string istead of the tring itself. I'm sure it's a simple mistake but I cant find it.
public class zutatenHinzufuegen extends AppCompatActivity {
private ArrayList<String> zutatenliste;
private ListView zutatenView;
private ArrayAdapter<String> zutatenadapter;
private TextInputLayout zutatInput;
private TextInputLayout anzahlInput;
private int anzahlint;
private String einheitInput;
private Button hinzufuegen_button;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.zutaten_hinzufuegen_linear);
getSupportActionBar().setTitle(R.string.menu_zutaten);
// Spinner
final Spinner einheiten_spinner = (Spinner) findViewById(R.id.spinner_einheiten2);
ArrayAdapter<String> einheiten_adapter = new ArrayAdapter<String>(zutatenHinzufuegen.this,
android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.einheiten));
einheiten_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
einheiten_spinner.setAdapter(einheiten_adapter);
// List
zutatInput =(TextInputLayout) findViewById(R.id.textInputZutat2);
einheitInput =(String) einheiten_spinner.getSelectedItem().toString();
anzahlInput = (TextInputLayout) findViewById(R.id.textInputAnzahl2);
try {
anzahlint = Integer.parseInt(anzahlInput.toString());
}catch (NumberFormatException nfe){}
hinzufuegen_button = findViewById(R.id.zutat_hinzufuegen_button2);
zutatenView =(ListView) findViewById(R.id.zutatenliste2);
zutatenliste= new ArrayList<>();
zutatenadapter = new ArrayAdapter<String>(this,R.layout.zutatenliste_items,R.id.textitemliste,zutatenliste);
// zutatenadapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item, zutatenliste);
zutatenView.setAdapter(zutatenadapter);
hinzufuegen_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// hinzufuegen(v , einheiten_spinner);
ZutatClass newzutat = new ZutatClass(zutatInput.toString(),anzahlint,einheitInput);
zutatenliste.add((String) newzutat.zutat_sting);
zutatenadapter.notifyDataSetChanged();
}
});
}
}
This is what I see when i press the button a few times
I'm new to Android Studio and java so I hope it's not to much of a mess.
Thanks in advance.
First of all, you need to add Edittext inside the TextInputLayout and then get a text like this ZutatClass newzutat = new ZutatClass(zutatInput.getEditText().getText().toString(),anzahlint,einheitInput); on your on click method
I guess the issue is that you are trying to convert a TextInputLayout to string instead of getting the text from it and convert it to string , try the code below
hinzufuegen_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// hinzufuegen(v , einheiten_spinner);
ZutatClass newzutat = new ZutatClass(zutatInput.getEditText().getText().toString(),anzahlintgetEditText().g etText().toString()
,einheitInput);
zutatenliste.add((String) newzutat.zutat_sting);
zutatenadapter.notifyDataSetChanged();
}
});
zutatInput.toString() --> zutatInput.getEditText().getText()
anzahlint.toString() --> anzahlint.getEditText().getText().toString()
In this application, I have a listview and a sqlitedatabase. There is a floating action button which on clicking displays a dialog box containing two edittext one for name and another for number. The problem is that the after clicking on the add option of the dialog box the entry is not shown on the listview. But when the activity is destroyed and onCreate is called again on the activity , the entry is shown.
I tried using adapter.notifyDataSetChanged() but it doesn't work. The code is shown below :
Code
public class DetailsActivity extends AppCompatActivity {
private DatabaseManager manager;
private ListView listView;
private SimpleCursorAdapter adapter;
final String[] from=new String[] {UserDatabase.NAME,UserDatabase.NUMBER};
final int[] to=new int[] {R.id.nameDisplay,R.id.phoneDisplay};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
manager = new DatabaseManager(getApplicationContext());
manager.open();
Cursor cursor=manager.fetch();
listView = (ListView) findViewById(R.id.listViewId);
listView.setEmptyView(findViewById(R.id.empty));
adapter = new SimpleCursorAdapter(getApplicationContext(),
R.layout.row_item, cursor, from, to, 0);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(DetailsActivity.this);
LayoutInflater inflater = DetailsActivity.this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.custom_dialog, null);
dialogBuilder.setView(dialogView);
final EditText name = (EditText) dialogView.findViewById(R.id.dialogEditNmID);
final EditText phone = (EditText) dialogView.findViewById(R.id.dialogEditPhID);
dialogBuilder.setTitle("Add Details");
dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!TextUtils.isEmpty(name.getText().toString()) &&
!TextUtils.isEmpty(phone.getText().toString())) {
/*adapter.notifyDataSetChanged();
manager.insert(name.getText().toString(), phone.getText().toString());
Toast.makeText(getApplicationContext(),
"Added " + name.getText().toString(), Toast.LENGTH_SHORT).show();*/
insertData(name.getText().toString(),phone.getText().toString());
} else {
Toast.makeText(getApplicationContext(),
"Empty field(s)", Toast.LENGTH_SHORT).show();
}
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog b = dialogBuilder.create();
b.show();
// listView.setAdapter(adapter);
//adapter.notifyDataSetChanged();
}
});
}
public void insertData(String fname,String phnumber){
manager.insert(fname,phnumber);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
Some of the statements are commented because I tried to get the desired result but couldn't get it.
There's a couple things here you have to change. Taking a look at this code:
dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!TextUtils.isEmpty(name.getText().toString()) && !TextUtils.isEmpty(phone.getText().toString())) {
adapter.notifyDataSetChanged();
manager.insert(name.getText().toString(), phone.getText().toString());
Toast.makeText(getApplicationContext(), "Added " + name.getText().toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Empty field(s)", Toast.LENGTH_SHORT).show();
}
}
});
When you click the "Add" button, right away you call adapter.notifyDataSetChanged();. In your case, you are only supposed to call that after you have added items to listView, but you haven't added anything yet.
You insert into your database using manager.insert(name.getText().toString(), phone.getText().toString());, but you don't update listView with your newly added data. You need to insert that data to the database, and then also add that data to listView.
Now you can call adapter.notifyDataSetChanged();.
I would recommend that when you want to insert into your database, create a method which will insert the data, add the new data to the listView, and then tell the adapter to refresh.
Edit
Regarding your recent edit, there's still a few things that need to be taken care of.
You should not have listView.setAdapter(adapter) in the method. You had it right the first time (in onCreate() but before the dialog builder).
You call manager.insert(fname,phnumber);, but still do not add the newly inserted data to listView.
Here's pseudocode for what you should have in your method:
public void insertData(String fname,String phnumber){
manager.insert(fname,phnumber);
// Code to add the data you just inserted into the manager above to `listView`.
adapter.notifyDataSetChanged();
}
Remember, adapter.notifyDataSetChanged(); only updates listView if there's changes to listView, and as of right now you haven't added/deleted/modified listView.
After you insert the entries in your database, you should fetch the data again so that your list has the newest entry. So you can either modify your code to be able to add a data point to the list you are passing to the adapter or refetch the data from the database after insertions and before notifyDatasetChanged().
i have did some changes into the code please try it and let me know if it is helpful or not
public class DetailsActivity extends AppCompatActivity {
private DatabaseManager manager;
private ListView listView;
private SimpleCursorAdapter adapter;
final String[] from=new String[] {UserDatabase.NAME,UserDatabase.NUMBER};
final int[] to=new int[] {R.id.nameDisplay,R.id.phoneDisplay};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
manager = new DatabaseManager(getApplicationContext());
manager.open();
listView = (ListView) findViewById(R.id.listViewId);
listView.setEmptyView(findViewById(R.id.empty));
adapter = new SimpleCursorAdapter(getApplicationContext(),R.layout.row_item, cursor, from, to, 0);
//adapter.notifyDataSetChanged();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(DetailsActivity.this);
LayoutInflater inflater = DetailsActivity.this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.custom_dialog, null);
dialogBuilder.setView(dialogView);
final EditText name = (EditText) dialogView.findViewById(R.id.dialogEditNmID);
final EditText phone = (EditText) dialogView.findViewById(R.id.dialogEditPhID);
dialogBuilder.setTitle("Add Details");
dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!TextUtils.isEmpty(name.getText().toString()) &&
!TextUtils.isEmpty(phone.getText().toString())) {
adapter.notifyDataSetChanged();
manager.insert(name.getText().toString(), phone.getText().toString());
Toast.makeText(getApplicationContext(),
"Added " + name.getText().toString(), Toast.LENGTH_SHORT).show();
Cursor cursor = manager.fetch();
listView.setAdapter(adapter);
} else {
Toast.makeText(getApplicationContext(),
"Empty field(s)", Toast.LENGTH_SHORT).show();
}
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog b = dialogBuilder.create();
b.show();
// listView.setAdapter(adapter);
//adapter.notifyDataSetChanged();
}
});
}}
Try to use notifyDataSetChanged after insert operation. In all place where you call(try to call) notify manager data isn't change yet.
i want to add listview item dynamically. i had done this but when i restart the app listview item disappear. How can i save this item permanently to listview. please suggest
public class ChatWithAttorney extends Activity {
ImageView btnBack;
ListView chatList;
EditText etMsg;
Button btnSend;
String msg_to_send;
ArrayAdapter<String> adapter;
ArrayList<String> listMsg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatwithattorny);
btnBack = (ImageView) findViewById(R.id.btnback);
chatList = (ListView) findViewById(R.id.chatList);
etMsg = (EditText) findViewById(R.id.etMsg);
btnSend = (Button) findViewById(R.id.btnSend);
listMsg = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, R.layout.chat_list_text, R.id.tvSentMsg,listMsg);
chatList.setAdapter(adapter);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
msg_to_send = URLEncoder.encode(etMsg.getText().toString(),
"utf-8");
listMsg.add(msg_to_send);
adapter.notifyDataSetChanged();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
}
Put those ArrayList items in a database or SharedPreference and read those items when resuming your activity.
You can use Local database , SharedPreference or Static arraylist for storing the messages
AT the Time of Destroy Serialize the List data.
And Deserilize when Application Starts Again.
Building my first app and can't find a solution by myself.
What my app does:
MainActivity prompts user to input player amount
presses Ok, input passed to next activity
now I want, that the user is prompted to input the player names, one by one with an AlertDialog. Those names, should be stored in an Array.
My code so far:
public class MainScreen extends AppCompatActivity {
private static final String TAG = MainScreen.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
try {
Intent intent = getIntent();
final int sumPlayers = getIntent().getIntExtra("sumPlayers", 0);
final List<String> playerNames = new ArrayList<>();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final EditText input = new EditText(getBaseContext());
input.setTextColor(Color.BLACK);
//input.setSingleLine();
for (int c=0; c<sumPlayers; c++) {
builder.setTitle("Input Player Name");
builder.setView(input);
builder.setPositiveButton("ADD", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
playerNames.add(input.getText().toString());
}
});
builder.show();
}
ArrayAdapter<String> playerAdapter = new ArrayAdapter<String>(this, R.layout.player_list_item, R.id.editText, playerNames);
ListView listView = (ListView) findViewById(R.id.listView_main);
listView.setAdapter(playerAdapter);
} catch (Exception e) {
System.out.println("2te Act");
Log.e(TAG, "Error#: ", e);
}
}
}
I get this Exception # builder.show();
Java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
It's working without the for loop except one minor problem.
When I set the input field to setSingleLine(); the listView stays empty.
You are creating a single AlertDialog.Builder and repeatedly setting the title, view, and positive button with different values. You likely need to move this logic inside the for loop:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final EditText input = new EditText(getBaseContext());
input.setTextColor(Color.BLACK);
//input.setSingleLine();