How to add an image to a sqlite ListView? - android

so far i have an android app which can save data (Simple text) into a sqlite database and display it in to a list view. I would like to be able to add images as well but i dont know how.
here is the class which creates the rows everytime i add some text:
public class TestDatabaseActivity extends ListActivity {
private CommentsDataSource datasource;
int holanumero;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_database);
datasource = new CommentsDataSource(this);
datasource.open();
List<Comment> values = datasource.getAllComments();
// use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this, android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
final ListView listadeutiles = (ListView) findViewById(android.R.id.list);
//
listadeutiles.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
holanumero = position;
}});
}
// Will be called via the onClick attribute
// of the buttons in main.xml
public void onClick(View view) {
#SuppressWarnings("unchecked")
ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) getListAdapter();
Comment comment = null;
switch (view.getId())
{
case R.id.add:
EditText texto1 = (EditText) findViewById(R.id.editText1);
String palabra1 = texto1.getText().toString();
EditText texto2 = (EditText) findViewById(R.id.editText2);
String palabra2 = texto2.getText().toString();
String palabra3 = palabra1 + palabra2;
comment = datasource.createComment(palabra3);
adapter.add(comment);
texto1.setText("");
texto2.setText("");
break;
case R.id.delete:
if (getListAdapter().getCount() > 0) {
comment = (Comment) getListAdapter().getItem(holanumero);
datasource.deleteComment(comment);
adapter.remove(comment);
}
break;
}
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}

Saving images in the database is rarely I good idea. You should store the file path to the image in the sd card, and then load that image in your getView() method in the ListView's adapter.

Related

How to reload list view after delete all item?

I have a delete all button and everytime it delete all item in a listview, the listview won't road but stay the same, they will reload only when I create a new item or restart this activity. I have print a log on my code and it seems that the list view reload before the delete method called. my code is this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DBHelper db = new DBHelper(this);
final ListView listView = (ListView) findViewById(R.id.listView);
TextView empty = (TextView) findViewById(R.id.empty);
ArrayList<Inventory> listArray = new ArrayList<>();
listArray.clear();
listArray = db.read();
if (listArray.size() == 0) {
empty.setText("No Items");
} else {
empty.setText("");
}
ListViewAdapter customAdapter = new ListViewAdapter(listArray);
customAdapter.notifyDataSetChanged();
listView.setAdapter(customAdapter);
Button add_button = (Button) findViewById(R.id.button);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addNewItem(view);
}
});
Button button_deleteAll = (Button) findViewById(R.id.button_deleteAll);
button_deleteAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deteleAll();
DBHelper db = new DBHelper(MainActivity.this);
final ListView listView = (ListView) findViewById(R.id.listView);
TextView empty = (TextView) findViewById(R.id.empty);
ArrayList<Inventory> listArray = new ArrayList<>();
listArray.clear();
listArray = db.read();
Log.v("arraysize:", String.valueOf(listArray.size()));
if (listArray.size() == 0) {
empty.setText("No Items");
} else {
empty.setText("");
}
ListViewAdapter customAdapter = new ListViewAdapter(listArray);
customAdapter.notifyDataSetChanged();
listView.setAdapter(customAdapter);
}
});
}
The method deleteAll() deletes all the data in SQLite.
I wish to know how to reload listview after this method called, rather than reload before this method.
add the delete all method in your adapter. call the deleteAll method of your adapter whenever button was clicked. the deleteAll method would be like below:
public void setListArray(ArrayList arrayList)
{
//assuming your adapter list is named "listArray"
this.listArray = arrayList;
notifyDataSetChanged();
}
and in your button click simply write this code:
button_deleteAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//assuming your list of itames here is named "mListArray"
mListArray.clear();
adapter.setListArray(mListArray);
}
}
I guess there is no need to initialize the customAdapter again in the button OnClick method. Also no need to setAdapter again.
Try to remove these lines in the onClick method.
Hope this fixes you issue.
Just add notifyDataSetChanged(); to your Adapter, inside a Listener. For example:
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override public void onItemClick(AdapterView<?> parent, android.view.View view, int position, long id) {
myArrayList.remove(position);
myArrayAdapter.notifyDataSetChanged();
}
});

Android - ListView layout two line list item

