Refresh listview/display newly added data to listview android - android

I'm new to Android Sqlite DB Dev't so I need your help guys. I was able to do the basic CRUD operations. Now I want to know how to refresh the listview to display the newly added data. I've looked into adapter.notifyDataSetChanged but I wonder why it's not working for me. Here's what I've tried so far
private void initControls() {
SearchAuto = (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);
String[] SearchItems = getResources().getStringArray(R.array.DogSearch);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.searchitems,SearchItems);
SearchAuto.setAdapter(adapter);
SearchAuto.setThreshold(0);
search = (Button) findViewById (R.id.handle);
search.setOnClickListener(this);
lv = (ListView) findViewById (R.id.lv);
values = dbHelper.getAllAnimals(ANIMALTYPE);
for (int i = 0; i < values.length; i++) {
lvAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
lv.setAdapter(lvAdapter);
}
// TODO onItemClick
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
String strDog = parent.getItemAtPosition(position).toString();
Intent i = new Intent(DogClass.this, Dogs.class);
i.putExtra("dog_name", strDog);
startActivity(i);
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.addanimal, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// get prompt_addprayer.xml view
LayoutInflater li = LayoutInflater.from(this);
View promptsView = li.inflate(R.layout.prompt_addanimal, null);
AlertDialog.Builder alertDialogBuilder =
new AlertDialog.Builder(this);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText etBreed = (EditText) promptsView
.findViewById(R.id.etBreed);
final EditText etDescription = (EditText) promptsView
.findViewById(R.id.etDescription);
final EditText etDiet = (EditText) promptsView
.findViewById(R.id.etDiet);
final EditText etShelter = (EditText) promptsView
.findViewById(R.id.etShelter);
final EditText etHygiene = (EditText) promptsView
.findViewById(R.id.etHygiene);
final EditText etMedication = (EditText) promptsView
.findViewById(R.id.etMedication);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int id) {
String strAnimalType = ANIMALTYPE;
String strBreed = etBreed.getText().toString();
String strDesc = etDescription.getText().toString();
String strDiet = etDiet.getText().toString();
String strShelter = etShelter.getText().toString();
String strHygiene = etHygiene.getText().toString();
String strMedication = etMedication.getText().toString();
dbHelper.addAnimalInfo(strAnimalType, strDesc,
strDiet, strShelter, strHygiene, strMedication, strBreed);
Toast.makeText(DogClass.this, "Data has been added successfully!",
Toast.LENGTH_SHORT).show();
lvAdapter.notifyDataSetChanged();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
return true;
}
Any ideas? I really need to get this working. Thanks

dbHelper.addAnimalInfo(strAnimalType, strDesc, strDiet, strShelter, strHygiene, strMedication, strBreed);
Toast.makeText(DogClass.this, "Data has been added successfully!",
Toast.LENGTH_SHORT).show();
lvAdapter.notifyDataSetChanged();
This is where you lacked. What you did is, you just inserted data into database, still you are remaining to bring data from database and bind it with adapter, and after that you may call notifyDataSetChanged();, and you'll achieve what you want...
Try this:
dbHelper.addAnimalInfo(strAnimalType, strDesc, strDiet, strShelter, strHygiene, strMedication, strBreed);
Toast.makeText(DogClass.this, "Data has been added successfully!",
Toast.LENGTH_SHORT).show();
values = dbHelper.getAllAnimals(ANIMALTYPE);
lvAdapter.clear();
lvAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
lvAdapter.notifyDataSetChanged();
Note: you should not write this way. Your code:
for (int i = 0; i < values.length; i++) {
lvAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
lv.setAdapter(lvAdapter);
}
If your getAllAnimals() method is returning an arrayList then you simply need to:
lvAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
lv.setAdapter(lvAdapter);
The last argument of your ArrayAdapter constructor needs List<Item> to be passed. And then just call setAdapter(adapter) of ListView.
For more clarification, refer this SO link: notifyDataSetChanged example
http://androidadapternotifiydatasetchanged.blogspot.in

Related

I want spinner to automatically be opened when the page gets loaded android

