Error: Target must not be null picasso - java

I am getting error: Target must not be null Picasso
public void getListFromDb(){
Cursor res = myDb.ViewAll();
startManagingCursor(res);
//Map cursor from db to viewFields
String[] fromFieldNames = new String[]{DatabaseHelper.COL_2, DatabaseHelper.COL_3, DatabaseHelper.COL_4, DatabaseHelper.COL_5};
int[] toViewIDS = new int[]{R.id.viewName, R.id.viewAddress, R.id.viewPostcode, R.id.viewType};
//Create SimpleCursorAdaptor with null cursor
SimpleCursorAdapter myCursorAdaptor = new SimpleCursorAdapter(this, R.layout.item_layout, null, fromFieldNames, toViewIDS, 0);
// Set adaptor for listView
myList.setAdapter(myCursorAdaptor);
Picasso
.with(getApplicationContext())
.load("http://www.newton.ac.uk/files/covers/968361.jpg")
.resize(600, 200) // resizes the image to these dimensions (in pixel). does not respect aspect ratio
.into(img);
new AsyncTask<SimpleCursorAdapter, Void, Cursor>() {
private SimpleCursorAdapter mSimpleCursorAdapter;
#Override
protected Cursor doInBackground(SimpleCursorAdapter... params) {
// Save cursorAdapter to use in postExecute
this.mSimpleCursorAdapter = params[0];
// Load cursor on background thread with search function
return myDb.ViewAll();
}
}
#Override
protected void onPostExecute(Cursor cursor) {
super.onPostExecute(cursor);
// and update the cursor (which is already in the listview)
this.mSimpleCursorAdapter.changeCursor(cursor);
}
}.execute(myCursorAdaptor);
}
private void registerListClickCallback() {
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long IDinDB) {
Cursor res = myDb.GetRow(IDinDB);
if (res.moveToFirst()) {
long idDB = res.getLong(DatabaseHelper.ROWID);
String message = "ID: " + idDB;
//Toast.makeText(ViewActivity.this, message, Toast.LENGTH_LONG).show();
String hello = Long.toString(idDB);
Intent intent = new Intent(ViewActivity.this, ImageFullViewActivity.class);
intent.putExtra("ImgID", hello);
startActivity(intent);
}
}
});
}
How do I solve this issue.
Also, the url of the image is just temporary as I'm using it for testing. Will I be able to insert the Real Path of the image inside .load() ?
Thanks

Related

SQLite Update not working in android

I've been trying to update my data in sqlite android, but it doesn't work. Also, there is also no error message shown in the logcat.
Here are my codes:
Dbadapter.java:
public boolean updateEntry(SalesItemInformationLV testing)
{
ContentValues values = new ContentValues();
try {
values.put(ENTRY_NAME, testing.getItemname());
values.put(ENTRY_TEL, testing.getCostprice());
values.put(ENTRY_SELLINGPRICE, testing.getSellingprice());
values.put(ENTRY_QTYSOLD, testing.getItemquantity());
values.put(ENTRY_DATESOLD, testing.getDatesold());
values.put(ENTRY_STAFFDISCOUNT, testing.getStaffdiscount());
}
catch (SQLiteException e)
{
Log.w(MYDBADAPTER_LOG_CAT, "Update failed!" + e.toString());
}
// updating row
int returnvalue = _db.update(DATABASE_TABLE, values, KEY_ID + " = ?", new String[] { String.valueOf(testing.getId()) });
return returnvalue==1 ? true : false;
}
MyItems.java:
public boolean updateDatabase(SalesItemInformationLV testing2, Context c)
{
MyDbAdapter db = new MyDbAdapter(c);
db.open();
boolean rowIDofUpdatedEntry = db.updateEntry(testing2);
db.close();
return rowIDofUpdatedEntry;
}
ListView.java, which passes saleitem2 object intent to Edit.java:
MyItems mi2;
private ArrayList<SalesItemInformationLV> displayiteminfo2;
mi2 = MyItems.getInstance();
displayiteminfo2 = mi2.retrieveAllForlist2(getApplicationContext());
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SalesItemInformationLV saleitem2 = displayiteminfo2.get(position);
String namevalue = saleitem2.getItemname();
Intent myintent = new Intent(ListSaleItemActivity.this, EditSaleActivity.class);
myintent.putExtra("array", saleitem2);
startActivity(myintent);
Edit.java which will use the update method from Items.java:
Bundle extras = this.getIntent().getExtras();
final SalesItemInformationLV sale1 = (SalesItemInformationLV)extras.getSerializable("array");
final int id1 = extras.getInt("itemID");
btnSaveChanges.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mc.updateDatabase(sale1, getApplicationContext());
}}
I have been trying to figure out, and I think there could be something wrong in my Dbadapter.java, but i am not sure. Please advise me on how to solve this thanks!

