I wish to send data from a fragment to an activity but my present code doesn't work.
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent();
Context ctx = getActivity();
DBoperations db = new DBoperations(ctx);
Cursor cr = db.getInfo(db);
cr.moveToFirst();
long count = id;
while( count > 0){
cr.moveToNext();
count --;
}
String ID = Integer.toString(cr.getInt(0));
String Name = cr.getString(1);
intent.putExtra("extra",ID + " " + Name);
startActivity(getActivity(),LocationInfo.class);
}
This function is inside a class that extends Fragment.
Here the entire last line startActivity(...) is underlined in red and says:
startActivity(android.content.intent, android.os.Bundle) in Fragment
cannot be applied to
(android.support.v4.app.FragmentActivity,java.lang.Class)
So how to I pass data from fragment to an activity?
I didn't write
startActivity(new Intent(getActivity(),LocationInfo.class));
That was the only issue...
Try this:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getActivity(), LocationInfo.class);
Context ctx = getActivity();
DBoperations db = new DBoperations(ctx);
Cursor cr = db.getInfo(db);
cr.moveToFirst();
long count = id;
while( count > 0){
cr.moveToNext();
count --;
}
String ID = Integer.toString(cr.getInt(0));
String Name = cr.getString(1);
intent.putExtra("extra",ID + " " + Name);
startActivity(intent);
}
Related
I have to find "id" in database and I try this way but I can't solve it. Could you help me. Thanks a lot.
listview.setOnItemClickListener(new AdapterView.XouOnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String text = (String) listview.getItemAtPosition(arg2);
Database db = new Database(getApplicationContext());
String query = "SELECT name, id FROM tableDB WHERE name = '" + text + "'"; // I think problem is here
Cursor cursor = db.rawQuery(query, null);
cursor.moveToFirst();
id_position = cursor.getInt(cursor.getColumnIndex("id"));
go_detail();
}
});
// this part is OK
private void go_detail(){
Intent intent = new Intent(getApplicationContext(), Detail_page.class);
intent.putExtra("id", (int) name_ids[id_position]);
startActivity(intent);
}
I think error is in your go_detail function. try adding a parameter, such as go_detail(int id_position){....} right now, it cant get the id without parameter
I'm trying to pass the ListView position via intent and not the id. Is there anyway of doing this. When I delete an item, i want to pass the changed position. Currently, both the position and id are the same.
If there's a better way (i.e. if statement in 2nd view), please explain.
public class MyCollection extends Activity {
private ListView listView;
List<MyMovieDataModel> movieList;
MyDatabase database;
MyMovieAdapter myMovieAdapter;
private static final String TAG = "popularmovies";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_collection_main);
database = new MyDatabase(this);
movieList = database.getAllItems();
myMovieAdapter = new MyMovieAdapter(this, R.layout.my_collection_row, movieList);
listView = (ListView) findViewById(R.id.myCollection_listView);
listView.setAdapter(myMovieAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MyCollection.this, MyDetailView.class);
intent.putExtra("movie", position);
Log.d(TAG, "Intent position: " + position);
Log.d(TAG, "Intent id: " + id);
startActivity(intent);
}
});
clickToDetail();
}
public void clickToDetail() {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MyCollection.this, MyDetailView.class);
intent.putExtra("movie", position);
Log.d(TAG, "Intent position: " + position);
Log.d(TAG, "Intent id: " + id);
startActivity(intent);
}
});
}
This is from 2nd view:
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
mPosition = bundle.getInt("movie");
Log.d(TAG, "Bundle mPosition: " + mPosition);
}
moviePosition = (int) (mPosition + 1);
Log.d(TAG, "Bundle moviePosition: " + moviePosition);
MyDatabase myDatabase = new MyDatabase(this);
database = myDatabase.getWritableDatabase();
String selectQuery = "SELECT * FROM " + MyDatabase.DATABASE_TABLE + " WHERE _id = " + moviePosition;
Log.d(TAG, "SQL Query Position: " + moviePosition);
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor != null && cursor.moveToFirst()) {
do {
idList.add(cursor.getInt(0));
list.add(cursor.getString(1));
list.add(cursor.getString(2));
list.add(cursor.getString(3));
list.add(cursor.getString(4));
//list.add(cursor.getString(5));
} while (cursor.moveToNext());
}
cursor.moveToFirst();
//Link & Set Detail Views//
detailID = (TextView) findViewById(R.id.detailID);
detailID.setText(cursor.getString(0));
detailTitle = (TextView) findViewById(R.id.detailTitle);
detailTitle.setText(cursor.getString(1));
detailDate = (TextView) findViewById(R.id.detailDate);
detailDate.setText(cursor.getString(2));
detailRating = (TextView) findViewById(R.id.detailRating);
detailRating.setText(cursor.getString(3));
detailSynopsis = (TextView) findViewById(R.id.detailSynopsis);
detailSynopsis.setText(cursor.getString(4));
//detailPoster = (ImageView) findViewById(R.id.detailPoster);
}
I'm guessing you are correctly passing item's position through intent; all you need to do is in your MyDetailView, call
getIntent().getIntExtra("movie", 0);
where "movie" has to be the same String value as you specified when putting extra into intent, and 0 is the default value that will be passed if there is no value associated with the key(in this case "movie"). Then you can receive correct item's position.
I want to open new activity which will display instructions from the position id of my listview.
This is my helper
public List<step_con> getSteps(){
List<step_con> steplist = new ArrayList<step_con>();
String query = "SELECT s1,s1_img,s2,s2_img,s3,s3_img,s4,s4_img,s5,s5_img,s6,s6_img, FROM step_software WHERE _id = "+ id;
Cursor cur = database.rawQuery(query, null);
if (cur.moveToFirst()) {
do {
step_con steps = new step_con();
steps.setS(cur.getString(0));
steps.setImage(cur.getBlob(1));
steps.setS2(cur.getString(2));
steps.setImage2(cur.getBlob(3));
steps.setS3(cur.getString(4));
steps.setImage3(cur.getBlob(5));
steps.setS4(cur.getString(6));
steps.setImage4(cur.getBlob(7));
steps.setS5(cur.getString(8));
steps.setImage5(cur.getBlob(9));
steps.setS6(cur.getString(10));
steps.setImage6(cur.getBlob(11));
} while (cur.moveToNext());
}
database.close();
return steplist;
}
The +id is the position of mylistview.
And this is my listitemclick
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myIntent = new Intent(view.getContext(),DatabaseAccess.class);
int pos = position;
String pos1 = String.valueOf(pos);
}
I'm new to android without attending class, just learning by myself. Please help what should i do or include?
I am trying to create a List for Android with a SQLite DB. While creating a new Item works without a problem, after it returns to the list activity, the Items are showed various times. Still in my DB only one new Item is inserted (as should), and when I restart the App and load the list, each Item is showed once. So here is my main activity, as I said DBHandler should be ok.
public class MainActivity extends Activity {
List<FavImages> FavImages = new ArrayList<FavImages>();
ListView favImageListView;
final Context context = this;
private SharedPreferences mPrefs;
private SharedPreferences.Editor mEditor;
//label logs
private static String logtag = "CameraApp";
//use main camera
private static int TAKE_PICTURE = 1;
private Uri imageUri;
public Uri imagePath = Uri.parse("android.resource://com.adrian/drawable/no_picture.png");
DataBaseHandler dbHandler;
int longClickedItemIndex;
ArrayAdapter<FavImages> favImagesAdapter;
private static final int EDIT = 0, DELETE = 1;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
favImageListView = (ListView) findViewById(R.id.listView);
dbHandler = new DataBaseHandler(getApplicationContext());
mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
mEditor = mPrefs.edit();
//enter an Item
registerForContextMenu(favImageListView);
//maybe without long
favImageListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//position of Item
longClickedItemIndex = position;
return false;
}
});
populateList();
//Button Action
Button cameraButton = (Button)findViewById(R.id.button_camera);
cameraButton.setOnClickListener(cameraListener);
}
private OnClickListener cameraListener = new OnClickListener(){
public void onClick(View v){
takePhoto(v);
}
};
//launch native camera app
private void takePhoto(View v){
final Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
//save Image and create file
// in Progress
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.text_entry, null);
final EditText input1 = (EditText) textEntryView.findViewById(R.id.pictureName);
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
//create Dialog
alert
.setTitle("Bitte bennenen Sie Ihr Bild!")
.setView(textEntryView)
.setPositiveButton(R.string.alert_dialog_ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.i("AlertDialog","TextEntry 1 Entered "+input1.getText().toString());
/* User clicked OK so do some stuff */
String inputText = input1.getText().toString();
mEditor.putString("pictureName", inputText);
mEditor.commit();
File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), replaceChars(mPrefs.getString("pictureName", "picture")) + ".jpg");
//access information of file
imageUri = Uri.fromFile(photo);
//save image path information
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//for favImages
imagePath = imageUri;
mEditor.putString("picturePath", imagePath.toString());
mEditor.commit();
//
startActivityForResult(intent, TAKE_PICTURE);
//
Log.e("Dateipfad", imagePath.toString());
FavImages favImages = new FavImages(dbHandler.getFavCount(), mPrefs.getString("pictureName", "Bild"), imagePath);
dbHandler.createFav(favImages);
FavImages.add(favImages);
//favImagesAdapter.notifyDataSetChanged();
populateList();
List<FavImages> addableFavs = dbHandler.getAllFav();
int favCount = dbHandler.getFavCount();
for(int i = 0; i < favCount; i++){
FavImages.add(addableFavs.get(i));
}
if (!addableFavs.isEmpty())
populateList();
}
});
//show Dialog
alert.show();
}
public String replaceChars (String inputText){
inputText = inputText.replace("ä","ae");
inputText = inputText.replace("ö","oe");
inputText = inputText.replace("ü","ue");
inputText = inputText.replace("ß","ss");
return inputText;
}
//deal with output
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
//user hits ok button (picture accepted)
if(resultCode == Activity.RESULT_OK){
Uri selectedImage = imageUri;
//communication between apps
getContentResolver().notifyChange(selectedImage, null);
/*get Image
ImageView imageView = (ImageView)findViewById(R.id.image_camera);
//hold Image data
ContentResolver cr = getContentResolver();
Bitmap bitmap;
//get bitmap data
try {
bitmap = MediaStore.Images.Media.getBitmap(cr, selectedImage);
//set Image
imageView.setImageBitmap(bitmap);
//notify user of success
Toast.makeText(MainActivity.this, selectedImage.toString(), Toast.LENGTH_LONG).show();
}catch (Exception e){ //catch exceptions along the way
Log.e(logtag, e.toString());
} */
}
}
//
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, view, menuInfo);
menu.setHeaderTitle("Favorit bearbeiten");
menu.add(Menu.NONE, DELETE, menu.NONE, "Favorit löschen");
}
public boolean onContextItemSelected (MenuItem item){
switch (item.getItemId()){
case EDIT:
//TODO: edit Favorites
break;
case DELETE:
//
dbHandler.deleteFav(FavImages.get(longClickedItemIndex));
FavImages.remove(longClickedItemIndex);
favImagesAdapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
private void populateList(){
//ArrayAdapter<FavImages> adapter = new favImagesListAdapter();
//favImageListView.setAdapter(adapter);
favImagesAdapter = new favImagesListAdapter();
favImageListView.setAdapter(favImagesAdapter);
}
//Constructor for List Items
private class favImagesListAdapter extends ArrayAdapter<FavImages>{
public favImagesListAdapter(){
super (MainActivity.this, R.layout.listview_item, FavImages);
}
#Override
public View getView (int position, View view, ViewGroup parent){
if (view == null)
view = getLayoutInflater().inflate(R.layout.listview_item, parent, false);
FavImages currentFav = FavImages.get(position);
TextView favName = (TextView) view.findViewById(R.id.favName);
favName.setText(currentFav.getImageName());
ImageView ivFavsImage = (ImageView) view.findViewById(R.id.favImage);
ivFavsImage.setImageURI(currentFav.getImagePath());
return view;
}
}
So to sum it up, what am I doing wrong, that my Items are loaded various times.
EDIT:
as requested here is my DBHandler class:
<!-- language: lang-java -->
public class DataBaseHandler extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "favoritesManager",
TABLE_FAVS = "favorites",
KEY_ID = "id",
KEY_IMGName = "name",
KEY_IMGPATH = "imagePath";
//standard DB method
public DataBaseHandler(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//standard DB method
#Override
public void onCreate(SQLiteDatabase db){
db.execSQL("CREATE TABLE " + TABLE_FAVS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_IMGName + " TEXT, " + KEY_IMGPATH + " TEXT)");
}
//standard DB method
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABL IF EXISTS" + TABLE_FAVS);
onCreate(db);
}
public void createFav(FavImages favImages){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_IMGName, favImages.getImageName());
values.put(KEY_IMGPATH, favImages.getImagePath().toString());
db.insert(TABLE_FAVS, null, values);
db.close();
}
public void deleteFav(FavImages favImages){
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_FAVS, KEY_ID + "=?", new String[]{String.valueOf(favImages.getId())});
db.close();
}
public int getFavCount(){
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_FAVS, null);
int count = cursor.getCount();
cursor.close();
db.close();
return count;
}
public List<FavImages> getAllFav(){
List<FavImages> favImages = new ArrayList<FavImages>();
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_FAVS, null);
if (cursor.moveToFirst()){
do {
favImages.add(new FavImages(Integer.parseInt(cursor.getString(0)), cursor.getString(1), Uri.parse(cursor.getString(2))));
}while (cursor.moveToNext());
}
cursor.close();
db.close();
return favImages;
}
Hi you need to use the view holder pattern see link provided below:
http://ricston.com/blog/optimising-listview-viewholder-pattern/
Ok after a fresh look on the code I found my mistake myself, I am adding multiple times the same Item to the List. Stupid mistake I know but now it works fine.
Still, thanks for your Help.
I'm showing data from a database in a list view and I want to delete one entry when the user do a longclick in one row and then selects "yes" in a Dialog. I have all the code and it compiles but it isn't deleting anything. Any suggestion? Thanks
That's the code of the listview:
public class Consult extends FragmentActivity {
private ListView list;
private SQLiteDatabase db;
private int id = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.consult);
list = (ListView)findViewById(R.id.list);
this.getIntent();
ApeironsSQLiteHelper apeironsdb = new ApeironsSQLiteHelper(this, "DBApeirons.DB", null, 1);
db = apeironsdb.getWritableDatabase();
String[] campos = new String[]{"_id", "name", "kind_place", "score"};
Cursor c = db.query("Apeirons", campos, null, null, null, null, null);
c.moveToFirst();
String[] from = new String[]{"name", "kind_place", "score"};
int [] to = new int[] {R.id.Titulo, R.id.SubTitulo};
//#SuppressWarnings("deprecation")
MyListAdapter myadapter = new MyListAdapter (this,
R.layout.entrys, c, from, to);
list.setAdapter(myadapter);
list.setLongClickable(true);
list.setOnItemLongClickListener(new OnItemLongClickListener(){
public boolean onItemLongClick(AdapterView<?> arg0, View v,
int index, long arg3) {
saveID(index);
//db.delete("Apeirons", "_id=" + String.valueOf(index), null);
Log.d("ONCLICK", String.valueOf(index));
Log.d("ONCLICK", String.valueOf(id));
callDialog();
return false;
}
});
}
public void callDialog(){
Log.d("DIALOG", String.valueOf(id));
FragmentManager fragmentmanager = getSupportFragmentManager();
SimpleDialog dialog = new SimpleDialog();
dialog.saveIndex(id);
//SimpleDialog.newInstance(id);
dialog.show(fragmentmanager, "tag");
Log.d("erase", "salgo del callDialog");
}
public void saveID(int ID){
id = ID;
}
And that's the code of the Dialog:
public class SimpleDialog extends DialogFragment {
private SQLiteDatabase dbs;
int ID;
#Override
public Dialog onCreateDialog (Bundle savedInstanceState){
//ID = getArguments().getInt("id");
ApeironsSQLiteHelper apeironsdbs = new ApeironsSQLiteHelper(getActivity(),
"DBApeirons.DB", null, 1);
dbs = apeironsdbs.getWritableDatabase();
AlertDialog.Builder builder =
new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.EraseDialogMessage);
builder.setTitle(R.string.app_name);
builder.setPositiveButton(R.string.EraseDialogPButton, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String args = String.valueOf(ID);
Log.d("Yes BUTTON", args);
/*String sql = "DELETE FROM Apeirons WHERE _id=" + args;
dbs.execSQL(sql);*/
//int prueba = dbs.delete("Apeirons", " _id = ?" + args, null);
int prueba = dbs.delete("Apeirons", "_id = ?", new String[] { "" + args });
Log.d("RETORNO DELETE", String.valueOf(prueba));
}
});
builder.setNegativeButton(R.string.EraseDialogNButton, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
return builder.create();
}
public void saveIndex(int index){
ID = index;
}
}
I fixed!!! The problem was that I was using the id of the listview and it isn't the same in the database. Now I recover first the _id of the database and works perfect. Thank you for all the answers. The code to recover the _id of database below (maybe is useful to someone):
list.setLongClickable(true);
list.setOnItemLongClickListener(new OnItemLongClickListener(){
public boolean onItemLongClick(AdapterView<?> arg0, View v,
int index, long arg3) {
c.moveToPosition(index);
int id = c.getInt(c.getColumnIndex("_id"));
saveID(id);
Log.d("ONCLICK", String.valueOf(index));
Log.d("ONCLICK", String.valueOf(id));
callDialog();
return false;
}
});
You can try
private SQLiteDatabase dbs;
String args = String.valueOf(ID);
Delete query:
Method 1:
dbs = apeironsdbs.getWritableDatabase();
String deleteQuery = "DELETE FROM Apeirons where _id='"+ args +"'";
dbs .execSQL(deleteQuery);
Or you can use
Method 2:
ApeironsSQLiteHelper apeironsdb = new ApeironsSQLiteHelper(this, "DBApeirons.DB", null, 1);
apeironsdb .delete(Apeirons, _id+"="+ID, null); // ID is int value
Try change this line:
int prueba = dbs.delete("Apeirons", " _id = ?" + args, null);
into
int prueba = dbs.delete("Apeirons", " _id = \"" + args + "\"", null);