I want the spinner drop down to get opened automatically when the page gets loaded.
what can i do for that?
<Spinner
android:entries="#array/cities_arrays"
android:id="#+id/spinner"
android:layout_width="230sp"
android:gravity="center_horizontal"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:spinnerMode="dropdown"
tools:layout_editor_absoluteY="16dp"
android:background="#drawable/spinner_styling"
android:layout_marginLeft="80sp"
android:layout_marginRight="80sp"
android:layout_marginTop="10sp"
android:layout_below="#+id/app_bar"/>
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
placesList = new ArrayList<>();
cities = getResources().getStringArray(R.array.cities_arrays);
Spinner spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, cities);
listView = (ListView) findViewById(R.id.listView);
// This is to avoid automatic keypad opening as soon as the page loads.
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
placesList.clear();
autoCompView = (AutoCompleteTextView) findViewById(R.id.autoCompleteText);
autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this, R.layout.list_item));
autoCompView.setOnItemClickListener(this);
listAdapter = new ListViewAdapter(this, R.layout.row,placesList);
spinner.setAdapter(adapter);
// Open the Spinner when your activity will load...
spinner.performClick();
mButton = (Button) findViewById(R.id.plus_button);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// inflate alert dialog xml
LayoutInflater li = LayoutInflater.from(mContext);
View dialogView = li.inflate(R.layout.custom_dialog, null);
android.support.v7.app.AlertDialog.Builder alertDialogBuilder = new android.support.v7.app.AlertDialog.Builder(mContext);
// set title
alertDialogBuilder.setTitle("Add Location");
// set custom dialog icon
//alertDialogBuilder.setIcon(R.drawable.ic_launcher);
// set custom_dialog.xml to alertdialog builder
alertDialogBuilder.setView(dialogView);
final EditText userInput = (EditText) dialogView
.findViewById(R.id.autoCompleteTextView);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
//etOutput.setText(userInput.getText());
dialog.cancel();
}
})
.setNegativeButton("Done",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
// create alert dialog
android.support.v7.app.AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
index = arg0.getSelectedItemPosition();
city = cities[index];
if(index != 0) {
PLACES_OF_INTEREST_URL = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" + city + "+point+of+interest&language=en&key=" + API_KEY + "";
listView.clearAnimation();
listAdapter.clear();
new GetPlaces().execute();
listAdapter.addAll(placesList);
listView = (ListView) findViewById(R.id.listView);
listView.invalidateViews();
listAdapter.notifyDataSetChanged();
listView.setAdapter(listAdapter);
System.out.println(city);
Toast.makeText(getApplicationContext(), "Selected: " + city, Toast.LENGTH_LONG).show();
}
index = -1;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
Toast.makeText(getApplicationContext(),"Please Select a City!", Toast.LENGTH_LONG).show();
}
});
}
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.application.microsoft.wayfarer, PID: 24758
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.application.microsoft.wayfarer/com.application.microsoft.wayfarer.activities.MainActivity}: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
You can achieve this like below :-
Spinner yourSpinner = (Spinner) findViewById(R.id.yourSpinner);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this,R.array.planets, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
yourSpinner.setAdapter(adapter);
// Open the Spinner when your activity will load...
yourSpinner.performClick();
and in your method comment this below line
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

I want to get the selected value from List view in alert dialog

I have ArrayList of object (citiesInSpinner) each object have two value(Id, Name)
I have already get it in alert dialog
I use this function to alert dialog:
public void test()
{
FillSpinner();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(SearchFligtsActivity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.custom, null);
alertDialog.setView(convertView);
alertDialog.setTitle("Select City");
ListView lv = (ListView) convertView.findViewById(R.id.listView1);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,citiesInSpinner);
lv.setAdapter(adapter);
/* alertDialog.setItems(citiesInSpinner, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
/////
}
});*/
alertDialog.show();
/**/
}
now I want to make something to get the ((ID)) of item (I mean the Id of City)
I tried to do that but I failed...
any help Please !!
and thank you
Simply use
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
City city = citiesInSpinner.get(position)
//get your id -> city.Id
}
});

Display more than one item in array list