How to delete ListViews items by their ID in sqlite database

I followed the tutorial here : Tutorial todo APP and I would like to customize the code nad build training app. My first change is to delete things by their ID in database ( in the example they are being deleted by names ). Here is my current code responsible for deleting items:
// FUNCTION for DELETING EXERCISE
public void deleteExercise(View view) {
final View parent = (View) view.getParent();
AlertDialog dialog = new AlertDialog.Builder(this)
.setMessage("Are you sure, you want to delete exercise?")
.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
TextView exerciseTextView = (TextView) parent.findViewById(R.id.exercise_name);
String exercise = String.valueOf(exerciseTextView.getText());
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(ExerciseContract.ExerciseEntry.TABLE,
ExerciseContract.ExerciseEntry.COL_EXERCISE_NAME + " = ?",
new String[]{exercise});
db.close();
updateUI();
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
}
// UPDATING USER INTERFACE AFTER CHANGES IN DB
private void updateUI() {
ArrayList<String> exerciseList = new ArrayList<>();
SQLiteDatabase db = mHelper.getReadableDatabase();
String[] projection = {
ExerciseContract.ExerciseEntry._ID,
ExerciseContract.ExerciseEntry.COL_EXERCISE_NAME,
//ExerciseContract.ExerciseEntry.COL_EXERCISE_DESCRIPTION
};
Cursor cursor = db.query(
ExerciseContract.ExerciseEntry.TABLE, //tablica do zapytań
projection, //zwracane kolumny
null, //columny dla WHERE
null, //wartosci dla WHERE
null,//nie grupuj wierszy
null,//nie filtruj grup
null); //porządek sortowania
while (cursor.moveToNext()) {
int idx = cursor.getColumnIndex(ExerciseContract.ExerciseEntry.COL_EXERCISE_NAME);
exerciseList.add(cursor.getString(idx));
}
if (mAdapter == null) {
mAdapter = new ArrayAdapter<>(this,
R.layout.item_workout,
R.id.exercise_name,
exerciseList);
mWorkoutListView.setAdapter(mAdapter);
} else {
mAdapter.clear();
mAdapter.addAll(exerciseList);
mAdapter.notifyDataSetChanged();
}
cursor.close();
db.close();
}
What would be the simplest way to do that?
You're not returning the id anywhere, I'd personally recommend a custom adapter. But for a quick way i think the easiest thing to do is delete it when the users click an item in the list view.
Set the lists views onItemClickListener.
mTaskListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Tasks task =(Tasks) mTaskListView.getItemAtPosition(position);
deleteTask(task.getId());
}
});
For the delete tasks pass in the _id of the clicked item.
public void deleteTask(long id) {
//TextView taskTextView = (TextView) parent.findViewById(R.id.task_title);
//String task = String.valueOf(taskTextView.getText());
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(TaskContract.TaskEntry.TABLE, TaskContract.TaskEntry._ID + " = ?", new String[]{String.valueOf(id)});
db.close();
updateUI();
}
In the UpdateUI section change this while loop to also retrieve _id.
while (cursor.moveToNext()) {
int title = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
int _id = cursor.getColumnIndex(TaskContract.TaskEntry._ID);
Tasks tasks = new Tasks();
tasks.setId(cursor.getInt(_id));
tasks.setTitle(cursor.getString(title));
taskList.add(tasks);
}
Lastly create a model for your tasks.
package com.aziflaj.todolist.db;
public class Tasks {
String title;
int id;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public String toString()
{
return getTitle();
}
}
Also remember to remove the button from the LayoutFile. You could show a dialog before deleting, but this was a quick solution. Ideally i'd recommended creating your own custom adapter. You'll probably have to do that if you wish to keep the button in and delete it that way.
Custom Adapter for List View
Create on common method inside your database helper class.
public boolean deleteRowData(String tableName, String selection, String[] selectionArgs) {
open();
sqLiteDb.delete(tableName, selection, selectionArgs);
close();
return true;
}
// ---opens the database---
public NotesData open() throws SQLException {
DatabaseHelper dbHelper = new DatabaseHelper(context);
sqLiteDb = dbHelper.getWritableDatabase();
sqLiteDb = dbHelper.getReadableDatabase();
if (!sqLiteDb.isReadOnly()) {
// Enable foreign key constraints
sqLiteDb.execSQL("PRAGMA foreign_keys = ON;");
}
return this;
}
// ---closes the database---
public void close() {
if (sqLiteDb != null && sqLiteDb.isOpen()) {
sqLiteDb.close();
}
}
Now onClick of listView Item do this:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
showDeleteAlertDialog(position); // Common method for delete alert dialog
}
});
private void showDeleteAlertDialog(int arrayPosition) {
//delete data from
String title = getResources().getString(R.string.warning);
String message = getResources().getString(R.string.warning_for_delete);
final android.app.Dialog dialog = new Dialog(YourActivity.this, R.style.DialogTheme); //this is a reference to the style above
dialog.setContentView(R.layout.custom_dialog); //I saved the xml file above as custom_dialog.xml
dialog.setCancelable(true);
//to set the message
TextView sub_message = (TextView) dialog.findViewById(R.id.tv_Message);
TextView dialogTitle = (TextView) dialog.findViewById(R.id.tv_Title);
Button btn_Negative = (Button) dialog.findViewById(R.id.btn_Negative);
Button btn_Positive = (Button) dialog.findViewById(R.id.btn_Positive);
btn_Negative.setText("Cancel");
btn_Positive.setText("Delete");
sub_message.setText("Are you sure you want to delete this>");
dialogTitle.setText(title);
//add some action to the buttons
btn_Positive.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final String selection = YourColumnName + " LIKE ?";
final String[] selectionArgs = {myArrayList.get(arrayPosition).getID()};
mHelper.deleteRowData(YourTableNAME, selection, selectionArgs);
// Now just remove that array position from your arraylist (from activity & adapter arralist too).
myArrayList.remove(arrayPosition);
yourAdapter.yourArrayList.remove(arrayPosition);
notifyDataSetChanged();
}
});
btn_Negative.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}

