Getting GetId() to work on a LinkedList() - android

Further to my question "Extracting multiple data items from LinkedList() element" which now works fine on the demo "Book" app thanks to quocnhat7, now I'm stuck on the onItemClick where the method getId() method causes "error: cannot find symbol method getId()" on building the app.
public class MainActivity extends ListActivity implements OnItemClickListener {
JCGSQLiteHelper db = new JCGSQLiteHelper(this);
List list;
ArrayAdapter myAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db.createBook(new Book("The waves", "Virginia Woolf"));
db.createBook(new Book("Mrs Dalloway", "Virginia Woolf"));
db.createBook(new Book("War and Peace", "Leo Tolstoy"));
// get all books
List<Book> list = db.getAllBooks();
List<String> listTitle = new ArrayList<String>();
for (int i = 0; i < list.size(); i++) {
listTitle.add(i, list.get(i).getTitle());
}
myAdapter = new ArrayAdapter(this, R.layout.row_layout, R.id.listText, listTitle);
getListView().setOnItemClickListener(this);
setListAdapter(myAdapter);
}
#Override
public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
// start BookActivity with extras the book id
Intent intent = new Intent(this, BookActivity.class);
intent.putExtra("book", list.get(arg2).getId());
startActivityForResult(intent, 1);
}
}