Hello guys i would like to display more than one item horizontally in a single list. This items are picked from the dialog box that has two button ok and cancel. When you click okay it should pick the values from the edit text and a string value from the dialog and display in the list horizontally.
Array List Adapter
public class VehicleListAdapter extends ArrayAdapter<String> {
private Context context;
private List<String> vehicle_no;
public VehicleListAdapter(Context context, int resource, List<String> objects) {
super(context, resource, objects);
this.context = context;
this.vehicle_no = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//get the vehicle number we are displaying
String my_vehicle = vehicle_no.get(position);
//get the inflater and inflate the XML layout for each item
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.vehicle_num_layout, null);
TextView txt_vehicle_num = (TextView) view.findViewById(R.id.txt_vehicle_num);
txt_vehicle_num.setText(my_vehicle);
return view;
}
}
Activity with the list
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// get user input and set it to result
// edit text
if(userInput.getText().toString().trim().length()==0) {
userInput.setError("Vehicle Number Required");
focus.start();
String stime = focus.getText().toString();
}
else {
result.setText(userInput.getText());
ListView list = (ListView) findViewById(R.id.list);
vehicle_list.add(userInput.getText().toString().trim());
VehicleListAdapter listAdapter = new VehicleListAdapter(StartWatch.this, 0, vehicle_list);
list.setAdapter(listAdapter);
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
First of all, why you are creating new listview every time when user hit ok of dialog. Remove this line ListView list = (ListView) findViewById(R.id.list); from dialog positive button click.
Add line as shown below after your code in positive button click
VehicleListAdapter listAdapter = new VehicleListAdapter(StartWatch.this, 0, vehicle_list);
list.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged(); // Add this line to tell adapter that data has been changed

2 dynmically created spinners -> but only 1 onItemSelected

i got 2 dynamically created spinners in 1 Activity.
private void populateSpinner() {
AlertDialog.Builder adb2 = new AlertDialog.Builder(this);
LayoutInflater adbInflater2 = LayoutInflater.from(this);
View SpinnerLayout = adbInflater2.inflate(R.layout.spinner, null);
adb2.setView(SpinnerLayout);
adb2.setTitle("Kostenstelle auswählen:");
spinnerKOST = (Spinner) SpinnerLayout.findViewById(R.id.spinner);
List<String> lables = new ArrayList<String>();
lables.add("");
spinnerKOST.setSelection(1, false);
for (int i = 0; i < KostList.size(); i++) {
lables.add(KostList.get(i).getKost());
}
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>
(this,android.R.layout.simple_spinner_dropdown_item, lables);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerKOST.setAdapter(spinnerAdapter);
// use .create to get the AlertDialog
AlertDialog dialog = adb2.create();
// set an OnShowListener
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
public void onShow(DialogInterface dialog) {
spinnerKOST.setOnItemSelectedListener(StaffActivity.this);
}
});
dialog.show();
}
and the second:
private void populateSpinner2() {
AlertDialog.Builder adb2 = new AlertDialog.Builder(this);
LayoutInflater adbInflater2 = LayoutInflater.from(this);
View SpinnerLayout = adbInflater2.inflate(R.layout.spinner, null);
adb2.setView(SpinnerLayout);
adb2.setTitle("Box auswählen:");
spinnerBox = (Spinner) SpinnerLayout.findViewById(R.id.spinner);
List<String> lables = new ArrayList<String>();
lables.add("");
spinnerBox.setSelection(1, false);
for (int i = 0; i < BoxesList.size(); i++) {
lables.add(BoxesList.get(i).getBoxer_mail());
}
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>
(this,android.R.layout.simple_spinner_dropdown_item, lables);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerBox.setAdapter(spinnerAdapter);
AlertDialog dialog = adb2.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
public void onShow(DialogInterface dialog) {
spinnerBox.setOnItemSelectedListener((OnItemSelectedListener) StaffActivity.this);
}
});
dialog.show();
}
they are pretty the same, as you see.
Normally I use for every spinner 1 public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
Before I only had 1 Spinner per Activity and 1 public void onItemSelected.
Now I got 2 Spinner in the Activity but still 1 public void onItemSelected.
How I can use both spinners?
Use two spinner and toggle view viible and invisible between them
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Spinner spinner = (Spinner) parent;
if(spinner.getId() == R.id.spinner1)
{
//spinner1
}
else if(spinner.getId() == R.id.spinner2)
{
//spinner2
}
}

Want to update the list in every entry view?

i'am having a list with textview, many data's are flowing in list and having one textview in xml....problem is i want to update the every textview entry in the list..i want to update the (TAG_QTY) textview in list when every value entry...
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_BARCODE, TAG_DIVISION, TAG_MRP,TAG_QTY}, new int[] {
R.id.txt, R.id.txt1, R.id.mrp,R.id.qty1 });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//String name = ((TextView) view.findViewById(R.id.qty1)).getText().toString();
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts, null);
//final View textEntryView;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
fourth = (TextView)findViewById(R.id.qty1);
userInput = (EditText)promptsView.findViewById(R.id.editTextDialogUserInput);
//String ed = userInput.getText().toString();
//final int ed= Integer.parseInt(userInput.getText().toString());
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
String ed = userInput.getText().toString().trim();
fourth.setText(ed);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
);
In order to get the list view child
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
View c = lv.getChildAt(position);
// c is your list view child which is clicked
final TextView tv = (TextView) c.findViewById(R.id.qty1);
// tv is your textview of whom vwlue you have to change.
//changes the value of textview here and den notify data set changed and refresh the list.
}
});

Categories

Resources