Display data from SQLite database into ListView in Android

Although this question has been asked many times on here, I just can't find the proper answer to fit my code. I realise it may be something small, but I just can't seem to find the problem as I'm only really new to this.
Here's my code getClientNames in DatabaseHelper class:
public Cursor getSitesByClientname(String id) {
String[] args={id};
Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
String results = "";
/*int count = myCursor.getCount();
String[] results = new String[count + 1];
int i = 0;*/
if (myCursor != null) {
if(myCursor.getCount() > 0)
{
for (myCursor.moveToFirst(); !myCursor.isAfterLast(); myCursor.moveToNext())
{
results = results + myCursor.getString(myCursor.getColumnIndex("client_sitename"));
}
}
}
return results;
}
One problem is that I'm returning a 'String' to the 'Cursor', but I'm not sure what is the best way around this, as I think I should be returning a Cursor.
Here's the ClientSites class where I want to display the data:
public class ClientSites extends Activity {
//public final static String ID_EXTRA="com.example.loginfromlocal._ID";
private DBUserAdapter dbHelper = null;
private Cursor ourCursor = null;
private Adapter adapter=null;
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.client_sites);
Intent i = getIntent();
String uID = String.valueOf(i.getIntExtra("userID", 0));
ListView myListView = (ListView)findViewById(R.id.myListView);
dbHelper = new DBUserAdapter(this);
//dbHelper.createDatabase();
dbHelper.openDataBase();
ourCursor = dbHelper.getSitesByClientname(uID);
Log.e("ALERT", uID.toString());
startManagingCursor(ourCursor);
Log.e("ERROR", "After start manage cursor: ");
//#SuppressWarnings("deprecation")
//SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null);
CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
adapter = new Adapter(ourCursor);
//Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();
myListView.setAdapter(adapter);
myListView.setOnItemClickListener(onListClick);
}
catch (Exception e)
{
Log.e("ERROR", "XXERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view, int position,
long id)
{
Intent i=new Intent(ClientSites.this, InspectionPoints.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
};
class Adapter extends CursorAdapter {
#SuppressWarnings("deprecation")
Adapter(Cursor c) {
super(ClientSites.this, c);
}
//#Override
public void bindView(View row, Context ctxt,
Cursor c) {
Holder holder=(Holder)row.getTag();
holder.populateFrom(c, dbHelper);
}
#Override
public View newView(Context ctxt, Cursor c,
ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
Holder holder=new Holder(row);
row.setTag(holder);
return(row);
}
}
static class Holder {
private TextView name=null;
Holder(View row) {
name=(TextView)row.findViewById(R.id.ingredientText);
}
void populateFrom(Cursor c, DBUserAdapter r) {
name.setText(r.getName(c));
}
}
}
Here is the code I'm now using to try and display the data in the Listview. I have altered it somewhat from my original attempt, but still not sure what I'm doing wrong.
public void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.client_sites);
Intent i = getIntent();
String uID = String.valueOf(i.getIntExtra("userID", 0));
//int uID = i.getIntExtra("userID", 0);
//ListView myListView = (ListView)findViewById(R.id.myListView);
dbHelper = new DBUserAdapter(this);
dbHelper.createDatabase();
dbHelper.openDataBase();
String[] results = dbHelper.getSitesByClientname(uID);
//setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results));
//adapter = new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results);
setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.layout.client_sites, results));
//ListView myListView = (ListView)findViewById(R.id.myListView);
ListView listView = getListView();
listView.setTextFilterEnabled(true);
//ourCursor = dbHelper.getSitesByClientname(uID);
//Log.e("ALERT", uID.toString());
//startManagingCursor(ourCursor);
//Log.e("ERROR", "After start manage cursor: ");
//#SuppressWarnings("deprecation")
//SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null); // LOOK AT THIS IN THE MORNING!!!!!!!!!!!
//CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
//adapter = new Adapter(ourCursor);
//Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();
//myListView.setAdapter(adapter);
//myListView.setOnItemClickListener(onListClick);
I Created a Listview from a database. Here is the code I used for my app
Here is part of the database handler. It will return a List of Categories for my listview. It can return a list of Strings if that is what you need.
public List<Category> getAllCategorys() {
ArrayList<Category> categoryList = new ArrayList<Category>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CATEGORY;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
try{
if (cursor.moveToFirst()) {
do {
Category category = new Category();
category.setID(Integer.parseInt(cursor.getString(0)));
category.setCategory(cursor.getString(1));
// Adding category to list
categoryList.add(category);
} while (cursor.moveToNext());
}
}finally{
cursor.close();
}
db.close();
// return category list
return categoryList;
Here is how I fill the ListView by calling the database.
int size = db.getCategoryCount();
List<Category> categoryList = db.getAllCategorys();
category_data = new String[size-1];
int i=0;
for(Category cn : categoryList)
{
category_data[i] = cn.getCategory(); // get the name of the category and add it to array
i++;
}
listAdapter = new ArrayAdapter<String>(this, R.layout.categoryrow, category_data);
listViw.setAdapter(listAdapter);
EDIT: Here is something that should work for you
public List<String> getSitesByClientname(String id) {
String[] args={id};
ArrayList<String> result = new ArrayList<String>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
try{
if (myCursor.moveToFirst()){
do{
result.add(myCursor.getString(myCusor.getString(myCursor.getColumnIndex("client_sitename"));
}while(myCursor.moveToNext());
}
}finally{
myCursor.close();
}
db.close();
return result;
}
Use it like this
List<String> sites_data = dbHelper.getSitesByClientname(uID);
result_data = new String[sites_data.size()];
int i=0;
for(String s : sites_data)
{
result_data[i] = s; // get the name of the category and add it to array
i++;
}
listAdapter = new ArrayAdapter<String>(this, R.layout.client_sites, result_data);
listViw.setAdapter(listAdapter);
If you want to return the Cursor from dbHelper you can do something like this...
public Cursor getSitesByClientname(String id) {
String[] args={id};
return db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
}
I'd also take some time to read the listview tutorial

Android ListView with SimpleCursorAdapter - CursorIndexOutOfBoundsException error

I have a ListView in AcitivityA that is populated using a custom SimpleCursorAdapter called RecipeAdapter. The adapter holds data from SQLite
There is a EditText view at the top of the ListView, that filters the listview as the user searches for a recipe. When a user clicks on a item in the filtered ListView, ActivityB starts.
This all works perfectly. However when the user presses the backbutton to resume ActivityB, I get the following error.
java.lang.RuntimeException: Unable to resume activity {ttj.android.quorn/ttj.android.quorn.RecipeActivity}:
java.lang.IllegalStateException: trying to requery an already closed cursor android.database.sqlite.SQLiteCursor#418ae5d8
To fix this problem, I modified the onResume() from:
...
c = db.getCursor();
adapter.changeCursor(c);
to
....
Cursor cursor = db.getCursor();
adapter.changeCursor(cursor);
I then get the following exception. In the Logcat, the problem arises with the getId() method in DBHelper. I have added c.moveToFirst() in this method, but this still doesn't solve the problem.
FATAL EXCEPTION: main
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 70
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:400)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at ttj.android.quorn.DBHelper.getId(DBHelper.java:224)
at ttj.android.quorn.RecipeActivity$RecipeHolder.populateFrom(RecipeActivity.java:650)
at ttj.android.quorn.RecipeActivity$RecipeAdapter.bindView(RecipeActivity.java:572)
at android.support.v4.widget.CursorAdapter.getView(CursorAdapter.java:256)
at android.widget.AbsListView.obtainView(AbsListView.java:2214)
at android.widget.ListView.makeAndAddView(ListView.java:1774)
at android.widget.ListView.fillDown(ListView.java:672)
at android.widget.ListView.fillFromTop(ListView.java:732)
at android.widget.ListView.layoutChildren(ListView.java:1611)
at android.widget.AbsListView.onLayout(AbsListView.java:2044)
at android.view.View.layout(View.java:11418)
at android.view.ViewGroup.layout(ViewGroup.java:4224)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1628)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1486)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1399)
at android.view.View.layout(View.java:11418)
at android.view.ViewGroup.layout(ViewGroup.java:4224)
at android.widget.FrameLayout.onLayout(FrameLayout.java:431)
at android.view.View.layout(View.java:11418)
at android.view.ViewGroup.layout(ViewGroup.java:4224)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1628)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1486)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1399)
at android.view.View.layout(View.java:11418)
at android.view.ViewGroup.layout(ViewGroup.java:4224)
at android.widget.FrameLayout.onLayout(FrameLayout.java:431)
at android.view.View.layout(View.java:11418)
at android.view.ViewGroup.layout(ViewGroup.java:4224)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1628)
at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2585)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4507)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
Can anyone help me with my problem?
Here is my code:
In the onCreate, the cursor populate the ListView using c.getCursor and when the user filters the ListView via the EditText, the c.getFilterCursor is used.
public class RecipeActivity extends SherlockListActivity {
private DBHelper db = null;
private Cursor c = null;
private RecipeAdapter adapter = null;
ListView listContent;
private EditText filterText = null;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.filter_list);
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
ListView listContent = getListView();
db = new DBHelper(this);
db.createDataBase();
db.openDataBase();
c = db.getCursor();
adapter = new RecipeAdapter(c);
listContent.setAdapter(adapter);
adapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
// Search for states whose names begin with the specified letters.
c = db.getFilterCursor(constraint);
return c;
}
});
startManagingCursor(c);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
db.close();
}
#SuppressWarnings("deprecation")
#Override
protected void onResume() {
super.onResume();
Cursor cursor = db.getCursor();
adapter.changeCursor(cursor);
}
#Override
protected void onPause() {
super.onPause();
adapter.notifyDataSetInvalidated();
adapter.changeCursor(null);
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
RecipeAdapter inner class
class RecipeAdapter extends CursorAdapter {
#SuppressWarnings("deprecation")
public RecipeAdapter(Cursor c) {
super(RecipeActivity.this, c);
}
public void bindView(View row, Context arg1, Cursor arg2) {
RecipeHolder holder = (RecipeHolder) row.getTag();
holder.populateFrom(c, db);
}
public View newView(Context arg0, Cursor arg1, ViewGroup arg2) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.reciperow, arg2, false);
RecipeHolder holder = new RecipeHolder(row);
row.setTag(holder);
return (row);
}
static class RecipeHolder {
public TextView id = null;
private TextView name = null;
private TextView desc = null;
private TextView preptime = null;
private TextView cooktime = null;
private TextView serves = null;
private TextView calories = null;
private TextView fat = null;
private TextView fav = null;
RecipeHolder(View row) {
id = (TextView) row.findViewById(R.id.id);
name = (TextView) row.findViewById(R.id.recipe);
desc = (TextView) row.findViewById(R.id.desc);
preptime = (TextView) row.findViewById(R.id.preptime);
cooktime = (TextView) row.findViewById(R.id.cooktime);
serves = (TextView) row.findViewById(R.id.serving);
calories = (TextView) row.findViewById(R.id.calories);
fat = (TextView) row.findViewById(R.id.fat);
fav = (TextView) row.findViewById(R.id.fav);
}
void populateFrom(Cursor c, DBHelper r) {
id.setText(r.getId(c));
name.setText(r.getRecipe(c));
name.setTextColor(Color.parseColor("#CCf27c22"));
desc.setText(r.getDesc(c));
preptime.setText(r.getPrepTime(c) + ". ");
cooktime.setText(r.getCookTime(c) + " mins");
serves.setText(r.getServes(c));
calories.setText(r.getCalories(c));
fat.setText(r.getFat(c));
fav.setText(r.getFav(c));
DBHelper class
public Cursor getCursor() {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(DATABASE_TABLE);
String[] columns = new String[] { KEY_ROWID, RECIPE, DESC, PREPTIME,
COOKTIME, SERVES, CALORIES, FAT, CATEGORY, FAV };
Cursor myCursor = queryBuilder.query(myDataBase, columns, null, null,
null, null, RECIPE + " ASC");
return myCursor;
}
public Cursor getFilterCursor(CharSequence constraint) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(DATABASE_TABLE);
String[] columns = new String[] { KEY_ROWID, RECIPE, DESC, PREPTIME,
COOKTIME, SERVES, CALORIES, FAT, CATEGORY, FAV };
if (constraint == null || constraint.length() == 0) {
// Return the full list
return queryBuilder.query(myDataBase, columns, null, null, null,
null, RECIPE + " ASC");
} else {
String value = "%" + constraint.toString() + "%";
return myDataBase.query(DATABASE_TABLE, columns, "RECIPE like ? ",
new String[] { value }, null, null, null);
}
}
public String getId(Cursor c) {
c.moveToFirst();
return (c.getString(0));
}
public String getRecipe(Cursor c) {
return (c.getString(1));
}
public String getDesc(Cursor c) {
return (c.getString(2));
}
public String getPrepTime(Cursor c) {
return (c.getString(3));
}
public String getCookTime(Cursor c) {
return (c.getString(4));
}
public String getServes(Cursor c) {
return (c.getString(5));
}
public String getCalories(Cursor c) {
return (c.getString(6));
}
public String getFat(Cursor c) {
return (c.getString(7));
}
public String getCategory(Cursor c) {
return (c.getString(8));
}
public String getFav(Cursor c) {
return (c.getString(9));
}
#SuppressWarnings("deprecation")
Bad. You should get rid of the deprecation instead of hiding that :)
startManagingCursor(c);
Don't do that. That may have caused the requery on the already closed cursor. Simply remove that line.
adapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
// Search for states whose names begin with the specified letters.
c = db.getFilterCursor(constraint);
return c;
}
});
Don't overwrite your c here. Just return db.getFilterCursor(constraint); is what this should do.
Other things that may have a positive effect
#SuppressWarnings("deprecation")
public RecipeAdapter(Cursor c) {
super(RecipeActivity.this, c);
}
public RecipeAdapter(Cursor c) {
// no requeries and no observer required if you change the cursor yourself
super(RecipeActivity.this, c, 0)
}
Next one:
adapter.notifyDataSetInvalidated();
adapter.changeCursor(null);
// change to
adapter.changeCursor(null);
adapter.notifyDataSetChanged(); // maybe without this
As far as I understand the documentation notifyDataSetInvalidated() means that the data can't be valid afterwards ("Once invoked this adapter is no longer valid and should not report further data set changes.") and you need to create a new Adapter instance. Not sure though. Just doing notifyDataSetChanged() works fine. It might even be the case that doing adapter.changeCursor() will already implicitly do the change notification.
P.S.: c.MoveToFirst() is not required. The CursorAdapter will move the cursor to the required position.
You renamed your variable, as indicated here
....
Cursor cursor = db.getCursor();
adapter.changeCursor(cursor);
correct? But right after that you specify that you tried
c.moveToFirst()
So maybe you should set
c = cursor;
So that the rest of your code works?

