Been trying to get an answer on what I am doing wrong all over the place. I would like the user to select a button in the calling class, open a called listactivity which displays the contents of a database, let the user click an entry, copy that entry into a new database, send back the rowid from the new database to the calling class and have the calling class assign the title from the new database entry to the original button that was pushed.
Here is the calling class
static final private int CHOOSE_MONDAY = 0;
static final private int CHOOSE_TUESDAY = 0;
private int ButtonPushed = 0;
private NotesDbAdapter mDbHelper;
private MenuDbAdapter menuDbHelper;
private Long mRowId;
String menuTitle;
String menuProtein;
String menuBody;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.plan_menu);
Toast.makeText(this, "Choose a day to pick a meal for!", Toast.LENGTH_LONG).show();
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
menuDbHelper = new MenuDbAdapter(this);
menuDbHelper.open();
}
public void mButtonHandler(View target)
{
switch(target.getId())
{
case R.id.monday:
// Create new intent object and tell it to call the ColorPicker class
Intent question = new Intent(this, PlanMenuList.class);
// Start ColorPicker as a new activity and wait for the result
startActivityForResult(question, CHOOSE_MONDAY);
break;
case R.id.tuesday:
// Create new intent object and tell it to call the ColorPicker class
Intent question1 = new Intent(this, PlanMenuList.class);
// Start ColorPicker as a new activity and wait for the result
startActivityForResult(question1, CHOOSE_TUESDAY);
break;
}
And then this is the called class where I am trying to copy in the user's selection to the new database and then send back the id to the calling class.
public class PlanMenuList extends ListActivity {
private NotesDbAdapter mDbHelper;
private MenuDbAdapter menuDbHelper;
private List<Data>data;
String menuTitle;
String menuProtein;
String menuBody;
private Long mRowId;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notes_list);
mDbHelper = new NotesDbAdapter(this);
menuDbHelper = new MenuDbAdapter(this);
mDbHelper.open();
menuDbHelper.open();
fillData();
}
private void fillData() {
Cursor notesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(notesCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{NotesDbAdapter.KEY_TITLE};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.notes_row, notesCursor, from, to);
setListAdapter(notes);
}
private void populateFields() {
if (mRowId != null) {
Cursor note = mDbHelper.fetchNote(mRowId);
startManagingCursor(note);
menuTitle=(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
menuProtein=(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_PROTEIN)));
menuBody=(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
}
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
mDbHelper.fetchNote(id);
mRowId = id;
//populateFields();
menuDbHelper.createMenu("Monday", menuTitle, menuProtein, menuBody);
Intent answer = new Intent();
answer.putExtra("MenuDbAdapter.KEY_ROWID", mRowId);
setResult(RESULT_OK, answer);
finish();
}
}
I have been messing around with this thing for days and can't seem to get it to do what I want - any help would be appreciated.
Can you post your onActivityResult implementation?
When I've passed data back to an activity as a result, I've used Bundles. For example:
Intent answer = new Intent();
Bundle extras = new Bundle();
extras.putLong("MenuDbAdapter.KEY_ROWID", mRowId);
answer.putExtras(extras);
Then, in the activity result handler, you'd call Intent.getExtras and pull your value from there.
Edit: here are some examples from the android dev guide:
http://developer.android.com/guide/appendix/faq/commontasks.html (search for onActivityResult)
http://developer.android.com/resources/tutorials/notepad/notepad-ex3.html
protected void onListItemClick(ListView l, View v, int position, long id) {
the variable id is not the same as the database row number and thats where the issue is. I'd create a custom adapter and store the _id (row number) as a tag in the view. Retrieve the tag in the OnItemClickListener and do the db queries.
Custom Adapter code:
private class Cursy extends CursorAdapter {
public Cursy(Context context, Cursor c) {
super(context, c);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
viewHolder holder = (viewHolder) view.getTag();
holder.tv.setText(cursor.getString(cursor
.getColumnIndex(NotesDbAdapter.KEY_TITLE)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
viewHolder holder = new viewHolder();
holder._id = ursor.getString(cursor.getColumnIndex(NotesDbAdapter._ID));
View v = getLayoutInflater().inflate(
R.layout.list_layout, null);
holder.tv = (TextView) v
.findViewById(R.id.tv);
v.setTag(holder);
return v;
}
}
OnItemClickListener:
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
viewHolder holder = (viewHolder) view.getTag();
// use holder._id and do the db queries
}
});
Firstly, I think you want to make sure your CHOOSE_MONDAY and CHOOSE_TUESDAY constants are different values, so that you can differentiate between them later.
Secondly, you are sending back the wrong row ID to your original activity. Assuming your createMenu() method is based on SQLiteDatabase.insert(), it should return the row ID after insertion (or -1 if there was a problem). You can use this as the row ID:
mRowId = menuDbHelper.createMenu("Monday", menuTitle, menuProtein, menuBody);
Related
I am new to Android. I am accessing an ArrayList from another class but i am getting zero size of ArrayList in accessing class. In main class, it shows a positive value of size of array list. I dont know why i am getting zero size in accessing class. Check my code for mistakes.
Tab3Tracks Class
public class Tab3Tracks extends ListFragment {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
private ArrayList<String> trackslist = new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab3tracks, container, false);
final String trackid = MediaStore.Audio.Media._ID;
final String trackno = MediaStore.Audio.Media.TRACK;
final String trackname = MediaStore.Audio.Media.TITLE;
final String path = MediaStore.Audio.Media.DATA;
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
ContentResolver cr = getContext().getContentResolver();
final String[] projection = {trackid,trackno,trackname,path
};
final Cursor cursor = cr.query(uri,projection,null,null,null);
if (cursor!=null){
if(cursor.moveToFirst()){
do{
int trackIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
trackslist.add(cursor.getString(trackIndex));
}while(cursor.moveToNext());
}System.out.println(trackslist.size());
} cursor.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getActivity(),R.layout.playlist_item,R.id.songTitle,trackslist
);
setListAdapter(adapter);
return v;
}
public ArrayList<String> getList(){
return trackslist;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
int songIndex = position;
// Starting new intent
Intent in = new Intent(getActivity(), NowPlaying.class);
// Sending songIndex to PlayerActivity
in.putExtra("songIndex", songIndex);
startActivityForResult(in, 100);
}
}
NowPlaying Class
public class NowPlaying extends AppCompatActivity {
public ArrayList<String> songsList = new ArrayList<String>();
public Tab3Tracks tab3tracks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
// Getting all songs list
tab3tracks = new Tab3Tracks();
songsList= tab3tracks.getList();
System.out.println("songsListSize"+songsList.size());
System.out.println("List" +songsList);
}
Your ArrayList is initialized, but nothing is ever added.
trackslist.add(cursor.getString(trackIndex));
That is nested inside onCreateView, causing it to only be called once. You might want to consider adding onTOuchListener to the activity and add your code there inside the listener so it updates whenever the screen is touched.
Adding inside a thread might work too, but it really depends on your code.
onCreateView of Tab3Tracks will be called by android if fragment will inflate a view, so your array is empty because this code
trackslist.add(cursor.getString(trackIndex));
doesn't call anytime
I'm trying to save text from the selected item of a ListView in OnItemClick.
I've tried so many different methods to no avail, I think I'm missing something really stupidly obvious here...
SnakesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String choice = SnakesListView.getItemAtPosition(position).toString();
Intent intent = new Intent(SnakeList.this, SnakeProfile.class);
intent.putExtra("SelectedSnakeName", choice);
startActivity(intent);
}
});
The data is being displayed fine, I just can't seem to reference it.
The line causing the exception:
String choice = SnakesListView.getItemAtPosition(position).toString();
Full code for this activity
public class SnakeList extends Activity {
ListView SnakesListView;
Cursor cursor;
Button NewSnakeBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snake_list);
SnakesListView = (ListView) findViewById(R.id.SnakesListView);
NewSnakeBtn = (Button) findViewById(R.id.NewSnake);
SQLiteDatabase db = openOrCreateDatabase("snakeDB", Context.MODE_PRIVATE, null); // ACCESSES DB
cursor = db.rawQuery("SELECT name FROM snakes", null); // SETS cursor TO RESULTS OF QUERY
List<String> SnakeNamesList = new ArrayList<String>();
ArrayAdapter SnakeNamesAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, SnakeNamesList);
SnakeNamesList.clear(); // REMOVES ANY NAMES CURRENTLY IN NAME ARRAY TO AVOID DUPLICATES
SnakesListView.setAdapter(SnakeNamesAdapter);
if (cursor.moveToFirst()) {
cursor.moveToFirst(); // MOVES CURSOR TO FIRST POSITION
do SnakeNamesList.add(cursor.getString(0)); // RETURNS STRING FROM FIRST COLUMN (NAME)
while (cursor.moveToNext());
}
NewSnakeBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(SnakeList.this, NewSnake.class));
}
});
SnakesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String choice = SnakesListView.getItemAtPosition(position).toString();
Intent intent = new Intent(SnakeList.this, SnakeProfile.class);
intent.putExtra("SelectedSnakeName", choice);
startActivity(intent);
}
});
}
No use of referencing the ListView; you can get the value from adapter itself.
Change
String choice = SnakesListView.getItemAtPosition(position).toString();
to
String choice = SnakeNamesAdapter.getItem(position).toString();
declare the string arraylist(SnakeNamesList) as global variable and
change
String choice = SnakesListView.getItemAtPosition(position).toString();
to
String choice = SnakeNamesList.get(position);
I have a listView which loads data from SQLite database and right now I would want to implement an onclicklistener to the list. When users click on the list, it should bring them to the next activity and load the corresponding data into TextView. My question is how would I pass the data of the list for example it is a list of "Topics" and user click on the topic "My Home". I want to pass the topic "My Home" to the next activity so that I know which corresponding data to be retrieved respectively.
How do I go about it? Do I "putExtras" to the new Intent? or there is another way. Below are part of my codes which display the listview:
ListView listContent = (ListView) findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToRead();
Cursor cursor = mySQLiteAdapter.queueAll();
startManagingCursor(cursor);
String[] from = new String[] { SQLiteAdapter.KEY_CONTENT };
int[] to = new int[] { R.id.text };
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.listrow, cursor, from, to);
listContent.setAdapter(cursorAdapter);
mySQLiteAdapter.close();
//Onclick ListView setlistener
listContent.setTextFilterEnabled(true);
listContent.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent summaryIntent = new Intent(DocumentListActivity.this, ViewDocumentActivity.class);
// summaryIntent.putExtra("SummTopic", value);
}
});
EDITED:
This part is on the next activity.
Intent i = getIntent();
extraTopic = i.getStringExtra("SummTopic");
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
Cursor allrows = mydb.rawQuery("SELECT * FROM "+ TABLE + " WHERE topic = \" " + extraTopic + " \" " , null);
Integer cindex = allrows.getColumnIndex("topic");
Integer cindex1 = allrows.getColumnIndex("text1");
Integer cindex2 = allrows.getColumnIndex("text2");
I got an error while retrieving from database:
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0
Please help.
Thank you.
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent summaryIntent = new Intent(DocumentListActivity.this, ViewDocumentActivity.class);
Cursor c = (Cursor)parent.getItemAtPosition(position);
summaryIntent.putExtra("SummTopic", c.getString(c.getColumnIndex(SQLiteAdapter.KEY_CONTENT)));
startActivity(summaryIntent);
}
or you can pass id (summaryIntent.putExtra("SummTopicId", id);) of this row and "ask db" in next Activity for Topic with this id
EDIT:
protected void onCreate(Bundle savedInstanceState){
Intent i = getIntent();
String extraTopic = i.getStringExtra("SummTopic");
//or long extraTopic = i.getLongExtra("SummTopic"); if you put id there (which is better)
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
String[] args = new String[] { extraTopic };
//or String[] args = new String[] { Long.toString(extraTopic) }; with id version
Cursor singleRow = mydb.rawQuery("SELECT * FROM "+ TABLE + " WHERE topic=?" , args);
//args is better then escaping special chars in query
//and it should be single row so we've changed var name :)
if(singleRow.moveToFirst()){ //we should do moveToFirst before we can use Cursor
Integer cindex = allrows.getColumnIndex("topic");
Integer cindex1 = allrows.getColumnIndex("text1");
Integer cindex2 = allrows.getColumnIndex("text2");
//setup views and stuff ....
}else{
Toast.makeText(this, "Oops we did not find topic, detail activity was closed", Toast.LENGTH_SHORT).show();
finish();
}
}
After you have used setContentView(...) you need to reference your String and get the text such as...
EditText et = (EditText) findViewById(R.id.my_edit_text);
String theText = et.getText().toString();
To pass it to another Activity you use an Intent. Example...
Intent i = new Intent(this, MyNewActivity.class);
i.putExtra("text_label", theText);
startActivity(i);
In the new Activity (in onCreate()), you get the Intent and retrieve the String...
public class MyNewActivity extends Activity {
String uriString;
#Override
protected void onCreate(...) {
...
Intent i = getIntent();
uriString = i.getStringExtra("text_label");
}
}
EDITED :
to get String From Listview you can apply below code and get ITEM String and Pass it to Next Activity:
listContent.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String ITEM=listContent.getItemAtPosition(position);
//Intent summaryIntent = new Intent(DocumentListActivity.this, // ViewDocumentActivity.class);
// summaryIntent.putExtra("SummTopic", value);
}
});
You can use Intent for this.
Intent intent= new Intent(context,classname.class);
intent.putExtra("name",string);
You can get it in the target class name using intent.getextra().
I guess you are using an adapter to fill your list with some data. So you need to override getItem(int position) method in your adapter:
#Override
public Object getItem(int position) {
//Note that return type should be the same you you use to initilise items oof the adapter. E.g. String or some custom Topic class
Object someObject = mObjects[position];
return someObject;
}
Then you need to set an item click listener to you list
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Object someObject = adapterView.getItemAtPosition(i);
Intent i = new Intent(this, MyNewActivity.class);
i.putExtra("text_label", someObject.toString());
startActivity(i);
}
});
I need some help with my project. I've created a Custom Adapter, since I want my List View to display 5 textview, instead of one that I managed to do so far. This is my CustomAdapterPn activity:
public class CustomAdapterPn extends BaseAdapter {
private static ArrayList<Poniedzialek> searchPnArrayList;
private LayoutInflater mInflater;
public CustomAdapterPn(final Context context, final ArrayList<Poniedzialek> results) {
searchPnArrayList = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return searchPnArrayList.size();
}
public Object getItem(int position) {
return searchPnArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.entry, null);
holder = new ViewHolder();
holder.txtSession = (TextView) convertView.findViewById(R.id.textSession);
holder.txtName = (TextView) convertView.findViewById(R.id.textName);
holder.txtStart = (TextView) convertView.findViewById(R.id.textStartTime);
holder.txtEnd = (TextView) convertView.findViewById(R.id.textEndTime);
holder.txtRoom = (TextView) convertView.findViewById(R.id.textRoom);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtSession.setText(searchPnArrayList.get(position).getTypeOfSession());
holder.txtName.setText(searchPnArrayList.get(position).getName());
holder.txtStart.setText(searchPnArrayList.get(position).getStartTime());
holder.txtEnd.setText(searchPnArrayList.get(position).getEndTime());
holder.txtRoom.setText(searchPnArrayList.get(position).getRoom());
return convertView;
}
static class ViewHolder {
TextView txtSession;
TextView txtName;
TextView txtStart;
TextView txtEnd;
TextView txtRoom;
}
}
And this is Activity where I wish to use this CustomAdapter. Note that I was using ArrayAdapter to display list items - I didn't modify the code yet, since I am clueless what should I do to manage this custom adapter correctly ( I was trying to, but nothing worked out well ). I am a newbie, so it's quite hard for me to get this, although I was reading tons of tutorials.
public class PoniedzialekActivity extends Activity implements OnClickListener, OnItemClickListener{ // z ListActivity na Activity
private Button butPnAdd;
private Button butPnDelete;
private ListView list_Pn;
private static final int DIALOG_ALERT = 10;
// We need some kind of Adapter to made the connection between ListView UI component and SQLite data set.
private ListAdapter pn_list_adapter;
// We need this while we read the query using Cursor and pass data
private ArrayList<Poniedzialek> pn_list;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_poniedzialek);
butPnAdd = (Button) findViewById(R.id.butPnAdd);
butPnAdd.setOnClickListener(this);
butPnDelete = (Button) findViewById(R.id.butPnDel);
butPnDelete.setOnClickListener(this);
// Initialize UI components
list_Pn = (ListView) findViewById(R.id.listPn);
list_Pn.setOnItemClickListener(this);
pn_list = new ArrayList<Poniedzialek>();
// For the third argument, we need a List that contains Strings.
//We decided to display undergraduates names on the ListView.
//Therefore we need to create List that contains undergraduates names
pn_list_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());
list_Pn.setAdapter(pn_list_adapter);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.butPnAdd){
Intent i = new Intent(PoniedzialekActivity.this,dodawaniePoniedzialek.class);
startActivity(i);
}
if(v.getId()==R.id.butPnDel){
showDialog(DIALOG_ALERT);
}
}
/**
* DIALOG
*/
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ALERT:
// Create out AlterDialog
Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Czy na pewno chcesz usunac wszystkie wpisy ?");
builder.setCancelable(true);
builder.setPositiveButton("Tak", new OkOnClickListener());
builder.setNegativeButton("Nie", new CancelOnClickListener());
AlertDialog dialog = builder.create();
dialog.show();
}
return super.onCreateDialog(id);
}
private final class CancelOnClickListener implements
DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
// Nic nie robi
}
}
private final class OkOnClickListener implements
DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
DeletePn();
onResume();
}
}
public void DeletePn(){
DatabaseHelper openHelperClass = new DatabaseHelper(this);
SQLiteDatabase sqliteDatabase = openHelperClass.getWritableDatabase();
sqliteDatabase.delete(DatabaseHelper.PN_TABLE, null, null);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
// To create a List that contains undergraduate names, we have to read the SQLite database
//We are going to do it in the separate method
public List<String> populateList(){
// We have to return a List which contains only String values. Lets create a List first
List<String> pn_string_list = new ArrayList<String>();
// First we need to make contact with the database we have created using the DbHelper class
DatabaseHelper openHelperClass = new DatabaseHelper(this);
// Then we need to get a readable database
SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();
// We need a a guy to read the database query. Cursor interface will do it for us
//(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
Cursor cursor = sqliteDatabase.query(DatabaseHelper.PN_TABLE, null, null, null, null, null, null);
// Above given query, read all the columns and fields of the table
startManagingCursor(cursor);
// Cursor object read all the fields. So we make sure to check it will not miss any by looping through a while loop
while (cursor.moveToNext()) {
// In one loop, cursor read one undergraduate all details
// Assume, we also need to see all the details of each and every undergraduate
// What we have to do is in each loop, read all the values, pass them to the POJO class
//and create a ArrayList of undergraduates
String session = cursor.getString(cursor.getColumnIndex(DatabaseHelper.PN_KEY_TYPE_OF_SESSION));
String start = cursor.getString(cursor.getColumnIndex(DatabaseHelper.PN_KEY_START_TIME));
String end = cursor.getString(cursor.getColumnIndex(DatabaseHelper.PN_KEY_END_TIME));
String name = cursor.getString(cursor.getColumnIndex(DatabaseHelper.PN_KEY_NAME));
String room = cursor.getString(cursor.getColumnIndex(DatabaseHelper.PN_KEY_ROOM));
// Finish reading one raw, now we have to pass them to the POJO
Poniedzialek pn = new Poniedzialek();
pn.setTypeOfSession(session);
pn.setName(name);
pn.setStartTime(start);
pn.setEndTime(end);
pn.setRoom(room);
// Przekazujemy pn do arraylist
pn_list.add(pn);
// But we need a List of String to display in the ListView also.
// That is why we create "pn_string_list"
pn_string_list.add(name);
}
// Jezeli Baza Danych nie zostanie zamknieta dostaniemy error
sqliteDatabase.close();
return pn_string_list;
}
// If you don't write the following code, you wont be able to see what you have just insert to the database
#SuppressWarnings("unchecked")
#Override
protected void onResume() {
super.onResume();
pn_list_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());
list_Pn.setAdapter(pn_list_adapter);
((ArrayAdapter<String>) pn_list_adapter).notifyDataSetChanged(); // dodano
list_Pn.refreshDrawableState(); // dodanoe
list_Pn.invalidate(); // dodanoe
}
} // end PoniedzialekActivity
Create an object for your custom adapter class CustomAdapterPn and set this custom adapter object to list view . Not the array adapter .
Look at this lines and make changes according to it,
CustomAdapterPn pn_list_adapter; //change 1
pn_list = new ArrayList<Poniedzialek>();
populateList() // Change 2
pn_list_adapter = new CustomAdapterPn(this,pn_list); // Change 3
list_Pn.setAdapter(pn_list_adapter);
Try this and let me know what happen..
I've been searching on this for a while now, but I can't find anything that could help me solve my problem.
I have a list of categories in a listview. I fetch these from a SQLiteDatabase and use a SimpleCursorAdapter to put them in the list.
This works fine...
Now, if I click a category, I want to launch a new activity displaying all items with that specific category. Passing parameters to the new activity isn't a problem - found a nice tutorial on how to do this here: Passing data or parameter to another activity
My problem is that I can't get the id out of the selected view... I want the id from the selected category so I can get the items with that categoryId.
This is where I try and get the id out of the view - I've used a lot of different methods (including some fiddling with listview, item and position, ... this is my most recent attempt) and don't know what to try next...
#Override
public void onItemClick(AdapterView<?> listview, View item, int position,
long itemId) {
Intent intent = new Intent();
Bundle bun = new Bundle();
bun.putInt("categoryId", (int) itemId);
intent.setClass(MainActivity.this, ItemsPerCategoryActivity.class);
intent.putExtras(bun);
startActivity(intent);
}
Has anybody encountered the same problem and if you have, do you have some advice for me on how to do this?
This is how the problem got solved:
Cursor c = (Cursor)listview.getAdapter().getItem(position);
int id = c.getInt(c.getColumnIndex(_ID)); //0 = index id
//Log.d("Category id", id + "");
Intent intent = new Intent();
Bundle bun = new Bundle();
bun.putInt("categoryId", id);
intent.setClass(MainActivity.this, ItemsPerCategoryActivity.class);
intent.putExtras(bun);
startActivity(intent);
Try following
#Override
public void onItemClick(AdapterView<?> listview, View item, int position,
long itemId) {
Cursor c = (Cursor)adatper.getItem(position); //adapter = cursor adapter object
int id = c.getInt(0)// 0 is index of id.
Intent intent = new Intent();
Bundle bun = new Bundle();
bun.putInt("categoryId", id);
intent.setClass(MainActivity.this, ItemsPerCategoryActivity.class);
intent.putExtras(bun);
startActivity(intent);
}
For this,you have can use custom adapter and there,you can set ids in a HashMap.Here is an example:
public class DemoAdapter extends SimpleCursorAdapter
{
Cursor dataCursor;
LayoutInflater mInflater;
Context context;
public static HashMap<Integer,String> myList=new HashMap<Integer,String>();
public DemoAdapter(Context context, int layout, Cursor dataCursor, String[] from,int[] to)
{
super(context, layout, dataCursor, from, to);
this.context=context;
this.dataCursor = dataCursor;
mInflater = LayoutInflater.from(context);
this.fromWhere=fromWhere;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
if(convertView==null)
{
convertView = mInflater.inflate(R.layout.my_list_item, null);
holder = new ViewHolder();
holder.cName=(TextView)convertView.findViewById(R.id.contactName);
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
dataCursor.moveToPosition(position);
String id=Integer.toString(dataCursor.getInt(dataCursor.getColumnIndexOrThrow("_id")));
myList.put(position, id);
holder.cName.setText(dataCursor.getString("contact_name"));
return convertView;
}
static class ViewHolder
{
TextView cName;
}
}
Now,use it like-
listView.setOnItemClickListener(new OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,long id) {
int id=Integer.parseInteger(DemoAdapter.myList.get(position));
}
});