You have 2 problems:
list is defined as non-generic List, thus it's get method returns an Object, and not Book, and Object doesn't have a method getId.
List<Book> list = db.getAllBooks(); hides the member List list, and so there is no assignment to the member list.
To fix it, you should do 2 things:
Change list definition:
public class MainActivity extends ListActivity implements OnItemClickListener {
JCGSQLiteHelper db = new JCGSQLiteHelper(this);
List<Book> list;
// ^^^^^^
Assign to the member, not to a local variable:
// get all Books
list = db.getAllBooks();

Related

ListView Generated from SQLite onClickListener() to take me to another activity based on where i clicked

I'm creating an android app. In this app, I have a ListView populated with data from SQLite. I am trying to add an onClickEventListener to each row of the ListView so that when a menu item is clicked it opens up another Activity with more information from the Database about the item clicked. I have succeeded in adding an event listener to the ListView, but I am not sure how to pass on database information depending on the list item clicked.
Here is my code:
public class MainActivity extends AppCompatActivity {
private DatabaseHelper dbh;
private ArrayList listItems = new ArrayList();
ArrayList<String[]> noteList;
private ArrayAdapter adapter;
private ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbh = new DatabaseHelper(this);
dbh.open();
lv = (ListView) findViewById(R.id.noteListView);
noteList = dbh.selectAll();
String id = "";
String content = "";
for(int i = 0; i < noteList.size(); i++){
content = noteList.get(i)[1];
id = noteList.get(i)[0];
listItems.add(id + ", " + content);
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(arrayAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Intent i = new Intent(MainActivity.this, EditNote.class);
//i.putExtra();
startActivity(i);
}
});
}
}
In your case list has strings, so here is what you need to do:
String yourString = listItem.get(position);
i.putExtra("KEY", yourString);
startActivity(i);
And at the receiving activity you can retrieve as
intent intent = getIntent();
String yourString = intent.getExtras().getString("KEY");
EDIT: If your list is having some POJO class or simple class objects
You can pass to second activity like this
intent.putExtra("Your class", obj);
To retrieve object in second Activity
getIntent().getSerializableExtra("Your class");
EDIT: One important thing to remember.
If you passing a class object it must implement Serializable or Parcelable interface.
For eg
class Student implements Serializable{
}
You should make a custom adapter that extends the arrayadapter. Load everything from your database into an arraylist and use something like this:
// CODE DOES NOT WORK WITH YOUR CODE, IT'S JUST AN EXAMPLE
public class MyClassAdapter extends ArrayAdapter<MyClass> {
private static class ViewHolder {
private TextView itemView;
}
public MyClassAdapter(Context context, int textViewResourceId, ArrayList<MyClass> items) {
super(context, textViewResourceId, items);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(this.getContext())
.inflate(R.layout.listview_association, parent, false);
viewHolder = new ViewHolder();
viewHolder.itemView = (TextView) convertView.findViewById(R.id.ItemView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
MyClass item = getItem(position);
if (item!= null) {
// My layout has only one TextView
// do whatever you want with your string and long
viewHolder.itemView.setText(String.format("%s %d", item.reason, item.long_val));
}
return convertView;
}
}
...
lv.setAdapter(new MyClassAdapter(....));
In your OnItemClickListener you have the position of the clicked item so to get the object use MyClass object = lv.getItemAtPosition(position); and use that object to pass data to the new activity.
Intent intent = new Intent(getBaseContext(), my.class);
intent.putExtra("key", "value");
startActivity(intent);
To access
String s = getIntent().getStringExtra("key");
More: https://stackoverflow.com/a/2265712/2890156

Android sort arrays

I'm trying to sort an array in alphabetical order (by word string). After I put this line Arrays.sort(word, String.CASE_INSENSITIVE_ORDER);, the other parallel string arrays such as example and flag don't match with word position anymore.
If word string changes its position after it is sorted, the others strings should be linked to it and change their position.
public class MainActivity extends Activity implements
SearchView.OnQueryTextListener {
ListView list;
SearchView mSearchView;
ArrayList<Vocabulary> vocabularylist;
ListViewAdapter adapter;
String[] definition;
String[] word;
String[] example;
int[] flag;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Generate sample data into string arrays
word = new String[] { "bimbo",
"heartthrob",
"good-for-nothing"};
definition = new String[] { "loira burra",
"arrasa-corações",
"vagabundo"};
example = new String[] { "She's a real bimbo.",
"He's a real heartthrob.",
"What are you doing wasting time here? Get a job, you good-for-nothing!"};
flag = new int[] { R.drawable.bimbo,
R.drawable.heartthrob,
R.drawable.vagabundo};
**// THE PROBLEM IS HERE**
**Arrays.sort(word, String.CASE_INSENSITIVE_ORDER);**
list = (ListView) findViewById(R.id.listview);
mSearchView = (SearchView) findViewById(R.id.search_view);
vocabularylist = new ArrayList<Vocabulary>();
for (int i = 0; i < word.length; i++) {
Vocabulary vocabulary = new Vocabulary(word[i], definition[i], example[i],
flag[i]);
vocabularylist.add(vocabulary);
}
// Pass results to ListViewAdapter Class
adapter = new ListViewAdapter(getApplicationContext(), vocabularylist, word, definition, example, flag);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
setupSearchView();
// Capture ListView item click
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(MainActivity.this, SingleItemView.class);
// Pass all data definition
Vocabulary voc = (Vocabulary) adapter.getItem(position);
i.putExtra("definition", voc.getDefinition());
// Pass word
i.putExtra("word", voc.getWord());
// Pass example
i.putExtra("example", voc.getExample());
// Pass flag
i.putExtra("flag", voc.getFlag());
// Pass position
i.putExtra("position", position);
// Open SingleItemView.java Activity
startActivity(i);
}
});
}
private void setupSearchView() {
mSearchView.setIconifiedByDefault(false);
mSearchView.setOnQueryTextListener(this);
mSearchView.setSubmitButtonEnabled(false);
mSearchView.setQueryHint("Pesquise aqui...");
}
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
public boolean onQueryTextSubmit(String query) {
return false;
}
}
You already have an object that stores all the data collectively from the arrays called Vocabulary and your adapter is using a list of those objects that you have already created.
All you need to do is sort the vocabularyList as follows:
Collections.sort(vocabularyList, new Comparator<Vocabulary>() {
#Override
public int compare(Vocabulary lhs, Vocabulary rhs) {
return lhs.getWord().compareToIgnoreCase(rhs.getWord());
}
});
You can add this just before assigning the adapter its value.
adapter = new ListViewAdapter(getApplicationContext(), vocabularylist,
word, definition, example, flag);
Also, the adapter should only need the vocabularyList since that list contains the information from the arrays word, definition, example, and flag. You should remove those from the ListViewAdapter if they are not used in it.
Instead of defining multiple arrays that must be associated in a order after sorting, create a class with all the attributes you need (definition, words ans example ), define ONE list with that object type and sort it by the desired criteria
At the end of the sortime you will get concordance with all the membersame in the list
You need to define a class and implement comparable interface:
public class Data implements Comparable<Data> {
String definition;
String word;
String example;
int flag;
public int compareTo(Data data)
{
return this.word.compareTo(data.word);
}
}
and instead of defining word, example,... define an array of Data:
Data[] dataArray;
and use:
Arrays.sort(dataArray);
now all of the indexes are linked together

