Can't seem to find a solution to this. I'm trying to edit the data in my List View item. The List View uses an array adapter to display the data in a row in the list view.
The user holds their finger over the list view item they wish to edit which causes a box to pop up containing the option of either 'Delete' or 'Edit'. When the user clicks to Edit the data, the data from that list view item is supposed to be transferred over to the other activity where the user can edit it. Instead of transferring the data that I want to edit, the data from the last item in the List View is transferred.
This is the code below.
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int position = info.position;
switch (item.getItemId()) {
case R.id.edit:
{
itemCheck = true;
String bCheck = String.valueOf(itemCheck);
iTitle = paymentTitle.get(position).toString();
iPaymentDate = paymentDate.get(position).toString();
iReminderDate = reminderDate.get(position).toString();
iReminderTime = reminderTime.get(position).toString();
iAmount = paymentVal.get(position).toString();
if(iReminderDate == "No Date Set")
{
iReminderDate = "";
}
else
{
Intent reminder = new Intent(this, MyBroadcastReceiver.class);
PendingIntent.getBroadcast(this.getApplicationContext(), 1, reminder,
PendingIntent.FLAG_UPDATE_CURRENT).cancel();
}
if(iReminderTime == "No Time Set")
{
iReminderTime = "";
}
Intent intent = new Intent(Payments.this, AddPayment.class);
intent.putExtra("PID", pID);
intent.putExtra("ITITLE", pTitle);
intent.putExtra("PAYMENTDAY", pDay);
intent.putExtra("PAYMENTMONTH", pMonth);
intent.putExtra("PAYMENTYEAR", pYear);
intent.putExtra("REMINDERDAY", rDay);
intent.putExtra("REMINDERMONTH", rMonth);
intent.putExtra("REMINDERYEAR", rYear);
intent.putExtra("REMINDERHOUR", rHour);
intent.putExtra("REMINDERMIN", rMin);
intent.putExtra("IAMOUNT", pValue);
intent.putExtra("ITEMCHECK", itemCheck);
startActivity(intent);
finish();
}
return true;
This is the data from my database
C = readableDB.query("PaymentTable", new String[] { "_ID", "PTITLE", "PA", "PDAY", "PMONTH", "PYEAR", "RDAY", "RMONTH",
"RYEAR", "RMIN", "RHOUR", "DATE"}, null, null, null, null, "DATE ASC");
This is how the variables is created using the data imported from the Database.
paymentID = C.getInt(C.getColumnIndex("_ID"));
pTitle = C.getString(C.getColumnIndex("PTITLE"));
pDay = C.getString(C.getColumnIndex("PDAY"));
pMonth = C.getString(C.getColumnIndex("PMONTH"));
pYear = C.getString(C.getColumnIndex("PYEAR"));
rDay = C.getString(C.getColumnIndex("RDAY"));
rMonth = C.getString(C.getColumnIndex("RMONTH"));
rYear = C.getString(C.getColumnIndex("RYEAR"));
rHour = C.getString(C.getColumnIndex("RHOUR"));
rMin = C.getString(C.getColumnIndex("RMIN"));
pValue = C.getString(C.getColumnIndex("PA"));
pID = paymentID.toString();
This is how the array list items are made which are used to display the data in my list view.
reminderDateStr = rDay + "/" + rMonth + "/" + rYear;
reminderTimeStr = rHour + ":" + rMin;
paymentDateStr = pDay + "/" + pMonth + "/" + pYear;
paymentTitleStr = pTitle;
paymentValue = "£" + pValue;
paymentTitle.add(paymentTitleStr);
reminderTime.add(reminderTimeStr);
paymentDate.add(paymentDateStr);
reminderDate.add(reminderDateStr);
paymentVal.add(paymentValue);
Would really appreciate it if someone could tell me how to get this working or at least tell me where I've went wrong and what I should try instead. Thanks to anyone who tries to help me with this.
Instead of using onContextItemSelected to open the new activity, I think you can use OnItemClickListener for that. You can declare it this ways:
yourListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
ListView lv = (ListView)parent;
#SuppressWarnings("unchecked")
ArrayAdapter<YourObject> adapter = ArrayAdapter<YourObject>)
lv.getAdapter();
YourObjectitem = adapter.getItem(position);
// The rest of the code goes here
}
});
Related
I'm using listView and in every line I have a button. I'm using OnClick and not a listener.
When I press the button I need to update the database. How can I know what is the ID?
here is my code:
public void saleButtonClick(View v) {
int quantity = 0;
TextView mQuantityTextView = (TextView) findViewById(R.id.main_quantity);
quantity = Integer.parseInt(mQuantityTextView.getText().toString());
if (quantity > 0){
quantity --;
Uri updateUri = ContentUris.withAppendedId(BookEntry.CONTENT_URI, v.getId());
ContentValues values = new ContentValues();
values.put(BookEntry.COLUMN_BOOK_QUANTITY, quantity);
int rowsUpdated = getContentResolver().update(
updateUri,
values,
null,
null);
if (rowsUpdated == 1) {
Toast.makeText(this, R.string.sellable, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.not_sellable, Toast.LENGTH_SHORT).show();
}
} else {
// Out of stock
Toast.makeText(this, R.string.out_of_stock, Toast.LENGTH_LONG).show();
}
mQuantityTextView.setText(Integer.toString(quantity));
}
If you use ListView with CursorAdapter (+ContentProvider) then you should add onClickListener in your CursorAdapter. In this case all of your List Items will have the SaleButton connected to your product (with it's unique id).
Try this code in your Adapter:
Button saleButton = view.findViewById(R.id.sale_button);
saleButton.setOnClickListener(v -> {
sellItem(_id, productQuantity);
});
/**
* helper method for sell a product
* #param id - id of product
* #param productQuantity - original quantity which must decreased by one
*/
private void sellItem(long id, int productQuantity) {
int newQuantity = --productQuantity;
// check that new quantity is greater than 0. In this case we update product
if (newQuantity > 0) {
ContentValues sellItem = new ContentValues();
sellItem.put(BookEntry.COLUMN_BOOK_QUANTITY, quantity);
int result= mContext.getContentResolver().update(ContentUris.withAppendedId(BookEntry.CONTENT_URI,id),sellItem,null,null);
if(result==1){
// rest of your code
}
}
}
Hope it helps.
I had a very similar project, take a look at: https://github.com/csongi77/InventoryApp
Best regards!
what im trying to do is look at the json pull all the names to a list view(save the imdbid of that names) and from there you can click on a movie and it will go to a new intent that will bring you the movie that you clicked on with its name summary and an image
im searching in a json with an array in it that looks like this(it based on what the user searched so this is one example...)
{"Search":[{"Title":"Batman Begins","Year":"2005","imdbID":"tt0372784","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg"},{"Title":"Batman v Superman: Dawn of Justice","Year":"2016","imdbID":"tt2975590","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BNTE5NzU3MTYzOF5BMl5BanBnXkFtZTgwNTM5NjQxODE#._V1_SX300.jpg"},{"Title":"Batman","Year":"1989","imdbID":"tt0096895","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BMTYwNjAyODIyMF5BMl5BanBnXkFtZTYwNDMwMDk2._V1_SX300.jpg"},{"Title":"Batman Returns","Year":"1992","imdbID":"tt0103776","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BODM2OTc0Njg2OF5BMl5BanBnXkFtZTgwMDA4NjQxMTE#._V1_SX300.jpg"},{"Title":"Batman Forever","Year":"1995","imdbID":"tt0112462","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BNWY3M2I0YzItNzA1ZS00MzE3LThlYTEtMTg2YjNiOTYzODQ1XkEyXkFqcGdeQXVyMTQxNzMzNDI#._V1_SX300.jpg"},{"Title":"Batman & Robin","Year":"1997","imdbID":"tt0118688","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BNTM1NTIyNjkwM15BMl5BanBnXkFtZTcwODkxOTQxMQ##._V1_SX300.jpg"},{"Title":"Batman: The Animated Series","Year":"1992–1995","imdbID":"tt0103359","Type":"series","Poster":"http://ia.media-imdb.com/images/M/MV5BMTU3MjcwNzY3NF5BMl5BanBnXkFtZTYwNzA2MTI5._V1_SX300.jpg"},{"Title":"Batman: Under the Red Hood","Year":"2010","imdbID":"tt1569923","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BMTMwNDEyMjExOF5BMl5BanBnXkFtZTcwMzU4MDU0Mw##._V1_SX300.jpg"},{"Title":"Batman: The Dark Knight Returns, Part 1","Year":"2012","imdbID":"tt2313197","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BMzIxMDkxNDM2M15BMl5BanBnXkFtZTcwMDA5ODY1OQ##._V1_SX300.jpg"},{"Title":"Batman: Mask of the Phantasm","Year":"1993","imdbID":"tt0106364","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BMTMzODU0NTYxN15BMl5BanBnXkFtZTcwNDUxNzUyMQ##._V1_SX300.jpg"}],"totalResults":"310","Response":"True"}
so what i want to do is get the imdbid when he clicks on the listview which contains the movie name
this is what i tried:
JSONObject jsonObject = new JSONObject(finalJson);
JSONArray parentArray = jsonObject.getJSONArray("Search");
StringBuffer finalStringBuffer = new StringBuffer();
String imdbid ;
for (int i=0; i<parentArray.length(); i++){
JSONObject finalJsonObject = parentArray.getJSONObject(i);
String movieName = finalJsonObject.getString("Title");
nameOfMovie.add(movieName);
String year = finalJsonObject.getString("Year");
yearOfMovie.add(year);
String omdbID = finalJsonObject.getString("imdbID");
id.add(omdbID);
finalStringBuffer.append(movieName + " , " + year + " , " + omdbID + "\n");
imdbid = omdbID ;
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
but how can i know the imdbid(which is in the movie name that is displayed in a list) that he cliked on?
listview code:
listViewInternetScreen.setClickable(true);
listViewInternetScreen.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long i) {
Intent intenttoEditScreen=new Intent(AddFromInternet.this, EditMovie.class);
setResult(RESULT_OK,intenttoEditScreen);
String jsonMovieName = String.valueOf(nameOfMovie);
String jsonMovieSummery = String.valueOf(yearOfMovie);
String jsonImageURL = String.valueOf(id);
intenttoEditScreen.putExtra("json", jsonMovieName);
intenttoEditScreen.putExtra("json", jsonMovieSummery);
intenttoEditScreen.putExtra("json", jsonImageURL);
startActivity(intenttoEditScreen);
}
});
and the search method:
btnGo = (Button) findViewById(R.id.btnGo);
assert btnGo != null;
btnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//MAKE A SEARCH STRING AND PARSE THE RESULT
final String search = "http://www.omdbapi.com/?s=" + EtSearch.getText().toString();
Log.e("JSON", search);
new JSONParser().execute(search);
ArrayList<String> list = new ArrayList<>(nameOfMovie);
arrayAdapter = new ArrayAdapter<>(AddFromInternet.this,
android.R.layout.simple_list_item_1, list);
arrayAdapter.notifyDataSetChanged();
listViewInternetScreen.setAdapter(arrayAdapter);
Log.e("JSON MOVIE", String.valueOf(nameOfMovie));
}
});
thanks for any help :D
Step 1: Use Gson (and Retrofit, if you'd like) to simplify turning a JSON string into a list of Java objects
Step 2: Make a custom ArrayAdapter that loads this list of objects. Then, when you add an Item click listener, you can get that object from the list item you clicked, and start the Intent for showing the full info for that movie.
Additional step would be to make the Movie object Parcelable, so you can add the object to the Intent in one line, rather than each individual field it contains
I have written a program to get some values from sqlite database and populate inside spinner ,which is working perfectly , but i want to show the selected item from the spinner into a different activity , all i am getting is either a blank value or android.database.sqlite.SQLiteCursor#3456046c , so how to convert it to string ??
Need some help
int[] to = new int[] { android.R.id.text1 };
String[] from = new String[] { DbListHelper.ACCOUNT_TYPE };
final SimpleCursorAdapter adapter4 = new SimpleCursorAdapter(
getBaseContext(), android.R.layout.simple_list_item_1, cursor,
from, to) {
public View getView(int position, View convertView, ViewGroup
parent) {
View v = super.getView(position, convertView, parent);
((TextView) v).setTextSize(18);
((TextView) v).setGravity(Gravity.CENTER);
((TextView) v).setTextColor(Color.parseColor("#1C689C"));
return v;
}
};
adapter4.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
spinnerType.setAdapter(adapter4);
On button click to save the records i am doing this , acName is the spinner variable which i am inserting , i also tried to put a dummy value inside acName as acName = "1" , which is showing properly .
btnPrint.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(cursor.moveToFirst()){
do {
acName =
cursor.getString(cursor.getColumnIndex(DbListHelper.ACCOUNT_NAME));
} while (cursor.moveToNext());
}
vehicleNo1 = editVehicleNo1.getText().toString();
driverName = editDriverName.getText().toString();
driverCode = editDriverCode.getText().toString();
dieselRate = editDieselRate.getText().toString();
dieselQty = editDieselQty.getText().toString();
amount = editAmount.getText().toString();
referenceNo = editReferenceNo.getText().toString();
noOfCopies = editNoOfCopies.getText().toString();
remark = editRemark.getText().toString();
transactionID = imeiCode + "" + dateTime;
if (spinnerData.equals("") || vehicleNo1.equals("")
|| spinnerAccountName.equals("")
|| spinnerFuelRate.equals("")
|| driverName.equals("")
|| dieselQty.equals("")
|| dieselRate.equals("")
|| amount.equals("")
|| referenceNo.equals("")) {
Toast.makeText(getBaseContext(),
"Please fill all the fields",
Toast.LENGTH_LONG).show();
}
else if (noOfCopies.equals("")) {
Toast.makeText(getBaseContext(),
"Please enter any value",
Toast.LENGTH_LONG).show();
} else {
long id = listHelper.insertPumpData(
acName, vehicleNo1,
driverName,driverCode,
dieselRate, dieselQty, amount + " Rs",
referenceNo, noOfCopies, date, time,
transactionID);
}
}
});
Thank You
Ok i myself got an answer to the above question
I did this to get the value of selected spinner item
Cursor acNameCur=(Cursor)spinnerAccountName.getSelectedItem();
String accountNamecol=acNameCur.getString(acNameCur.getColumnIndex
(DbListHelper.ACCOUNT_NAME));
Sorry for the mouthful of a title, I have to cut it down because I exceeded the 150 character limit.
I have an AutoCompleteTextView (ACTV) and I am using a SimpleCursorAdapter since the normal ACTV only searches the user input at the start of each substring (substring are separated by whitespaces) and not within those substrings. For example, having a list with Adipose and Bad Wolf and searching ad will show Adipose only and not Bad Wolf. I already made the Adapter as shown below:
//create ACTV Here
AutoCompleteTextView search = (AutoCompleteTextView) findViewById(R.id.actvCatalogueSearch);
search.setThreshold(1);
String[] from = { "name" };
int[] to = { android.R.id.text1 };
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_dropdown_item_1line, null, from, to, 0);
cursorAdapter.setStringConversionColumn(1);
FilterQueryProvider provider = new FilterQueryProvider(){
#Override
public Cursor runQuery(CharSequence constraint) {
// TODO Auto-generated method stub
String constrain = (String) constraint;
constrain = constrain.toUpperCase();
Log.d("hi", "runQuery constraint: " + constraint);
if (constraint == null) {
return null;
}
String[] columnNames = { Columns._ID, "name" };
MatrixCursor c = new MatrixCursor(columnNames);
try {
for (int i = 0; i < pdflist.length; i++) {
if(pdflist[i].contains(constrain)){
Log.d("Hello","Match! pdflist item = " + pdflist[i]);
c.newRow().add(i).add(pdflist[i]);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
};
cursorAdapter.setFilterQueryProvider(provider);
search.setAdapter(cursorAdapter);
This code enables me to show the other list items that contains the substring from the user input.
Now, I am trying to make the OnItemClickListener function properly. Here is what I have so far:
search.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
MatrixCursor matrix = (MatrixCursor)parent.getItemAtPosition(position);
Log.d("hello", "matrix values is = " + matrix);
String selection = matrix.getString(position);
Log.d("hallo","selection = " + selection);
Log.d("hello","item id at position = " + parent.getItemIdAtPosition(position));
int pos = (int) parent.getItemIdAtPosition(position);
Log.d("sup", "position is = " + pos);
String path = imagelist[pos].getAbsolutePath();
openPdfIntent(path);
}
});
Here, I am trying to get the MatrixCursor element at the given position. It works fine of the user selects the first 2 suggestions. However, when the user clicks the 3rd suggestion onwards, the application throws a CursorIndexOutOfBoundsException Requested Column: 2, # of columns: 2 Clicking on the logCat lines pointed me to the code String selection = matrix.getString(position);
I think that doing matrix.getString(position) causes the error since getString returns the value of the requested column as a String, and since there are only 2 columns, selecting a suggestion in the ACTV whose position (position as it is shown to the user, not the position of the said item in the list) is greater than 2 causes the code to screw up.
My question is, is there a better way to get the String value of the selected item given that I am using SimpleCursorAdapter? I've looked over the documentation of Matrix Cursor in the android dev site and I can't find a way to get a row/element based on the position.
Any help is very much appreciated.
Edit:
using matrix.moveToFirst(); as such did not help as well:
search.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
MatrixCursor matrix = (MatrixCursor)parent.getItemAtPosition(position);
if(matrix != null) {
if(matrix.getCount() > 0) {
matrix.moveToFirst();
String selection = matrix.getString(position);
int pos = (int) parent.getItemIdAtPosition(position);
String path = imagelist[pos].getAbsolutePath();
openPdfIntent(path);
}
}
}
});
and I still got the exception:
android.database.CursorIndexOutOfBoundsException: Requested column: 4, # of columns: 2
The requested column 4 is the position of the selected ACTV suggestion, indexed zero.
Try out like this
MatrixCursor matrix = .............
Log.d("hello", "matrix values is = " + matrix);
/***** Check here Cursor is NOT NULL *****/
if(matrix != null) {
if(matrix.getCount() > 0) {
matrix.moveToFirst();
/***
Your Stuff will be here....
**/
}
}
Made it work using a different approach. I get the View and cast it as a TextView. From there, I get the String input. I then use this string and look for its position in the original list. Note that my list is an Array, not an ArrayList, that's why I had to loop through all the items.
search.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView tv = (TextView) view;
String userSelection = tv.getText().toString();
Log.d("hello", "selection is = " + userSelection);
int pos = -1;
for (int i = 0; i < pdflist.length; i++) {
if(pdflist[i].equalsIgnoreCase(userSelection)){
pos = i;
}
}
Log.d("hello","int position = " + pos);
String path = imagelist[pos].getAbsolutePath();
openPdfIntent(path);
}
});
Is there any easier way to do this?
String[] values = new String[] { "1337", "2", "3DPD", "4", "10q",
"10x", "A C?", "AAF", "ADAD", "ADIH", "ADIP", "AEAP", "AFAICR",
"AFAICS"
};
final String[] title = new String[] { "1337", "2", "3DPD", "4", "10q",
"10x", "A C?", "AAF", "ADAD", "ADIH", "ADIP", "AEAP", "AFAICR",
"AFAICS"
};
final String[] content = new String[] {
" From the word Leet, derived from the word elite",
"too, or to",
" 3-Dimensional Pig Disgusting, denotes two dimensions are superior to reality",
"For", "Thank you", "Thanks", "AH! SI?", "As A Friend",
"Another Day Another Dollar", "Another Day In Hell",
" Another Day in Paradise", "As Early As Possible",
"As far as I can recall / remember", " As far as I can see",};
When user clicks list item I need to pass information from every array to another activity , example: User clicks item with name "1337" and now I'm taking paramteres from three arrays with position 0 ... And I have to do this for every click :
switch (itemPosition) {
case 0:
Intent intent = new Intent(DisplayMessageActivity.this, AboutSlangs.class);
intent.putExtra(TITLE, title[0]);
intent.putExtra(CONTENT, content[0]);
startActivity(intent);
break;
Any easier way?
First of all create a model like
class DataModel implements Serialiable{
private String title ;
private String value ;
private String description ;
DataModel(String ... data){
this.title = data[0] ;
this.value = data[1];
this.description = data[2] ;
}
// Generate getter setter for all
}
Now generate the arrayList like
ArrayList <DataModel> arr = new ArrayList<DataModel>();
for(int i = 0 ; i < size ; i++){
DataModel model = new DataModel("title","value","description"); //change logic according to requirement
arr.add(model);
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DataModel model = arr.get(position);
Intent intent = new Intent(DisplayMessageActivity.this, Target.class);
intent.putExtra("DATA", model);
startActivity(intent);
}
You could add another array like this:
Class<?>[] target = { ActivityA.class, ActivityB.class, ActivityC.class };
and position them appropriately to your tile/content arrays. This way you wouldn't need a switch statement at all, on onItemClick simply get the position and do:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(DisplayMessageActivity.this, target[position]);
intent.putExtra("TITLE", title[position]);
intent.putExtra("CONTENT", content[position]);
startActivity(intent);
}