I'm working on creating a dictionary and I'm trying to create ListMenu dynamically as it is created automatically while filtering words from database alphabetically.
I created a ListMenu manually, but cannot turn it into dynamic one. Does anyone have an idea how to create the ListMenu dynamically?
Here's my code:
package ge.gtug;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Settings extends ListActivity{
String listItems[] = {"AboutUs", "AboutApp", "Feedback"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Settings.this, android.R.layout.simple_list_item_1, listItems));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
String koba = listItems[position];
super.onListItemClick(l, v, position, id);
try{
Class myClass1 = Class.forName("ge.gtug." + koba);
Intent myIntent1 = new Intent(Settings.this, myClass1);
startActivity(myIntent1);
}catch(ClassNotFoundException e){
e.printStackTrace();
try {
Class myClass2 = Class.forName("ge.gtug." + koba);
Intent myIntent2 = new Intent(Settings.this, myClass2);
startActivity(myIntent2);
}catch(ClassNotFoundException o){
o.printStackTrace();
}
}
}
}
Instead of using an Array for storing data use a List (ArrayList, Vector, or similar). And whenever you alter the data collection you need to inform the ArrayAdapter that the data has changed - to notify the array adapter that the list has changed you call the method
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Settings.this, android.R.layout.simple_list_item_1, listItems);
setListAdapter(adapter);
listItems.add("new string");
adapter.notifyDataSetChanged();
http://developer.android.com/reference/android/widget/ArrayAdapter.html#notifyDataSetChanged%28%29
Related
I've looked up similar post regarding this question but they didn't solve my issue, so here it is.
I'm trying to set a setOnItemClickListener, for when I click on any item of my list I will open a dialog with the info (retrieve from the list) on the clicked list and more info. But i'm struggling to implement the setOnItemClickListener part.
I'm getting and error in line: myList.setOnItemClickListener(new OnItemClickListener()){
package com.example.proyectoprueba;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;;
public class PlantillaChina extends ActionBarActivity{
// DB Class to perform DB related operations
DBController controller = new DBController(this);
// Progress Dialog Object
ProgressDialog prgDialog;
HashMap<String, String> queryValues;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.lista);
Intent myIntent = getIntent();
String value = myIntent.getStringExtra("key");
TextView titulo=(TextView)findViewById(R.id.titulo);
// Get Platos records from SQLite DB
ArrayList<HashMap<String, String>> platoList = controller.getAllEntremeses();
if (value.equals("entremeses")){
platoList = controller.getAllEntremeses();
titulo.setText(value);
}else if(value.equals("arroces y pasta")){
platoList = controller.getAllArrocesyPasta();
titulo.setText(value);
}else if(value.equals("mar")){
platoList = controller.getAllMar();
titulo.setText(value);
}else if(value.equals("carnes")){
platoList = controller.getAllCarnes();
titulo.setText(value);
}
// If Platos exists in SQLite DB
if (platoList.size() != 0) {
// Set the Plato Array list in ListView
ListAdapter adapter = new SimpleAdapter(PlantillaChina.this, platoList, R.layout.itemlista, new String[] {
"platoId", "platoNombre", "platoDescripcion", "platoPrecio" }, new int[] {R.id.codigo, R.id.nombre, R.id.descripcion, R.id.precio });
ListView myList = (ListView) findViewById(R.id.listaplatos);
myList.setAdapter(adapter);
myList.setOnItemClickListener(new OnItemClickListener()){
}
}
Thank you for your time
It think you want something like this.
myList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id)
{
// You have the position available here as well as the clicked view.
}
});
You need to actual define the OntItemClickListener to do something.
First, the code you have doesn't make much sense. You want something like this:
myList.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
// Your code here
}
});
Basically you are creating your own OnItemClickListener class, and overriding the OnItemClick method. This callback will get called whenever an item in your list is clicked. You can do whatever processing you would like inside that function.
I got an activity that is called from main activity. In the activity, i got database connections established and i fill a spinner according to db data. When a user selects one of the spinner items and press the button, the activity finishes and returns a value to the main activity (activity on result). But the button in the activity doesnt work, so the activity never returns a value to main activity. Here is the code:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class mySpinnerClass extends Activity implements
OnItemSelectedListener {
private VeriTabani veritabani;
private SQLiteDatabase db;
Spinner spinner;
Button btnAdd;
String dataBaseName;
int selectedValue;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner);
dataBaseName = "";
selectedValue = -1;
Intent i = getIntent();
dataBaseName = i.getStringExtra("dataBaseName");
veritabani = new VeriTabani(this);
db = veritabani.getWritableDatabase();
// Spinner element
spinner = (Spinner) findViewById(R.id.mySpinner);
// add button
btnAdd = (Button) findViewById(R.id.addButton);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Loading spinner data from database
loadSpinnerData();
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
if (dataBaseName == "phoneOrientation") {
Intent intent = getIntent();
intent.putExtra("phoneOrientation", selectedValue);
setResult(RESULT_OK, intent);
finish();
}
else if(dataBaseName== "phonePosition") {
Intent intent = getIntent();
intent.putExtra("phonePosition", selectedValue);
setResult(RESULT_OK, intent);
finish();
}
else if(dataBaseName =="Label"){
Intent intent=getIntent();
intent.putExtra("label",selectedValue);
setResult(RESULT_OK, intent);
finish();
}
}
});
}
private void loadSpinnerData() {
// Spinner Drop down elements
List<String> lables = getAllLabels();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
public List<String> getAllLabels() {
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + dataBaseName;
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(cursor.getColumnIndex("isim")));
} while (cursor.moveToNext());
}
// closing connection
// returning lables
return labels;
}
public int returnID(String item) {
int toBereturnedID;
Cursor myCursor = db.rawQuery("SELECT _id from " +dataBaseName+ " WHERE isim="+"'"+item+"'", null);
myCursor.moveToFirst();
toBereturnedID = myCursor.getInt(0);
return toBereturnedID;
}
public void onItemSelected(AdapterView<?> parent, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
String label = parent.getItemAtPosition(position).toString();
selectedValue = returnID(label);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
You are calling loadSpinnerData(); method in onCreate() of activity so dataBaseName is always going to be empty, so you want to have value of spinner at time click you need to call that with on onClick() method of button, which will give you correct dataBaseName and use dataBaseName.equals("phoneOrientation") instead of dataBaseName == "phoneOrientation"
Try creating a new Intent instead of getIntent().
Intent intent=new Intent();
intent.putExtra("label",selectedValue);
setResult(RESULT_OK, intent);
finish();
Hope it helps.
I have an activity that displays a list of "main menu" items. Each list item should start a new activity when clicked. I do this by loading the appropriate activity using it's class name.
Code:
public class MenuActivity extends ListActivity {
String classes[] = { "AboutUsActivity", "CompanyProfileActivity", "ProductsActivity", "ContactActivity" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, classes));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String cheese = classes[position];
try {
Class ourClass = Class.forName("com.example.test." + cheese);
Intent ourIntent = new Intent(this, ourClass);
startActivity(ourIntent);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Because I'm storing class names in the list, that is what is shown to the user, so it's not very user-friendly. How can I fix this?
For example, instead of showing "AboutUs", how can I make the list show something like "About Us" or "About Company's Name"?
Try this:
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MenuActivity extends ListActivity
{
private String[] menuItems = { "About Us", "Company Profile", "Products", "Contact" };
private String[] menuClassNames = { AboutUsActivity.class.getName(), CompanyProfileActivity.class.getName(), ProductsActivity.class.getName(), ContactActivity.class.getName() };
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, menuItems));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
try
{
Intent intent = new Intent(this, Class.forName(menuClassNames[position]));
startActivity(intent);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
Alternatively, you could make menuClassNames a Class[], and then you wouldn't need to go the extra step of loading the class by name.
Use 2 arrays, one for the classes and other one for the names you want to display.
I'm really frustrated because of bad programming style, and inexperience in Android. Sorry to tell you guys that.
How the app works:
This is a todo app for my job training. There are 6 columns.
3 of these contain information about the todo and the other 3 contain a view detail, edit, and remove screen.
When the user clicks remove for some reason even after setting a notifyDataChange, my screen is not updated and the deleted row it's still displayed.
Any ideas of what is going on here? I've tried many solutions for about 3 hours now
The code is posted here sorry if its a bit tedious.
The whole class with the ListViews:
package com.DCWebMakers.Vairon;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class ManageAppointment extends Activity {
ListView rowLi, whenLi, postedLi, detailsLi, editLi, removeLi;
ArrayAdapter<String> whenAdapter, postedAdapter, detailsAdapter,
editAdapter, removeAdapter;
ArrayAdapter<Integer> rowAdapter;
final AppointmentInfo information = new AppointmentInfo(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
/*
* The ListViews created here are not the proper way to make ListViews.
* This is for testing purposes and will be updated for efficiency. The
* remove also doesn't work properly
*/
super.onCreate(savedInstanceState);
setContentView(R.layout.manage_appointment);
initVariables();
try {
databaseManagement();
detailsLi.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> aV, View v, int pos,
long arg3) {
// TODO Auto-generated method stub
Intent openDetails = new Intent(
"com.DCWebMakers.Vairon.APPOINTMENTDETAILS");
openDetails.putExtra("position", pos);
startActivity(openDetails);
}
});
editLi.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> aV, View v, int pos,
long arg3) {
// TODO Auto-generated method stub
Intent openEdit = new Intent(
"com.DCWebMakers.Vairon.EDITAPPOINTMENT");
openEdit.putExtra("position", pos);
startActivity(openEdit);
notifyChangesToAdapters();
}
});
removeLi.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> aV, View v, int pos,
long arg3) {
// TODO Auto-generated method stub
databaseManagement();
information.open();
information.delete(pos);
information.close();
Dialog sucDeleted = new Dialog(ManageAppointment.this);
sucDeleted.setTitle("Sucesfully deleted");
TextView tvDintWorked = new TextView(ManageAppointment.this);
tvDintWorked.setText("The appointment at position:" + pos
+ " was sucesfully deleted");
sucDeleted.setContentView(tvDintWorked);
sucDeleted.show();
notifyChangesToAdapters();
}
});
} catch (Exception e) {
Dialog showError = new Dialog(this);
showError.setTitle("Error");
TextView tvDintWorked = new TextView(this);
String error = e.toString();
tvDintWorked.setText(error);
showError.setContentView(tvDintWorked);
showError.show();
}
}
public void initVariables() {
rowLi = (ListView) findViewById(R.id.rowList);
whenLi = (ListView) findViewById(R.id.whenList);
postedLi = (ListView) findViewById(R.id.postedList);
detailsLi = (ListView) findViewById(R.id.detailsList);
editLi = (ListView) findViewById(R.id.editList);
removeLi = (ListView) findViewById(R.id.removeList);
}
#Override
protected void onPause() { // TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
notifyChangesToAdapters();
}
private void notifyChangesToAdapters() {
// TODO Auto-generated method stub
rowAdapter.notifyDataSetChanged();
whenAdapter.notifyDataSetChanged();
postedAdapter.notifyDataSetChanged();
detailsAdapter.notifyDataSetChanged();
editAdapter.notifyDataSetChanged();
removeAdapter.notifyDataSetChanged();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent mainIntent = new Intent("com.DCWebMakers.Vairon.MAINMENU");
startActivity(mainIntent);
}
public void databaseManagement() {
information.open();
int primaryKey = information.getKeys();
String when[] = information.getWhen();
String posted[] = information.getPosted();
String details[] = new String[primaryKey];
Integer rowNumber[] = new Integer[primaryKey];
String edit[] = new String[primaryKey];
String delete[] = new String[primaryKey];
for (int set = 0; set < rowNumber.length; set++) {
rowNumber[set] = (set);
}
for (int set = 0; set < details.length; set++) {
details[set] = ("Details");
}
for (int set = 0; set < edit.length; set++) {
edit[set] = ("Edit");
}
for (int set = 0; set < delete.length; set++) {
delete[set] = ("Delete");
}
information.close();
rowAdapter = new ArrayAdapter<Integer>(ManageAppointment.this,
android.R.layout.simple_list_item_1, rowNumber);
whenAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, when);
postedAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, posted);
detailsAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, details);
editAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, edit);
removeAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, delete);
rowLi.setAdapter(rowAdapter);
whenLi.setAdapter(whenAdapter);
postedLi.setAdapter(postedAdapter);
detailsLi.setAdapter(detailsAdapter);
editLi.setAdapter(editAdapter);
removeLi.setAdapter(removeAdapter);
}
}
The delete method:
public void delete(int position) {
theDatabase.beginTransaction();
try {
theDatabase
.delete(DATABASE_TABLE, KEY_ROWID + "=" + position, null);
theDatabase.setTransactionSuccessful();
} catch (SQLiteException e) {
// TODO: handle exception
e.printStackTrace();
} finally {
theDatabase.endTransaction();
theDatabase.close();
}
}
before notifyDataSetChanged you need to remove the entry from the List
Did you see any exception when deleting from database. and you also need to delete pos entry from global list before notifying.
After following code and showing no errors when I use my button to access my list view it forces close my code is as follows
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Listview extends ListActivity {
String classNames[] = {"home1", "Sweet", "tutorial2"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, classNames));
}#Override
protected void onListItemClick (ListView lv, View v, int position, long id){
super.onListItemClick(lv, v, position, id);
String openClass = classNames[position];
try{
Class selected = Class.forName("us.beats.with." + openClass);
Intent selectedIntent = new Intent(this, selected);
startActivity(selectedIntent);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
where the button was set up I had Button Listview = (Button) findViewById(R.id.Listview);
Listview.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("us.beats.with.Mylist"));
mpButtonClick.start();
but start activity was us.beats.with.Listview should have been the above
Change your classname and run it will work fine
public class MyList extends ListActivity {
String classNames[] = {"home1", "Sweet", "tutorial2"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, classNames));
}#Override
protected void onListItemClick (ListView lv, View v, int position, long id){
super.onListItemClick(lv, v, position, id);
String openClass = classNames[position];
try{
Class selected = Class.forName("us.beats.with." + openClass);
Intent selectedIntent = new Intent(this, selected);
startActivity(selectedIntent);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
Now run the above code