why it doesn't display any auto corrections my array got strings
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Sentence");
alert.setMessage("type only words you taught him!!!");
// Set an EditText view to get user input
//final EditText input = new EditText(this);
//alert.setView(input);
// Get a reference to the AutoCompleteTextView in the layout
final AutoCompleteTextView textView = new AutoCompleteTextView(this);
// Get the string array
//String[] countries = getResources().getStringArray(R.array.countries_array);
// Create the adapter and set it to the AutoCompleteTextView
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mywords);
textView.setAdapter(adapter);
alert.setView(textView);
alert.setPositiveButton("Order", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value =textView.getText().toString();
String[] inputarray;
value=value.trim();
inputarray=value.split(" ");
playnum=new int[inputarray.length];
for(int j=0;j<inputarray.length;j++)
{
legit=0;
for(int i=0;i<mywords.length;i++)
{
if(info.choosetext[Integer.parseInt(mywords[i])].equalsIgnoreCase(inputarray[j])){
playnum[j]=Integer.parseInt(mywords[i]);
legit++;
}
}
if(legit==0)
break;
}
if(legit!=0){
playone=MediaPlayer.create(getBaseContext(), getResources().getIdentifier("word" + Integer.toString(playnum[0]), "raw", getPackageName()));
gottext=true;
}
}
});
alert.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
i want it to display array suggestions and on click input it into the text view and now i am talking just cause i got too much code and can't post
someone got to know how to do this without xml
At least one thing you should do is to declare the autocomplete text view in xml and get a reference to it by calling AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.textView); instead of final AutoCompleteTextView textView = new AutoCompleteTextView (this)
Here is a good tutorial on autocomplete text views:
http://www.tutorialspoint.com/android/android_auto_complete.htm
try this,
textview.setThreshold(1);
after textview.setAdapter()
Related
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.
Context: There is a custom Listview and each list item has a button in it. When you click the button an alertDialog appears with an edit text and submit button. This only happens on the first click, on subsequent clicks a Toast will simply appear with the number of times it has been clicked thus far.
When you click the submit button a toast will appear displaying the text that was entered into the editText and the number of times they have clicked on it which will presumably always be 1 since this can only happen on the first click.
Problem: The timesClicked counter is not working properly if the user so much as clicks on the editText before clicking submit. It is restting to 0 I guess. However if the user does not click on the editText then the program works normally. 0_o I'm at a loss.
Attempts at solving: I simplified the code down quite a bit to try and pinpoint the problem and this is where I am stuck. Originally I was inflating a view that only had an edit text and then I was just using builder.setPositiveButtton. I thought implementing the buttons directly in the view would fix it but that doesn't seem to be the case. I have been stuck on this for awhile. Any help would be great
Here is a video of the bug happening
private class OnSubtractClickListener implements View.OnClickListener {
final int id; //id of list item that was clicked
int timesClicked;
Toast toast;
public OnSubtractClickListener(int id, View view) {
super();
this.id = id;
timesClicked = 0;
}
#Override
public void onClick(View view) {
if (timesClicked != 0) {
toast.setText(Integer.toString(timesClicked));
toast.show();
}
else{
toast = Toast.makeText(view.getContext(), "", Toast.LENGTH_SHORT);
final View dialogView = LayoutInflater.from(view.getContext()).inflate(R.layout.dialog_add_notes, null);
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setView(dialogView);
builder.setTitle("Subtract cigar?");
builder.setIcon(R.mipmap.monkey_launcher);
final AlertDialog dialog = builder.create();
Button yesButton = (Button)dialogView.findViewById(R.id.dialog_notes_yes_button);
yesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editText = (EditText)dialogView.findViewById(R.id.dialog_editText);
String userInput = editText.getText().toString();
String timesClickedString = Integer.toString(++timesClicked);
toast.setText(timesClickedString + ": " + userInput);
toast.show();
dialog.dismiss();
}
});
dialog.show(); //new
}
}
}
You can make class that extend Dialog.
example:
public class CustomDialog extends Dialog {
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WindowManager.LayoutParams lpWindow = new WindowManager.LayoutParams();
lpWindow.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
lpWindow.dimAmount = 0.8f;
getWindow().setAttributes(lpWindow);
setContentView(R.layout.activity_custom_dialog);
editText = (EditText) findViewById(R.id.editText);
}
}
You can use this dialog..
mCustomDialog = new CustomDialog();
mCustomDialog.show();
You can make the layout as you wish.
======================================================================
You can use AlertDialog.Builder.setPositiveButton.
site : setPositiveButton
example...
toast = Toast.makeText(view.getContext(), "", Toast.LENGTH_SHORT);
final View dialogView = LayoutInflater.from(view.getContext()).inflate(R.layout.dialog_add_notes, null);
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setView(dialogView);
builder.setTitle("Subtract cigar?");
builder.setIcon(R.mipmap.monkey_launcher);
builder.setPositiveButton("text", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
EditText editText = (EditText)dialogView.findViewById(R.id.dialog_editText);
String userInput = editText.getText().toString();
String timesClickedString = Integer.toString(++timesClicked);
toast.setText(timesClickedString + ": " + userInput);
toast.show();
}
});
final AlertDialog dialog = builder.create();
dialog.show(); //new
I found the solution. Basically what was happening was that when the Keyboard appeared it would cause the listview to adjust the size recreating the whole listview with recycled/old versions of the list items from before the dialog appeared -effectively undoing any changes made to the ListView items by the dialog.
In your listview XML add this:
android:descendantFocusability="beforeDescendants"
In Mainfest.xml:
<activity android:name= ".yourActivity"
android:windowSoftInputMode="adjustPan"/>
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();
In my app, information like file names are stored in the externally storage. They are then implemented into the app with the help of ListView. I can delete files individually with OnItemLongClickListener() but I want to select multiple files in ListView and then click a Delete button. How can I do this? My MainActivity file is below:
public class MainActivity extends AppCompatActivity {
ArrayList<FileName> filenames;
ListViewAdapter adapter;
ListView lv_filenames;
public Handler handler;
private String _path = Environment.getExternalStorageDirectory() + "/sample_directory/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditorManager manager = new EditorManager(getApplicationContext());
manager.CreateNewDirectory();
lv_filenames = (ListView) findViewById(R.id.list);
handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
filenames = manager.GetList();
adapter = new ListViewAdapter(getApplicationContext(), R.layout.listView, filenames);
lv_filenames.setAdapter(adapter);
lv_filenames.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int file_name, long l) {
final File deleteFile = new File(_path + filenames.get(file_name).getName());
final String tempFileName = filenames.get(file_name).getName() + " is deleted";
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Delete File");
builder.setMessage("Do you really want to delete this file?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
boolean deleted = deleteFile.delete();
if (deleted) {
Toast.makeText(getApplicationContext(), tempFileName, Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// Do nothing.
}
});
builder.create();
AlertDialog dialog = builder.create();
dialog.show();
return false;
}
});
}
}
I deleted the extra code. Thanx for helping!
PS -
I heard that in Android 4.4 + files can't be deleted like this. What should I do?
EDIT -
I have seen those answers. But I want to create a button on whose click the check/uncheck buttons would be available. How can I do that? I want the Check/Uncheck buttons to be visible only when I click delete button. Also the other answers are a bit confusing.
I would have a button with a edit or delete icon and have it change the ListView to one with checkboxes in each view. Either make a new ListView with a new Adapter or just tell adapter and set a boolean in it, and then dataSetChange the Adapter.
I fixed my problem. I use a SparseBooleanAdapter to register the delete options.Then I press delete button to delete them.
this question is is similar to this
* Android - Listview delete item and Refresh
and this (the same , but I added the full code here to check if I have any problems in my code):
please give me code example. . .
can i call an intent to refresh my list ?
I cant refresh my adapter with :
adapter.notifyDataSetChanged();
I tried:
adapter.remove(adapter.getItem(pos));
but without success, just one time (weird...).
there is another answer there:
Call that Activity once again Using Intent
sombody can give me the exact code for this (or for the adapter/cursor) ?
I am trying this for a couple of hours without success.
my full code:
protected void onCreate (Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
setContentView(R.layout.personalmessageview);
headtitle= getIntent().getExtras().getString("head");
setTitle(headtitle);
personalresults = getIntent().getExtras().getStringArrayList("personalres");
personalresultswithtime = getIntent().getExtras().getStringArrayList("personalrestime");
// setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,personalresults));
ListView list = (ListView)findViewById(R.id.listview_personal);
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, personalresults);
list.setAdapter(adapter);
registerForContextMenu(list);
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
String time = personalresultswithtime.get(pos).toString();
Show_Alert_box(v.getContext(),"Please select action.",time,pos);
return true;
}
});
public void Show_Alert_box(Context context, String message,String time,int position)
final String timestamp = time;
final int pos = position;
final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(getString(R.string.app_name));
alertDialog.setButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try
{
db = databaseHelper.getWritableDatabase();
db.delete("messages","timestamp" + "=?", new String[] { timestamp });
Log.d("DB"," delete! ");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PersonalMessageView.this, android.R.layout.simple_list_item_1, personalresults);
adapter.remove(adapter.getItem(pos)); //not working t all! why ?
list.notify();
list.invalidate();
personalresults.remove(pos);
personalresultswithtime.remove(pos);
adapter.notifyDataSetChanged();
db.close();
}
catch(Exception e)
{
}
} });
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
} });
alertDialog.setMessage(message);
alertDialog.show();
}
Inside your onClick of Dialog, you are dealing with an entirely new Adapter.There is no accociation of adapter(inside onClick()) to the listView Either you should say list.setAdapter(adapter); inside the onClick() method or make the adapter global.
instead of using
adapter.remove(adapter.getItem(pos));
use
string str=list.getItemAtPosition(index).toString();
personalresults.remove(str);
adapter.notifyDataSetChanged();