Listview not loading properly

I am trying to save a link from webview. From my webview class, I am saving the page url as below.
public void AddUrl(String page_url){
SaveUrlActivity urlactivity = new SaveUrlActivity();
urlactivity.saveurl(page_url);
}
My SaveUrlActivity class is as below:
public class SaveUrlActivity extends Activity {
public String url;
public ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_savedurl);
lv = (ListView) findViewById(R.id.list);
saveurl(url);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent in = new Intent(SaveUrlActivity.this, DisPlayWebPageActivity.class);
in.putExtra("page_url", url);
startActivity(in);
}
});
}
public void saveurl(String url1){
url = url1;
final List<RowItem> ri = new ArrayList<RowItem>();
RowItem item = new RowItem(url);
ri.add(item);
SavedUrlAdapter adapter = new SavedUrlAdapter(SaveUrlActivity.this, ri);
lv.setAdapter(adapter);
}
}
Whenever I run my program, I am getting the following error.
FATAL EXCEPTION: main
Process: com.example.smarthelp, PID: 16284
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.example.smarthelp.SaveUrlActivity.saveurl(SaveUrlActivity.java:46)
at com.example.smarthelp.DisPlayWebPageActivity.AddUrl(DisPlayWebPageActivity.java:76)
at com.example.smarthelp.DisPlayWebPageActivity.onOptionsItemSelected(DisPlayWebPageActivity.java:66)
Can anyone help me figure out where I am making the mistake?
You're using reference to ListView lv before it has been initialized, and you can't do that without first starting the SaveUrlActivity, only after it's setContentView(R.layout.activity_savedurl); you can initialize the lv.
public void saveurl(String url1){
url = url1;
final List<RowItem> ri = new ArrayList<RowItem>();
RowItem item = new RowItem(url);
ri.add(item);
SavedUrlAdapter adapter = new SavedUrlAdapter(SaveUrlActivity.this, ri);
lv.setAdapter(adapter);
}
It would be easier if you make a static var in your SaveUrlActivity class and assign a value to it before you start the Activity, and the make call to the saveurl() from inside of that class when you have all your views initialized.
Something like:
public void AddUrl(String page_url){
SaveUrlActivity.page_url = page_url;
Intent i = new Intent(this, SaveUrlActivity.class);
startActivity(i);
}
And in your SaveUrlActivity.java:
public class SaveUrlActivity extends Activity {
public String url;
public ListView lv;
static page_url;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_savedurl);
lv = (ListView) findViewById(R.id.list);
saveurl();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent in = new Intent(SaveUrlActivity.this, DisPlayWebPageActivity.class);
in.putExtra("page_url", url);
startActivity(in);
}
});
}
public void saveurl(){
url = page_url;
final List<RowItem> ri = new ArrayList<RowItem>();
RowItem item = new RowItem(url);
ri.add(item);
SavedUrlAdapter adapter = new SavedUrlAdapter(SaveUrlActivity.this, ri);
lv.setAdapter(adapter);
}
}
It's accurate if you're planning to start this activity, if you need to update data in already started one, you better use the Handler
A couple of things to look at:
Make sure that the activity_savedurl layout file actually contains a view with the list ID. If it does not, then lv will be null.
You pass url to saveurl(), but you never assigned it a value.

Getting SQLite row id from ListView with OnLongClickListener not working

