I have created a working ViewBinder to use with my simpleCursorAdapter, and all is functioning properly. The desired images display as they should,etc. But when I was testing my code, I put a log my in my viewbinder that displays the criteria for displaying the image. When I look at logCat, it shows two iterations of the results as shown below. (there are only five entries). Which would in turn create two iterations of my if statements and resulting image display. This isn't a problem with the display, but it would create some redundancy in that it would display the images in the listView twice.
LOG FILE:
columnIndex=1 categoryIdentifier = Supplier
columnIndex=1 categoryIdentifier = Customer
columnIndex=1 categoryIdentifier = Other
columnIndex=1 categoryIdentifier = Other
columnIndex=1 categoryIdentifier = Other
columnIndex=1 categoryIdentifier = Supplier
columnIndex=1 categoryIdentifier = Customer
columnIndex=1 categoryIdentifier = Other
columnIndex=1 categoryIdentifier = Other
columnIndex=1 categoryIdentifier = Other
The code to run the viewBinder is this:
CODE:
private void fillData() {
//The desired columns to be bound:
String[] from = new String[] { ContactsDB.COLUMN_CATEGORY, ContactsDB.COLUMN_LAST_NAME, ContactsDB.COLUMN_FIRST_NAME };
//The XML views that the data will be bound to:
int[] to = new int[] {R.id.contact_icon, R.id.label2, R.id.label};
getLoaderManager().initLoader(0, null, this);
adapter = new SimpleCursorAdapter(this, R.layout.contact_row, null, from, to, 0);
// Set the ViewBinder to alternate the image in the listView
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
// int viewId = view.getId();
int categoryIndex = cursor.getColumnIndexOrThrow(ContactsDB.COLUMN_CATEGORY);
if(columnIndex == categoryIndex)
{
String categoryIdentifier = cursor.getString(columnIndex);
//switch categoryIdentifier
if(categoryIdentifier.equalsIgnoreCase("Supplier")){
displayImage = (ImageView) view;
displayImage.setImageResource(R.drawable.supplier);
}
if(categoryIdentifier.equalsIgnoreCase("Other")){
displayImage = (ImageView) view;
displayImage.setImageResource(R.drawable.other);
}
Log.v("TEST COMPARISON", "columnIndex=" + columnIndex + " categoryIdentifier = " + categoryIdentifier);
return true;
}
return false;
}
});
setListAdapter(adapter);
} // end of fillData
// Sort the names by last name, then by first name
String orderBy = ContactsDB.COLUMN_LAST_NAME + " COLLATE NOCASE ASC"
+ "," + ContactsDB.COLUMN_FIRST_NAME + " COLLATE NOCASE ASC" ;
// Creates a new loader after the initLoader () call
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
//String[] projection = { ContactsDB.ROW_ID, ContactsDB.COLUMN_LAST_NAME, ContactsDB.COLUMN_FIRST_NAME };
String[] projection = { ContactsDB.ROW_ID, ContactsDB.COLUMN_CATEGORY, ContactsDB.COLUMN_LAST_NAME, ContactsDB.COLUMN_FIRST_NAME };
CursorLoader cursorLoader = new CursorLoader(this,
whateverContentProvider.CONTENT_URI, projection, null, null, orderBy);
return cursorLoader;
}
Anyone know why there would be this redundancy?
change your listview android:layout_height to match_parent
Related
Aim of my program is to store data in SQLite database and then use that database in list view.
I have provided the codes ( deleted some unnecessary codes) below.
I have inserted successfully some dummy data in database.
Layout for custom adapter is also working properly.
My app is crashing when creating the object of Timetable adapted.
I have tried all the way which I can do, but not working.
If need some more information please let me know.
In MainActivity.java
TimeTableDBHelper timeTableDbHelper = new TimeTableDBHelper(this);
SQLiteDatabase db = timeTableDbHelper.getWritableDatabase();
db = timeTableDbHelper.getReadableDatabase();
String[] columns = {TimeTableContract.COLUMN_NAME_START_TIME,TimeTableContract.COLUMN_NAME_END_TIME,
TimeTableContract.COLUMN_NAME_DATE,
TimeTableContract.COLUMN_NAME_MONTH
};
Cursor cursor = db.query(TimeTableContract.TABLE_NAME, columns, null, null, null, null, null);
//My app is crashing after this line only
TimeTableAdapter adapter = new TimeTableAdapter(this, cursor);
ListView listView = (ListView) findViewById(R.id.mainListView1);
listView.setAdapter(adapter);
cursor.close();
TimetableAdapter.java
public class TimeTableAdapter extends CursorAdapter
{
public TimeTableAdapter(Context context, Cursor cursor)
{
super(context,cursor,0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
return LayoutInflater.from(context).inflate(R.layout.table_list_view, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor)
{
int startColumnIndex = cursor.getColumnIndex(TimeTableContract.COLUMN_NAME_START_TIME);
String time1 = cursor.getString(startColumnIndex);
int endColumnIndex = cursor.getColumnIndex(TimeTableContract.COLUMN_NAME_END_TIME);
String time2 = cursor.getString(endColumnIndex);
int dateColumnIndex = cursor.getColumnIndex(TimeTableContract.COLUMN_NAME_DATE);
String date = cursor.getString(dateColumnIndex);
int monthColumnIndex = cursor.getColumnIndex(TimeTableContract.COLUMN_NAME_MONTH);
String month = cursor.getString(monthColumnIndex);
TextView startTime = (TextView) view.findViewById(R.id.start_time);
TextView endTime = (TextView) view.findViewById(R.id.end_time);
TextView tuitorName = (TextView) view.findViewById(R.id.tuitor_name);
TextView subject = (TextView) view.findViewById(R.id.subject);
TextView remarks = (TextView) view.findViewById(R.id.remarks);
TextView dateMonth = (TextView) view.findViewById(R.id.date);
startTime.setText(time1);
endTime.setText(time2);
tuitorName.setText("Tutor");
subject.setText("subject");
remarks.setText("remarks...");
dateMonth.setText(date+", " + month);
}
Contract class
public class TimeTableContract
{
// Make constructor private do that it does not initiatted accidently
private TimeTableContract()
{};
public static final String TABLE_NAME = "time_table";
public static final String COLUMN_NAME_START_TIME = "start_time";
public static final String COLUMN_NAME_END_TIME = "end_time";
public static final String COLUMN_NAME_DATE = "date";
public static final String COLUMN_NAME_MONTH = "month";
public static final String COLUMN_NAME_ID = "_id";
}
Creating table in database by following code ( by the way there is no problem with my database helper class)
"CREATE TABLE " + TimeTableContract.TABLE_NAME + " ( " +
TimeTableContract.COLUMN_NAME_ID + " INTEGER PRIMARY KEY," +
TimeTableContract.COLUMN_NAME_START_TIME + " TEXT," +
TimeTableContract.COLUMN_NAME_END_TIME + " TEXT,"+
TimeTableContract.COLUMN_NAME_DATE + " TEXT,"+
TimeTableContract.COLUMN_NAME_MONTH + " TEXT)";
You are missing the "_id" column in your cursor here:
String[] columns = {TimeTableContract.COLUMN_NAME_START_TIME,
TimeTableContract.COLUMN_NAME_END_TIME,
TimeTableContract.COLUMN_NAME_DATE,
TimeTableContract.COLUMN_NAME_MONTH
};
It's an android convention that you must include "_id" column in your cursor if you are working with CursorAdapters and ListViews or else they won't work.
When you implement onItemClick() method for your listview, you will get that same _id as an argument named long id
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, **long id**)
I am trying to make an android application that allows the user to create a custom workout list from an already existing list of workouts. I decided to create an sqlite database to accomplish this task. In my database handler class "DBHandles.java" I have created and populated "Table_Workouts" with all the available workouts in the application. Also in "DBHandles.java" I have created another empty table "Table_User_List" for the purpose of holding specific entries from the "Table_Workouts" table that the user selects. "Table_User_List" needs to be populated at runtime.
public class DBhandles extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Workouts.db";
public static final String TABLE_WORKOUTS = "Workouts";
public static final String TABLE_USER_LIST = "UserWorkouts";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_DESCRIPTION = "description";
public static final String COLUMN_LINK = "link";
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_WORKOUTS_TABLE = "CREATE TABLE " +
TABLE_WORKOUTS + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_DESCRIPTION + " TEXT,"
+ COLUMN_LINK + " TEXT" + ")";
String CREATE_USER_TABLE ="CREATE TABLE " +
TABLE_USER_LIST + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_DESCRIPTION + " TEXT,"
+ COLUMN_LINK + " TEXT" + ")";
db.execSQL(CREATE_WORKOUTS_TABLE);
db.execSQL(CREATE_USER_TABLE);
db.execSQL("INSERT INTO " + TABLE_WORKOUTS + "(name, description, link) VALUES ('Shoulder Press', 'Shoulder PRess description', 'https://www.youtube.com/watch?v=qEwKCR5JCog')");
public void addWorkout(Workout workout) {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, workout.getWorkoutName());
values.put(COLUMN_DESCRIPTION, workout.getDescription());
values.put(COLUMN_LINK, workout.getLink());
db.insert(TABLE_USER_LIST, null, values);
} catch (Exception e){
Log.d(TAG, "Error while trying to add");
}
finally{
db.endTransaction();
}
//db.close();
}
public Workout findWorkout(String Workoutname) {
String query = "SELECT * FROM " + TABLE_WORKOUTS
+ " WHERE " + COLUMN_NAME
+ " = \"" + Workoutname + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Workout workout = new Workout();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
workout.setID(Integer.parseInt(cursor.getString(0)));
workout.setWorkoutName(cursor.getString(1));
workout.setDescription((cursor.getString(2)));
workout.setLink(cursor.getString(3));
cursor.close();
} else {
workout = null;
}
db.close();
return workout;
}
public boolean deleteWorkout(String Workoutname) {
boolean result = false;
String query = " SELECT * FROM " + TABLE_USER_LIST
+ " WHERE " + COLUMN_NAME
+ " = \"" + Workoutname + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Workout workout = new Workout();
if (cursor.moveToFirst()) {
workout.setID(Integer.parseInt(cursor.getString(0)));
db.delete(TABLE_WORKOUTS, COLUMN_ID + " = ?",
new String[] { String.valueOf(workout.getID()) });
cursor.close();
result = true;
}
db.close();
return result;
}
public ArrayList getAllWorkoutNames (){
return genericGetSQL(TABLE_WORKOUTS, COLUMN_NAME);
}
public ArrayList genericGetSQL(String whichTable, String whichColumn){
ArrayList<String> wrkArray = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(whichTable, new String[]{whichColumn}, null,null, null, null,null);
String fieldToAdd = null;
if(cursor.moveToFirst()){
while(cursor.isAfterLast()==false){
fieldToAdd = cursor.getString(0);
wrkArray.add(fieldToAdd);
cursor.moveToNext();
}
cursor.close();
}
return wrkArray;
}
As you can see I am returning an Arraylist from the DBHandles.class to display the name column of the "Table_Workouts" table. This ArrayList is accessed in my "DisplayAllWorkouts.java" class. The "DiplayAllWorkouts.java" class generates a tablerow for each entry in the "Table_Workouts" table and displays the name column to the user.
public class DisplayAllWorkouts extends AppCompatActivity implements YourListFrag.OnFragmentInteractionListener {
DBhandles db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.displayworkoutlist);
yourListFrag = new YourListFrag();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.LinLayDisplayYourList, yourListFrag, "ARG_PARAM1").
commit();
context = this;
TableLayout tableLayout = (TableLayout) findViewById(R.id.tableLayout);
TableRow rowHeader = new TableRow(context);
rowHeader.setBackgroundColor(Color.parseColor("#c0c0c0"));
rowHeader.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
String[] headerText = {"NAME ", " ADD "};
for (String c : headerText) {
TextView tv = new TextView(this);
tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv.setTextSize(18);
tv.setPadding(5, 5, 5, 5);
tv.setText(c);
rowHeader.addView(tv);
}
tableLayout.addView(rowHeader);
db = yourListFrag.getDb();//new DBhandles(this, null, null, 1);
final ArrayList<String> arrNames = db.getAllWorkoutNames();
final ArrayList<String> arrDesc = db.getAllWorkoutDescription();
final ArrayList<String> arrLink = db.getAllWorkoutsLink();
for (int i = 0; i < arrNames.size(); i++) {
TableRow row = new TableRow(this);
final CheckBox AddBox = new CheckBox(this);
AddBox.setText("ADD");
final TextView nametv = new TextView(this);
//final TextView desctv = new TextView(this);
//final TextView linktv = new TextView(this);
nametv.setTextSize(30);
// desctv.setTextSize(30);
nametv.setText(arrNames.get(i));
//desctv.setText(arrDesc.get(i));
//linktv.setText(arrLink.get(i));
text = nametv.getText().toString();
row.addView(nametv);
row.addView(AddBox);
AddBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
// if(AddBox.isChecked()){
Workout wrk = (db.findWorkout(text));
db.addWorkout(wrk);
yourListFrag.refresh();
// yourListFrag.refresh();
// yourListFrag.refresh(text);
// }
// else{
// db.deleteWorkout(text);
//yourListFrag.delete(nametv.getText().toString());
// yourListFrag.refresh();
// }
}
});
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(DisplayAllWorkouts.this, DisplaySingleWorkout.class);
i.putExtra("itemName", nametv.getText());
i.putStringArrayListExtra("everydesc", arrDesc);
i.putStringArrayListExtra("everyname", arrNames);
i.putStringArrayListExtra("everylink",arrLink);
startActivity(i);
}
});
tableLayout.addView(row);
}
}
#Override
public void onFragmentInteraction(int position) {
}
}
My problem is as follows. I want to be able to click on a table row displayed in the "DisplayAllWorkouts.java" class and have the corresponding row in "Table_Workouts" table be copied to the "Table_User_List" table. Once the row is copied I want the name column of "Table_User_List" displayed in "YourListFrag.java" class and inflated in the "DisplayAllWorkouts.java" class.
public class YourListFrag extends Fragment {
private ArrayAdapter<String> arrayAdapter;
private ListView lstView;
public ArrayList<String> holdNamesFromDB;
final DBhandles db = new DBhandles(getContext(), null, null, 1);
public DBhandles getDb(){
return this.db;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_list, container, false);
lstView = (ListView)rootView.findViewById(R.id.lstView);
holdNamesFromDB = db.getAllUserWorkouts();
arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, holdNamesFromDB);
lstView.setAdapter(arrayAdapter);
public void refresh(){//String text){
//arrayAdapter.add(text);
// db.getAllUserWorkouts();
// arrayAdapter.notifyDataSetChanged();
holdNamesFromDB = db.getAllUserWorkouts();
//arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, db.getAllUserWorkouts());
arrayAdapter.notifyDataSetChanged();
// arrayAdapter.notifyDataSetChanged();
//
}
I need the fragment to refresh its view everytime a new entry is added to the "Table_User_List" so the user can see every entry of the name column of "Table_User_List" in real time. I put logs in my program and the the flow seemed to successfully reach all the appropriate method calls without throwing an error or crashing. However, my program does not display the entries from Table_User_List in the "YourListFrag.java" class. I don't know if their is a problem copying the row from one sqlite table to the other, displaying and refershing the name column in the fragment or inflating the fragment into "DisplayAllWorkouts.java" class. I have been struggling with this problem for awhile now and I finally decided to reach out to the community that has always been there for me. I have referenced the following sqlite copy data from one table to another
and i can't tell if this approach actually works in my program because nothing is displayed in the fragment. Thank you for your time and effort. I apologize for the lines of code i commented out and posted. I have been trying everything i could think of.
I'm trying to access a Content Provider I already made (which I made by very closely following a tutorial, I've tested it with the code the tutorial walked me through and it works fine) and read the email addresses that I've added into a SQLite database. In the database is the ID, a COLUMN_NAME, and a COLUMN_EMAIL. I want to get all the rows for the email column and have that be an ArrayList of strings that's returned into this activity.
So far my best guess is that somewhere somehow I'll query the database using the query method from the content provider, return the cursor to the activity, and then collect all the Strings from the rows and either manage to send a query with a projection for just that column or filter out all the #lorem.com's or second index of the cursor or some kind of post data retrieval filter.
Basically I'm just pretty stuck.
Okay so here's my code:
public class EmailScheduler extends AppCompatActivity implements LoaderManager
.LoaderCallbacks<Cursor> {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_email_scheduler);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final TextView emailText = (TextView) findViewById(R.id.emailText);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Cursor cursor = getContacts();
Log.i("TAG", cursor.getColumnName(2));
emailText.append(cursor.toString());
}
});
}
private static final int CONTACT_LOADER = 0;
public Uri contactUri;
ArrayList<String> addresses = new ArrayList<>();
Cursor cursor;
private Cursor getContacts() {
// Run query
Uri uri = Contact.CONTENT_URI;
String[] projection = new String[] { Contact._ID,
Contact.COLUMN_NAME };
String selection = Contact.COLUMN_EMAIL + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = Contact.COLUMN_NAME
+ " COLLATE LOCALIZED ASC";
return getContentResolver().query(uri, projection, selection, selectionArgs,
sortOrder);
}
// called by LoaderManager to create a Loader
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoader cursorLoader;
switch (id) {
case CONTACT_LOADER:
cursorLoader = new CursorLoader(this,
contactUri, // Uri of contact to display
null, // null projection returns all columns
null, // null selection returns all rows
null, // no selection arguments
null); // sort order
break;
default:
cursorLoader = null;
break;
}
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Log.i("TAG", "got to the beginning of onloadfinish " + data);
if (data != null && data.moveToFirst()) {
int nameIndex = data.getColumnIndex(Contact.COLUMN_NAME);
int emailIndex = data.getColumnIndex(Contact.COLUMN_EMAIL);
String address = data.getString(emailIndex);
Log.i("TAG", address);
while (data.getString(emailIndex) != null){
addresses.add(cursor.getString(cursor.getColumnIndex(
Contact.COLUMN_EMAIL)));
Log.i("TAG", addresses.toString());}
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) { }
}
In the onCreate method it returns this data when I run it: android.content.ContentResolver$CursorWrapperInner#60c9bd2
How do I get the information I need from that? Everything I try turns into a dead end.
private void getContacts() {
List<String> addresses = new ArrayList<String>();
// Run query
Uri uri = Contact.CONTENT_URI;
String[] projection = new String[] { Contact.COLUMN_EMAIL };
String selection = null;
String[] selectionArgs = null;
String sortOrder = Contact.COLUMN_EMAIL
+ " COLLATE LOCALIZED ASC";
Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs,
sortOrder);
TextView emailText = (TextView) findViewById(R.id.emailText);
if (cursor != null) {
cursor.moveToFirst();
String category;
for (int i = 0; i < cursor.getCount(); i++){
category = cursor.getString(cursor
.getColumnIndexOrThrow(Contact.COLUMN_EMAIL));
addresses.add(category);
cursor.moveToNext();
}
// always close the cursor
cursor.close();
}
}
I've tried to make a gallery out of the Videos created with my app.
When I click on one of the Thumbnail pictures I want to save the selected Video in my preferences.
To get the Thumbnails I wrote following code:
public void addVidsToArray()
{
String[] projection = { MediaStore.Video.Media._ID };
String selection = MEDIA_DATA + " like ? ";
String [] selectionArgs = new String[] {"%Bla%"};
int columIndex;
int id;
Cursor videoCursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
selectionArgs,
null);
videoCursor.moveToFirst();
if(videoCursor.getCount() >= 1)
{
while (videoCursor.moveToNext()) {
columIndex = videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID) ;
id = videoCursor.getInt(columIndex);
bitmaps.add(getThumbnail(id));
}
}
}
public Bitmap getThumbnail(int id)
{
ContentResolver crThumb = getContentResolver();
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(crThumb, id, MediaStore.Video.Thumbnails.MICRO_KIND, options);
curThumb = Bitmap.createScaledBitmap(curThumb, 300, 300, false);
return curThumb;
}
I get the Tumbnail Pics due to the Uri id.
Now my Problem is how to bring that back to a normal path in a new File to saved it.
Following code is the the onClickListener which should save the video to the preferences.
But if I add the Uri to the new File, the file doesen't exsist.
I don't get it.
ga.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id)
{
String[] projection = { MediaStore.Video.Media._ID };
String selection = MEDIA_DATA + " like ? ";
String [] selectionArgs = new String[] {"%Bla%"};
int columIndex;
int id1;
Cursor videoCursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
selectionArgs,
null);
videoCursor.moveToFirst();
if(videoCursor.getCount() >= 1)
{
while (videoCursor.moveToNext()) {
columIndex = videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID) ;
id1 = videoCursor.getInt(columIndex);
daten.add(id1+"");
}
}
Log.v("vid id", ""+daten.get(position));
int idData = Integer.parseInt(daten.get(position));
saveVideo(idData);
}
});
}
public void saveVideo(int idData)
{
String uriString = "content://media/external/video/media/" + idData;
Uri uri = Uri.parse(uriString);
File mVideoFile = new File(uriString);
Log.v("testpfad", ""+ mVideoFile.getAbsolutePath() + " " + mVideoFile.getParentFile().getAbsolutePath() + " " + mVideoFile.exists());
mVideoFileLen = getDurationFromURI(uri);
//setPreferences(mVideoFile.getAbsolutePath(), PICKED_VIDEO);
//setPreferences(mVideoFileLen, VIDEO_LEN);
//startActivity(new Intent(this, Finished.class));
}
In the end I need to create a File with the help of the Id from the Uri.
I have about 4k rows in sqlite table, table has 7 columns.
I created working ListView with my own CursorAdapter.
Query is like this SELECT * FROM [table] ORDER BY [column] DESC;
Table has first column _id INTEGER PRIMARY KEY but ordering is done by another column.
For opening db using my own subclass of SQLiteOpenHelper
Creating cursor
mySQLiteOpenHelper pm = new mySQLiteOpenHelper();
SQLiteDatabase db = pm.getReadableDatabase();
Cursor c = db.query([tablename], new String[]{"_id", "[column]", "[column]", "[column]", "[column]", "[column]"}, null, null, null, null, "name ASC");
Passing it to ListView
ListView lv = (ListView) findViewById(R.id.list_items);
lv.setOnItemClickListener(this);
pa = new ItemsAdapter(ItemsActivity.this, c);
In ItemsAdapter I have reimplemented
private LayoutInflater inflater;
#Override
public View newView(Context arg0, Cursor arg1, ViewGroup arg2) {
return inflater.inflate(R.layout.items_row, arg2,false);
}
and
#Override
public void bindView(View rtn, Context arg1, Cursor c) {
item_name = (TextView) rtn.findViewById(R.id.item_name);
item_description = (TextView) rtn.findViewById(R.id.item_description);
item_catalog_id = (TextView) rtn.findViewById(R.id.item_catalog_id);
item_true_price = (TextView) rtn.findViewById(R.id.item_true_price);
item_display_price = (TextView) rtn.findViewById(R.id.item_display_price);
item_button = (Button) rtn.findViewById(R.id.item_button);
item = new MyWrapClass(c);
// some work with item to fill up all UI items
}
MyWrapClass
public final class MyWrapClass {
public String name = "";
public String notes = "";
public int id = 0;
public String catalogId = "";
public int price = 0;
public int publicPrice = 0;
public String groupPrice = "";
public int order_count = 0;
public MyWrapClass(Cursor c) {
try {
id = c.getInt(0);
catalogId = c.getString(1);
name = c.getString(2);
price = c.getInt(3);
publicPrice = c.getInt(4);
groupPrice = c.getString(5);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
The same row init code was used in ListView and there it worked very good.
So if you can say from this code, is there ANY reason, why should load of 6 row items (one screen height) and scroll refresh (mean when you scroll one item down) take up to 1 minute?
Just load of ListView takes up to 2 minutes, and then about half time to scroll one list item down/up. Where can be the performance issue?
I'd create a custom Adapter, that only loads whatever is needed for the active views and that reuses views in the getView() method. It's really quite simple.
Update
I found an excellent example, that you should be able to use:
http://android.amberfog.com/?p=296