public class ConnectDatabase extends Activity {
private SimpleDBAdapter mDbHelper;
private ListView list;
private String[] values;
private String[] list1;
private int i=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list=(ListView )findViewById(R.id.simpleListView);
mDbHelper = new SimpleDBAdapter(ConnectDatabase.this);
mDbHelper.createDatabase();
mDbHelper.open();
values = mDbHelper.getEditTextValue();
mDbHelper.close();
for(i=0;i<10;i++) {
String tempvalue;
tempvalue=values[i];
list1[i]=tempvalue;
Log.v("log_tag"," tempvalue "+tempvalue);
Log.v("log_tag", "list1 is"+list1[i]);
//Log.v("log_tag"," list1"+list1[i]);
}
list.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values));
//list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//list.setTextFilterEnabled(true);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
/*for(int i=0;i<values.length;i++) {
String templist=values[i];
list1[i]=templist;
}*/
String fname=values[position];
Log.v("log_tag", "The fname is"+ fname);
Intent intent=new Intent(ConnectDatabase.this, Userinfo.class);
intent.putExtra("FirstName",fname );
startActivity(intent);
}
});
// to remove the last comma
}
}
Here I am doing ListView from SQLite database and want to display in ListView with only the first 10 ListView rows at the time but I get the error at the line list1[i]=tempvalue; so I can't copy array here anyone can help me to do copy the array name values where I get all the Column index values from my SQLite database.
Hope anyone have an idea to do this.
Your post is quite hard to read, but I think the issue is that list1 has not been initialised.
You need to add a line like this:
list1 = new String[10];
before you attempt to set a value within the array.
ps - I picked a value of 10 as your for loop has i<10.
Related
Hi I have been working through several different tutorials on getting data from a sql database into a listview. I can add data, get data from database and populate the list view, and have a working onclick listener (will fire off a Toast message). However I can not get any data from the listview when clicked. I have tried different combinations of getitem and getItemAtPosition but they all return a empty string(blank toast). Would someone be kind enough to look at my code and tell me if what I am trying to do is possible. In my listview i have four items in each entry, I would like to either get the fourth item directly or get all the items (as string?) then I can pull out the data I need.
Thanks in advance for your time.
public class ListViewActivity extends Activity {
SQLiteHelper SQLITEHELPER;
SQLiteDatabase SQLITEDATABASE;
Cursor cursor;
SQLiteListAdapter ListAdapter ;
ArrayList<String> ID_ArrayList = new ArrayList<String>();
ArrayList<String> GENRE_ArrayList = new ArrayList<String>();
ArrayList<String> NAME_ArrayList = new ArrayList<String>();
ArrayList<String> URL_ArrayList = new ArrayList<String>();
ListView LISTVIEW;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
LISTVIEW = (ListView) findViewById(R.id.listView1);
SQLITEHELPER = new SQLiteHelper(this);
}
#Override
protected void onResume() {
ShowSQLiteDBdata() ;
super.onResume();
}
private void ShowSQLiteDBdata() {
SQLITEDATABASE = SQLITEHELPER.getWritableDatabase();
cursor = SQLITEDATABASE.rawQuery("SELECT * FROM demoTable1", null);
ID_ArrayList.clear();
GENRE_ArrayList.clear();
NAME_ArrayList.clear();
URL_ArrayList.clear();
if (cursor.moveToFirst()) {
do {
ID_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_ID)));
GENRE_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Genre)));
NAME_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Name)));
URL_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Url)));
} while (cursor.moveToNext());
}
ListAdapter = new SQLiteListAdapter(ListViewActivity.this,
ID_ArrayList,
GENRE_ArrayList,
NAME_ArrayList,
URL_ArrayList
);
LISTVIEW.setAdapter(ListAdapter);
LISTVIEW.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// String text = (String) LISTVIEW.getAdapter().getItem(position);
String text = (String) LISTVIEW.getItemAtPosition(position);
//String text = (String) lv.getItemAtPosition(0);
// Object item = (Object) LISTVIEW.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
});
cursor.close();
}
}
LISTVIEW.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String value1 = ID_ArrayList.get(position);
String value2 = GENRE_ArrayList.get(position);
String value3 = NAME_ArrayList.get(position);
String value4 = URL_ArrayList.get(position);
Toast.makeText(getApplicationContext(),value1+" "+value2+" "+value3+" "+value4, Toast.LENGTH_SHORT).show();
}
});
try to change the line
String text = (String) LISTVIEW.getItemAtPosition(position);
with
String text = (String) parent.getItemAtPosition(position);
this should be the way ListView works.
Also i suggest you to not use Capital Cases with variables, usually in Java is used a CamelCase convention. And also have a look at RecyclerView, that usually is implemented today much more than ListView, because allow a great level of customization
Pls use below code within listview setOnItemClickListener :-
String genreID = ID_ArrayList.get(position);
String genre = GENRE_ArrayList.get(position);
String genreName = NAME_ArrayList.get(position);
String genreUrl = URL_ArrayList.get(position);
Toast.makeText(getApplicationContext(), genreID+", "+genre+","+genreName+", "+genreUrl+", "+, Toast.LENGTH_SHORT).show();
its return render data of listview.
try this,
ShowSQLiteDBdata() in onCreate() instead of onResume() method
hello i need some help ... i write this code but i am little confused when i add book to my fav it store to fav when i click on un fav there in fav list the book are still there in that activity until i don't close the activity when i reopen that fav activity the book are removed from there i want to add code that can refresh by self at that time when i un fav the book ... please help me out
public class Favrt extends AppCompatActivity implements AdapterView.OnItemClickListener {
ListView viewF;
Books_Adapter fav_adapter;
String[] name, links, author;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favrt);
fetch_fav();
fav_adapter = new Books_Adapter(this, name, links, author);
viewF = (ListView) findViewById(R.id.favView);
viewF.setAdapter(fav_adapter);
viewF.setOnItemClickListener(this);
}
public void fetch_fav(){
SQLiteDatabase database = openOrCreateDatabase("Pdf_books",MODE_PRIVATE,null);
Cursor db_cursor = database.rawQuery("select * from favourite", null);
name = new String[db_cursor.getCount()];
links = new String[db_cursor.getCount()];
author = new String[db_cursor.getCount()];
int i =0;
if (db_cursor.moveToLast()){
do {
name[i] = db_cursor.getString(db_cursor.getColumnIndex("name"));
links[i] = db_cursor.getString(db_cursor.getColumnIndex("links"));
author[i] = db_cursor.getString(db_cursor.getColumnIndex("author"));
i++;
}while (db_cursor.moveToPrevious());
}
database.close();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent web = new Intent(this, web_activity.class);
web.putExtra("url", links[position]);
startActivity(web);
}
#Override
public void onContentChanged() {
super.onContentChanged();
View empty = findViewById(R.id.empty);
ListView list = (ListView) findViewById(R.id.favView);
list.setEmptyView(empty);
}
}
Try fav_adapter.notifyDataSetChanged() after changing your list items (in this case, when your favorites are changed).
You have to update adapter. to do so fav_adapter.notifyDataSetChanged(). which will make changes to listview.
make function in activity where you do such things like remove from db and update list data.
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);
Okay, I have searched threw here and did not find my answer at all. What my android app is suppose to be doing is get a list from my php & mysql server, then store it on the database on the phone. This all works, and I can even create a listview with the information from my sqlite db. Where I am stuck as a new coder is trying to figure out how to display the information when they click on the listview item that will take them to another page that will show all the details for that listview.
So in short what I want is have my listview, items 1,item 2, item 3 for example, then when they click item 2, it gets the information for item 2 and displays it. Can someone point me in the correct direction, i know i have to use setOnClickListener, but just unsure how to make it look for that certain item.
public class Events extends Activity
{
// Identifies a particular Loader being used in this component
String event_name, event_time, event_price, event_loc;
static JSONObject object =null;
DBAdapter myDb;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.events);
openDB();
new PrefetchData().execute();
// used to refresh my page.
Button button = (Button) findViewById(R.id.refresh);
button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
openDB();
new PrefetchData().execute();
}
});
}
#Override
protected void onDestroy()
{
super.onDestroy();
closeDB();
}
private void openDB()
{
myDb = new DBAdapter(this);
myDb.open();
}
private void closeDB()
{
myDb.close();
}
private class PrefetchData extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
myDb.deleteAll();
JsonParser jsonParser = new JsonParser();
String json = jsonParser.getJSONFromUrl("http://www.website.com/test.json");
Log.e("JSON Response: ", "> " + json);
if (json != null)
{
try
{
JSONObject parent = new JSONObject(json);
JSONArray eventDetails = parent.getJSONArray("event");
for(int i=0; i < eventDetails.length(); i++)
{
object = eventDetails.getJSONObject(i);
event_name = object.getString("event_name");
event_time = object.getString("event_time");
event_price = object.getString("event_price");
event_loc = object.getString("event_loc");
//event_pic = object.getString("event_pic");
myDb.insertRow(event_name,event_time,event_price,event_loc);
Log.e("JSON", "> " + event_name + event_time + event_price + event_loc );
}
} catch (JSONException e)
{
// TODO Auto-generated catch block
Log.e("Json Error", "Error: " + e.toString());
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
populateListViewFromDB();
myDb.close();
// After completing http call
// will close this activity and lauch main activity
//Intent i = new Intent(MainActivity.this, Events.class);
//i.putExtra("event_name", event_name);
//i.putExtra("event_time", event_time);
//i.putExtra("event_price", event_price);
//startActivity(i);
// close this activity
//finish();
}
}
#SuppressWarnings("deprecation")
private void populateListViewFromDB()
{
Cursor cursor = myDb.getAllRows();
// Allow activity to manage lifetime of the cursor.
// DEPRECATED! Runs on the UI thread, OK for small/short queries.
startManagingCursor(cursor);
// Setup mapping from cursor to view fields:
String[] fromFieldNames = new String[]
{DBAdapter.KEY_NAME, DBAdapter.KEY_TIME, DBAdapter.KEY_PRICE, DBAdapter.KEY_LOC};
int[] toViewIDs = new int[]
{R.id.item_name};//, R.id.item_time};//, R.id.item_price, R.id.item_loc};
// Create adapter to may columns of the DB onto elemesnt in the UI.
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
this, // Context
R.layout.item_layout, // Row layout template
cursor, // cursor (set of DB records to map)
fromFieldNames, // DB Column names
toViewIDs // View IDs to put information in
);
// Set the adapter for the list view
ListView myList = (ListView) findViewById(R.id.listViewfordb);
myList.setAdapter(myCursorAdapter);
}
}
Don't use the setOnClickListener.
Be sure to use a CursorAdapter and to specify an ID column inside your db.
when you set the protected void onListItemClick(ListView l, View v, int position, long id) automatically the id is the ID inside the db. this way you can pass it through an intent and use the id to get back the data from the db.
Hope it's clear enough. Sorry i wrote quite in a rush
from your code simply add
myList.setOnItemClickListener(
new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
//here the id value is what you need to take data from the db filtering by id
}
}
);
you should set listeners to your ListView something like this
private OnItemClickListener onListItemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
// TODO YOUR CODE
}
};
private OnItemLongClickListener onItemLongClickListener = new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View view, int position, long id) {
YOUR_CODE
}
};
those are two types, longClicj and just click, you can use it both or one, its depends on your needs
also on your onCreate method you should set the listeners to your listView
listView.setOnItemClickListener(onListItemClickListener);
listView.setOnItemLongClickListener(onItemLongClickListener);
I am developing an android application pertaining to sms. I have managed to display a listView of all the messages in my android emulator, but i can't figure out what code should i write in the onItemClickListener such that whenever i click any row of my listview i should get the data(here.. message body) associated with it in another screen. What ahould i do about this?
My code is given below:
public class mainmenu extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle SavedInstanceState)
{
super.onCreate(SavedInstanceState);
setContentView(R.layout.main);
super.onStart();
{
final ListView list = (ListView) findViewById(R.id.list);
List<String> msgList = getSMS();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, msgList);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
// TODO Auto-generated method stub
}
});
}
}
public List<String> getSMS()
{
List<String> sms = new ArrayList<String>();
Uri uriSMSURI = Uri.parse("content://sms/inbox");
Cursor cur = getContentResolver().query(uriSMSURI, null, null,null,null);
while (cur.moveToNext())
{
String address=cur.getString(cur.getColumnIndex("address"));
String body = cur.getString(cur.getColumnIndexOrThrow("body"));
sms.add("Number: " + address + " .Message: " + body);
}
return sms;
}
}
Please give me the code that i should write in the OnItemClickListener as per the specifications i mentioned above. It's a bit urgent.
Just use the adapter there as such:
String itemAtClickedIntex = (String)adapter.getItem(position);
Hope this helps your urgent request :) please don't forget to accept as it encourages us to keep contributing.
Best
-serkan