Well, this is the setting:
Code for the activity
public class Users_List extends Activity {
private ArrayList<Users> users;
private ListView lvusers;
private int user_selected;
private DB db;
private ListAdapter adaptador;
private static final int NEW_USER = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.users_list);
DB db = new DB(this);
users = db.getAllUsers();
lvusers = (ListView) findViewById(R.id.listview);
adaptador = new AdaptadorUsersList(this, users);
lvusers.setAdapter(adaptador);
lvusers.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
registerForContextMenu(lvusers);
final Button new_user = (Button) findViewById(R.id.btn_new_user);
nuevo_socio.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Users_List.this,
User_Form.class);
startActivityForResult(intent, NEW_USER);
}
});
lvusers.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> a, View view, int position, long id) {
//HERE...LONG ID IS ALWAYS ZERO, WHY???
Log.d("Selected User--------", "---------------------"+id+"--------");
openContextMenu(lvusers);
return true;
}
});
}
//Here the codes continues....
}
I readed that the long id param. on onItemLongClick is actually the id of the row that was clicked right? so, what's wrong here that the id is returning always "0" as value on logcat?
Thank you!
the ID of the onItemClickListener or onItemLongClickListner is the same as the ID of the row if the adapter extends CursorAdapter or simpleCursorAdapter because the Cursor will take care of putting the Item's ID to the Long ID.
Bare in mind that your ID column or the primary key field should have the name of "_id". here is an example of how to implement Custom CursorAdapter.
Edit
You can use BaseAdapter as CursorAdapter since from the source code of CursorAdapter it extends the BaseAdapter however you will use getView() to call the bindView() and newView() where these two functions are the main functions of the CursorAdapter
so basically you are doing the CursorAdapter from the scratch refer to this question where they explain it more in details.
hope this answer your question.

onItemClickListener(), how to pass clicked item's data?

I am using onItemClickListener() with a List. I want to pass name of the item clicked on, and an arbitrary number to next instance of the list. How can this be done?
Edit: here is the class:
public class ListViewA extends Activity{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView lv= (ListView)findViewById(R.id.listview);
// create the grid item mapping
String[] from = new String[] {"col_1"};
int[] to = new int[] {R.id.item2};
// prepare the list of all records
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
for(int i = 0; i < 10; i++){
HashMap<String, String> map = new HashMap<String, String>();
map.put("col_1", "col_1_item_" + i);
fillMaps.add(map);
lv.setOnItemClickListener(onListClick);
}
// fill in the grid_item layout
SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.grid_item, from, to);
lv.setAdapter(adapter);
}
private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent,View view, int position, long id)
{
Intent i=new Intent(ListViewA.this,ListViewA.class);
startActivity(i);
}
};
}
Following example shows you how to pass data onItemClick for particular position.
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
HERE YOU GOT POSITION FOR PERTICULAR ITEM
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
i.putExtra("position", fillMaps.get(position));
startActivity(i);
}
});
And yes you need to declare fillMaps as globally.
public class ListViewA extends Activity{
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);......
Intent i=new Intent(ListViewA.this,ListViewA.class);
i.putExtra("Key", fillMaps.get(position));
startActivity(i);
You can use above code in your onItemClickListner.
In this method the third agrument is position. So you have to use this eg. The Arraylist you are passing to your listView contains the data shown on listView. so use this kind of code
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
String data= mArrlist.get(position);
}
If you are using the arralist of String type otherwise If you are using arraylist of getter setter class then use
mArralist.get(potion).getName();
You should get item #paticular position
HashMap<String, String> item = adapterview.getAdapter().getItem(position);
check your condition according to requirement and by getting data from item and process further.
Intent i=new Intent(ListViewA.this,ListViewA.class);
i.putExtra("item", item);
startActivity(i);
For adding arbitrary number you can use the Random class of java as below
Random mRandom = new Random();
int random = mRandom.nextInt(mMoveToList.size());
random variable of int type return every time random value.
you can use getItem(int position) of SimpleAdapter
put your SimpleAdapter variable adapter as global
in your ClickListener call adapter.getItem(position)

Categories

Resources