I am using Database to inflate my list view and i am using simple cursor adapter to do that. Now i want to expand row on list item click(Like if user Clicks on row, two text views of current row visible to him). I searched a lot but not find any answer. please help!!!! Thank you.
public class CallLogs extends Activity {
EditText from,to;
Button call;
TextView call_from,call_to,date_call,verify;
private SQLiteDatabase database;
String fields[] = { "from", "to", "date" };
private CursorAdapter dataSource;
long profile_counts;
SQLiteDatabase sqLiteDatabase;
DataBaseHandler dbHelper;
MyDataBaseHelper databaseHelper;
MyDBHelper databaseHelper_new;
Button get;
ListView listView;
RelativeLayout r2;
private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.call_logs);
databaseHelper_new= new MyDBHelper(this);
from = (EditText)findViewById(R.id.from);
to = (EditText)findViewById(R.id.to);
call_from = (TextView)findViewById(R.id.textView4);
call_to = (TextView)findViewById(R.id.textView6);
date_call = (TextView)findViewById(R.id.textView8);
verify = (TextView)findViewById(R.id.call_from);
call = (Button) findViewById(R.id.call);
get = (Button) findViewById(R.id.get);
call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String from_num = from.getText().toString();
call_from.setText(from_num);
String to_num = to.getText().toString();
call_to.setText(to_num);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());
DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy, HH:mm:ss");
String date = df.format(Calendar.getInstance().getTime());
date_call.setText(date);
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
Log.d("currentDateandTime",date+"");
String duration = "6 seconds";
databaseHelper_new.addFriend(from_num,to_num,duration,date);
dataAdapter.notifyDataSetChanged();
}
});
displayListView(); }
private void displayListView() {
Cursor cursor = databaseHelper_new.getFriends();
// The desired columns to be bound
String[] columns = new String[] { "call_from", "call_to","call_duration","call_date"};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.code,
R.id.name,
R.id.continent,
R.id.region,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new MyCursorAdapter(
this, R.layout.country_info,
cursor,
columns,
to,
0);
listView = (ListView) findViewById(R.id.listView);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String countryCode = cursor.getString(cursor.getColumnIndexOrThrow("call_from"));
Toast.makeText(getApplicationContext(),countryCode, Toast.LENGTH_SHORT).show();}});}
private class MyCursorAdapter extends SimpleCursorAdapter{
public MyCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//get reference to the row
View view = super.getView(position, convertView, parent);
//check for odd or even to set alternate colors to the row background
if(position % 2 == 0){
view.setBackgroundColor(Color.rgb(238, 233, 233));
}
else {
view.setBackgroundColor(Color.rgb(255, 255, 255));
}
return view;
}}}
Maybe it's not possible please use class that extends BaseAdapter
Related
I'm working on a android project and a got stuck. I'm trying to get an item from a ListView but all I get is info about the item's position in the database I created and not the item itself.
this is my code :
public class Map extends Activity {
Cursor cursor;
ListView listView;
String categoria = "livro";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
final CitySQL dbHelper = new CitySQL(Map.this, null, null, 1);
final SQLiteDatabase db = dbHelper.getWritableDatabase();
final String[] camposDb = {"city", BaseColumns._ID};
cursor = db.query("cities", camposDb, null, null, null, null, "city ASC");
int[] camposView = new int[] {android.R.id.text1};
#SuppressWarnings("deprecation")
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(Map.this,
android.R.layout.two_line_list_item, cursor, camposDb, camposView);
listView= (ListView)findViewById(R.id.city_list);
listView.setAdapter(adapter);
final Geocoder geocoder=new Geocoder(this, Locale.ENGLISH);
listView.setOnItemClickListener(new OnItemClickListener(){
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onItemClick(AdapterView<?> parent, View view, int posicao,long id) {
final String morada = listView.getAdapter().getItem(posicao).toString();
Toast.makeText(Map.this, morada, Toast.LENGTH_LONG).show();
I made a Toast to see exactly what was happening when I clicked but my goal is to get the item (a city name) and look for a location.
Change
final String morada = listView.getAdapter().getItem(posicao).toString();
to
Cursor cursor = (Cursor) listView.getAdapter().getItem(posicao);
String morada = cursor.getString(cursor.getColumnIndex("column_name_for_city"));
i have written a program which displays a spinner but i want to display a listview inside the same activity when i select any item of the spinner , i have also written a code for custom adapter to display items inside the listview and the the listviews row has 6 textviews all of which data comes from String-array defined inside strings.xml file , so need some help
Result_Date.java which has a spinner and the resources , dont know what all to call inside "onitemselected" method
public class Result_Date extends Activity {
ImageView iv;
String[] years = { "Select year", "2000", "2001", "2002", "2003", "2004",
"2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012",
"2013", "2014" };
ArrayAdapter<String> adapter;
ListView lv;
String[] name;
String[] mobile;
String[] gender;
String[] age;
String[] disease;
String[] day;
String[] month;
String[] year;
int[] images = { R.drawable.photo_bg, R.drawable.photo_bg,
R.drawable.photo_bg, R.drawable.photo_bg, R.drawable.photo_bg,
R.drawable.photo_bg, R.drawable.photo_bg, R.drawable.photo_bg };
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.result_list_year);
spinner = (Spinner) findViewById(R.id.btnShowYear);
iv = (ImageView) findViewById(R.id.imgBackReuslt);
adapter = new ArrayAdapter<String>(getBaseContext(),
R.layout.spinner_item, R.id.textView1, years) {
#Override
//this method is used to hide the default text "Select Year" which repeats twice
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View v = null;
if (position == 0) {
TextView tv = new TextView(getContext());
tv.setHeight(0);
tv.setVisibility(View.GONE);
v = tv;
} else {
v = super.getDropDownView(position, null, parent);
}
parent.setVerticalScrollBarEnabled(false);
return v;
}
};
adapter.setDropDownViewResource(R.layout.spinner_item);
spinner.setAdapter(adapter);
Resources res = getResources();
name = res.getStringArray(R.array.Name);
mobile = res.getStringArray(R.array.Mobile);
gender = res.getStringArray(R.array.Gender);
age = res.getStringArray(R.array.Age);
disease = res.getStringArray(R.array.DiagnosisName);
day = res.getStringArray(R.array.day_array);
month = res.getStringArray(R.array.month_year);
year = res.getStringArray(R.array.year_array);
lv = (ListView) findViewById(R.id.lstShowYear);
MyAdapter adapter = new MyAdapter(getBaseContext(), name, mobile,
gender, age, images, day, month, year, disease);
lv.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
public void onClick(View v) {
super.onBackPressed();
finish();
}
My CustomAdapter MyAdapter.java
public class MyAdapter extends ArrayAdapter<String> {
Context context;
int[] images;
String[] namearray;
String[] mobilearray;
String[] genderarray;
String[] agearray;
String[] diseasearray;
String[] dayarray;
String[] montharray;
String[] yeararray;
public MyAdapter(Context c, String[] name, String[] mobile,
String[] gender, String[] age, int[] img, String[] disease,
String[] day, String[] month, String[] year) {
super(c, R.layout.row_layout, R.id.textView1, name);
// TODO Auto-generated constructor stub
this.context = c;
this.namearray = name;
this.mobilearray = mobile;
this.genderarray = gender;
this.agearray = age;
this.diseasearray = disease;
this.dayarray = day;
this.montharray = month;
this.yeararray = year;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ListView lv;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.row_layout, parent, false);
ImageView image = (ImageView) row.findViewById(R.id.imgView);
TextView text1 = (TextView) row.findViewById(R.id.txtName);
TextView text2 = (TextView) row.findViewById(R.id.txtMobile);
TextView text3 = (TextView) row.findViewById(R.id.txtGender);
TextView text4 = (TextView) row.findViewById(R.id.txtAge);
TextView text5 = (TextView) row.findViewById(R.id.txtDesease);
TextView text6 = (TextView) row.findViewById(R.id.txtDate);
lv = (ListView) row.findViewById(R.id.listView1);
image.setImageResource(images[position]);
text1.setText(namearray[position]);
text2.setText(mobilearray[position]);
text3.setText(genderarray[position]);
text4.setText(agearray[position]);
text5.setText(diseasearray[position]);
text6.setText(dayarray[position]);
text6.setText(montharray[position]);
text6.setText(yeararray[position]);
return row;
}
}
Do i need to write the code from defining Resources obj till setting the adapter inside onitemselected method ??
any suggestions are welcomed
I'll do the following thing:
Create a method inside my ListAdapter named for example "refreshList" that could take as parameter the data from the selected spinner item that you need to "get" the data you need to fill the list with by the spinner's value selected. For example if the data that change the list is the YEAR the function could be something like this:
public void refreshList(String year) {
//Fill the arrays with the data according to the year
namearray = getResources().getStringArray(R.array.Name);
//Do loas all the data you need according to the year here
//And the refresh the adapter
this.notifyDataSetChanged();
}
Then in your onItemSelected call of the spinner call that function of the ListAdapter like adapter.refreshList(years[position]) or something like that. It's just an idea there is many ways to do this, the point is that you have a function in adapters called notifyDataSetChanged() that load again the list with the data currently in the list/array of data you handle inside the adapter. If the spinner selected value will change the list data then you should use that to refresh the list when the spinner value is selected. Hope it helps
I'm new in Android programming and I'm wondering witch is the most appropriate way to fill a ListView from DataBase.
Here the method I'm using in database to get my items
// Getting All stats
public List<StatParcours> getAllSats() {
List<StatParcours> statList = new ArrayList<StatParcours>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_STATS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
StatParcours stat = new StatParcours();
stat.setID(Integer.parseInt(cursor.getString(0)));
stat.setDate(cursor.getString(1));
stat.setDuration(cursor.getString(2));
stat.setDistance(Double.parseDouble(cursor.getString(3)));
stat.setSpeed(Double.parseDouble(cursor.getString(4)));
stat.setCondition(cursor.getString(5));
// Adding contact to list
statList.add(stat);
} while (cursor.moveToNext());
}
// return contact list
return statList;
}
and in the main activity, I'm using this. I know there is something wrong with the populateMyStatsList method, but I still don't know how to fix it.
public class History extends Activity {
public DatabaseHandler db;
private List<StatParcours> MyStats = new ArrayList<StatParcours>();
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("oncreate", "ok");
super.onCreate(savedInstanceState);
setContentView(R.layout.history);
populateMyStatsList ();
populateListView();
registerClickCallback();
}
private void populateMyStatsList (){
MyStats = db.getAllSats();
}
private void populateListView() {
ArrayAdapter<StatParcours> adapter = new MyListAdapter();
ListView list = (ListView) findViewById(R.id.HistListView);
list.setAdapter(adapter);
Log.i("Populate", "ok");
}
private void registerClickCallback() {
ListView list = (ListView) findViewById(R.id.HistListView);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long id) {
StatParcours clickedCar = MyStats.get(position);
String message = "You clicked position " + position
+ " Which is car make " + clickedCar.getDate();
Toast.makeText(History.this, message, Toast.LENGTH_LONG).show();
}
});
}
private class MyListAdapter extends ArrayAdapter<StatParcours> {
public MyListAdapter() {
super(History.this, R.layout.item_view, MyStats);
Log.i("MyListAdapter", "ok");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
Log.i("Make sure", "ok");
itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false);
}
Log.i("getview", "ok");
StatParcours currentStat = MyStats.get(position);
TextView makeText = (TextView) itemView.findViewById(R.id.item_txtMake);
makeText.setText(currentStat.getDate());
TextView yearText = (TextView) itemView.findViewById(R.id.item_txtYear);
yearText.setText("" + currentStat.getDistance());
TextView condionText = (TextView) itemView.findViewById(R.id.item_txtCondition);
condionText.setText(currentStat.getCondition());
return itemView;
}
}
}
You need to use a SimpleCursor Adapter. I can't reach the developer site for the documentation but here is an example with your code above.
EDIT: Here is the link to the android developer website.
http://developer.android.com/reference/android/widget/SimpleCursorAdapter.html
SECOND EDIT: This would go in the populateListView()
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_STATS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Set your layout to int[]
int[] to = new int[]{R.id.item_txtMake,R.id.item_txtYear,R.id.item_txtCondition};
//set your columns to string[]; fill in your actual column names
string[] from = new string[]{"make","year","condition"};
//set up adapter
SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(),R.layout.item_view, cursor, from,to,null);
//set adapter to listview
ListView list = (ListView) findViewById(R.id.HistListView);
list.setAdapter(adapter);
Since you only have TextView in your ListView you can just simply use SimpleCursorAdapter.
// Getting All stats
public Cursor getAllSats() {
List<StatParcours> statList = new ArrayList<StatParcours>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_STATS;
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery(selectQuery, null);
}
And in your History class
public class History extends Activity {
public DatabaseHandler db;
private List<StatParcours> MyStats = new ArrayList<StatParcours>();
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("oncreate", "ok");
super.onCreate(savedInstanceState);
setContentView(R.layout.history);
Cursor c = getAllSats();
String[] fromColumns = {Your database column name for date,
Your database column name for distance,
Your database column name for condition};
int[] toViews = {R.id.item_txtMake,
R.id.item_txtYear,
R.id.item_txtCondition};
adapter = new SimpleCursorAdapter(this, R.layout.item_view,
c, fromColumns, toViews, 0);
ListView list = (ListView) findViewById(R.id.HistListView);
list.setAdapter(adapter);
registerClickCallback();
}
I had populated a listview using simplecursoradapter. However, I want to add images, wherein if the answer is correct it should display check on the right and if null or incorrect it should display an x-mark. It does not display anything but there is no error. Here is my activity code:
public class Results extends ListActivity{
DBAdapter db = new DBAdapter(this);
private Cursor mCursor;
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.resultslist);
db.open();
fillData();
db.close();
}
private void fillData() {
mCursor = db.getAllInfo();
startManagingCursor(mCursor);
String[] from = new String[]{DBAdapter.KEY_QUESTIONS, DBAdapter.KEY_CORRECTANSWERS, DBAdapter.KEY_YOURANSWERS};
int[] to = new int[]{R.id.textViewquestionresults, R.id.textViewcorrectansresults, R.id.textViewyouranswerresults};
SimpleCursorAdapter c=
new SimpleCursorAdapter(this, R.layout.rowresults, mCursor, from, to);
setListAdapter(c);
}
private class c extends SimpleCursorAdapter{
Context lcontext;
public c(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
lcontext = context;
}
#Override
public View getView(final int pos, View v, ViewGroup parent) {
v = super.getView(pos, v, parent);
final ImageView iv = (ImageView) v.findViewById(R.id.imageViewresults);
final TextView tvQuestion = (TextView) v.findViewById(R.id.textViewQuestion);
final TextView tvCorrectAns = (TextView) v.findViewById(R.id.textViewcorrectansresults);
final TextView tvYourAns = (TextView) v.findViewById(R.id.textViewyouranswerresults);
if(tvYourAns.equals(tvCorrectAns)){
iv.setImageResource(R.drawable.greencheckmark);
}else{
iv.setImageResource(R.drawable.redxmark);
}
return v;
}
}
}
When extending SimpleCursorAdapter, you shouldn't override getView().
You should override newView() and bindView() instead.
In newView() inflate your layout and initialize your views.
In bindView() set your views' values.
I want to be able to fetch a row from a list view and populate textViews in a different activity. I want to be able to do this onclick of an item with the list view..
public class CBFilter extends Activity {
ListView RecipeNames;
Cursor cursor;
SimpleCursorAdapter adapter;
CBDataBaseHelper data;
SQLiteDatabase data2;
TextView RecipeText;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
RecipeNames = (ListView) findViewById(R.id.List1);
RecipeNames.setTextFilterEnabled(true);
RecipeText = (TextView) findViewById(R.id.recipeText);
adapter = new SimpleCursorAdapter (this, 0, cursor, null, null);
data = new CBDataBaseHelper(this);
data.open();
cursor = data.query();
startManagingCursor(cursor);
String[] from = {CBDataBaseHelper.KEY_NAME};
int[] to = { R.id.recipeText};
adapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
RecipeNames.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
public void CreateNew(View view){
Intent myIntent = new Intent(this, CBCreate.class);
startActivity(myIntent);
}
}
How can i convert this code in order to achieve the required functionality.. thanks Stefan
try like this
public void onListItemClick(ListView parent, View v, int position, long id) {
String string = from[position]); // this depends on your Adapter ...
Intent i = new Intent(CheckData.this,ShowData.class);
i.putExtra("SELECTED", string);
startActivity(i);
i got it from this link , it will be use full for you :
Use of SQLite