I have a listview with two lines of items: user ID and username. How to retrieve only user ID from the listview when one of the rows is clicked?
public class MainActivity extends AppCompatActivity {
private DatabaseReference mUsers;
String getValue = null;
ListView lvUsers = (ListView) findViewById(R.id.lvUsers);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsers = FirebaseDatabase.getInstance.getReference().child(Constants.FIREBASE_USERS);
FirebaseListAdapter<Users> adapter = new FirebaseListAdapter<Users>(
this, Users.class, android.R.layout.two_line_list_item, mUsers
) {
#Override
protected void populateView(View v, Users user, int pos) {
((TextView)v.findViewById(android.R.id.text1)).setText(user.getUserID());
((TextView)v.findViewById(android.R.id.text2)).setText(user.getUsername());
}
};
lvUsers.setAdapter(adapter);
setupListViewMenu();
}
private void setupListViewMenu() {
lvUsers.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
// How to retrieve only User ID from here?
getValue = ((TextView)view).getText().toString();
return true;
}
});
}
}
The listview data is from Firebase database. Is retrieving using for loop the only way? I have to loop through two dimensional array? Thanks
Could you please try the code below?
getValue = ((TextView)item.findViewById(android.R.id.text2)).getText().toString();
I believe that android.R.id.text2 is one of the childs of item(View received in the clickListener)
But need to test... Hope it works

Android Studio ListView - null pointer exception when trying to extract text from selected item

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);

sqlite database and listview

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);

Two dependent spinners

The items of the first one are defined in xml (<string-array>) but the second one should present different items arrays of strings according what is selected on the first...
The possible array of strings for the seconds are fetch from a web service using an AsyncTask (This part is working). In my onPostExecute(Void result) I have this:
private class GetInfoTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog = new ProgressDialog(StateTabActivity.this);
//...
#Override
protected void onPostExecute(Void result) {
Log.d("StateTabActivity","onPostExecute");
sectorsArray = getSectorsName(); // sectorsArray is an array of strings
roomsArray = getRoomsName(); // roomsArray is an array of strings
subcategorySpinnerAdapter = new ArrayAdapter<String>(StateTabActivity.this, R.layout.my_spinner,sectorsArray);
subcategorySpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
subCategorySpinner.setAdapter(subcategorySpinnerAdapter);
dialog.dismiss();
}
}
On the onCreate() of my activity I have:
Spinner categorySpinner = (Spinner) findViewById(R.id.statetab_category_spinner);
ArrayAdapter<String> categorySpinnerAdapter = new ArrayAdapter<String>(this, R.layout.my_spinner,getResources().getStringArray(R.array.array_category));
categorySpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
categorySpinner.setAdapter(categorySpinnerAdapter);
subCategorySpinner = (Spinner) findViewById(R.id.statetab_subcategory_spinner);
categorySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Log.d("StateTabActivity","in onitemselected");
switch (arg2) {
case 0:
//I want to set here the items of sectorsArray to be displayed on the second spinner (subCategorySpinner)
break;
case 1:
//I want to set here the items of roomsArray to be displayed on the second spinner (subCategorySpinner)
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
So my question is: What should I do to bind the right array to the second spinner, according what is selected on the first one?
This is my code to get district list as per selected state.
final Spinner state = (Spinner)_activity.findViewById(R.id.state);
final Spinner district= (Spinner) _activity.findViewById(R.id.district);
_activity.findViewById(R.id.name_of_city);
state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> adapter, View v, int i, long lng) {
if(i == 0){
districtAdapter =new ArrayAdapter<CharSequence>( _activity , android.R.layout.simple_spinner_item, **DistrictList**.AndraPradesh);
//DistricList is another class.its code given below
districtAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
district.setAdapter(districtAdapter);
if(_viewState == SAVED_VIEW){
district.setSelection(getArraySpinner(DistrictList.AndraPradesh,_initialValues.getAsString("District")),true);
}
}
In DistricList class,
public class DistrictList {
public static final String[] AndraPradesh = new String[] {"Adilabad",
"Anantapur",
"Chittoor",
"East Godavari",
"Guntur",
"Hyderabad",
"Karimnagar",
"Khammam"};
}
}

Categories

Resources