how to play video in same page(media player)

hi i have create one simple media player.... now its working fine. i retrieve video thumbnails in gallery. when i click the thumbnails video will play in other page... if i click thumbnails video play same page...see my screen shot....my video play in that red box...this type of frame how to create.....
this is my screen shot:
if i click thumbnails the video will play another page:
that screen shot:
this is for my coding:
public class videothumb extends Activity
{
private final static Uri MEDIA_EXTERNAL_CONTENT_URI =
MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
private final static String _ID = MediaStore.Video.Media._ID;
private final static String MEDIA_DATA = MediaStore.Video.Media.DATA;
//flag for which one is used for images selection
private Gallery _gallery;
private Cursor _cursor;
private int _columnIndex;
private int[] _videosId;
private Uri _contentUri;
private int video_column_index;
protected Context _context;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_context = getApplicationContext();
setContentView(R.layout.main);
//set GridView for gallery
_gallery = (Gallery) findViewById(R.id.videoGrdVw);
//set default as external/sdcard uri
_contentUri = MEDIA_EXTERNAL_CONTENT_URI;
//initialize the videos uri
//showToast(_contentUri.getPath());
initVideosId();
//set gallery adapter
setGalleryAdapter();
}
private void setGalleryAdapter() {
_gallery.setAdapter(new VideoGalleryAdapter(_context));
_gallery.setOnItemClickListener(videogridlistener);
}
private void initVideosId() {
try
{
//Here we set up a string array of the thumbnail ID column we want to get back
String [] proj={_ID};
// Now we create the cursor pointing to the external thumbnail store
_cursor = managedQuery(_contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int count= _cursor.getCount();
System.out.println("total"+_cursor.getCount());
// We now get the column index of the thumbnail id
_columnIndex = _cursor.getColumnIndex(_ID);
//initialize
_videosId = new int[count];
//move position to first element
_cursor.moveToFirst();
for(int i=0;i<count;i++)
{
int id = _cursor.getInt(_columnIndex);
//
_videosId[i]= id;
//
_cursor.moveToNext();
//
}
}catch(Exception ex)
{
showToast(ex.getMessage().toString());
}
}
protected void showToast(String msg)
{
Toast.makeText(_context, msg, Toast.LENGTH_LONG).show();
}
private AdapterView.OnItemClickListener videogridlistener = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
// Now we want to actually get the data location of the file
String [] proj={MEDIA_DATA};
// We request our cursor again
_cursor = managedQuery(_contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null);
//System.gc();
// video_column_index =
_cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
_columnIndex = _cursor.getColumnIndex(MEDIA_DATA);
// Lets move to the selected item in the cursor
_cursor.moveToPosition(position);
String filename = _cursor.getString(_columnIndex);
Intent intent = new Intent(videothumb.this, ViewVideo.class);
intent.putExtra("videofilename", filename);
startActivity(intent);
showToast(filename);
// Toast.makeText(videothumb.this, "" + position, Toast.LENGTH_SHORT).show();
}
};
private class VideoGalleryAdapter extends BaseAdapter
{
public VideoGalleryAdapter(Context c)
{
_context = c;
}
public int getCount()
{
return _videosId.length;
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imgVw= new ImageView(_context);
try
{
if(convertView!=null)
{
imgVw= (ImageView) convertView;
}
imgVw.setImageBitmap(getImage(_videosId[position]));
imgVw.setAdjustViewBounds(true);
imgVw.setBackgroundColor(Color.WHITE);
imgVw.setLayoutParams(new Gallery.LayoutParams(150, 100));
imgVw.setPadding(5,5,5,5);
imgVw.setScaleType(ImageView.ScaleType.FIT_XY);
}
catch(Exception ex)
{
System.out.println("StartActivity:getView()-135: ex " + ex.getClass() +",
"+ ex.getMessage());
}
return imgVw;
}
// Create the thumbnail on the fly
private Bitmap getImage(int id) {
Bitmap thumb = MediaStore.Video.Thumbnails.getThumbnail(getContentResolver(),id,
MediaStore.Video.Thumbnails.MICRO_KIND, null);
System.out.println("ff"+MediaStore.Video.Thumbnails.
getThumbnail(getContentResolver(),id, MediaStore.Video.Thumbnails.MICRO_KIND, null));
return thumb;
}
}
}
coding 2:`
public class ViewVideo extends Activity {
private String filename;
private VideoView Video;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main1);
//setContentView(new Zoom(this));
Video=(VideoView)findViewById(R.id.VideoView01);
System.gc();
Intent i = getIntent();
Bundle extras = i.getExtras();
filename = extras.getString("videofilename");
Video.setVideoPath(filename);
Video.setMediaController(new MediaController(this));
Video.requestFocus();
Video.start();
}
}
anyone help me...
You want to use Videoview
<VideoView android:id="#+id/Videoview1"
android:layout_marginTop="100px"
android:layout_marginLeft="10px"
android:layout_width="20px"
android:layout_height="200px"/>
and create object in your activity
and play.
videoview.start();
like this.
Hope this will help you
private VideoView mVView;
mVView= (VideoView) findViewById(R.id.Videoview1);
mVView.setVideoPath("sdcard/filename.mp4");
mVView.start();

Categories

Resources