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);
}
Related
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
String items={shoporder=shop1,shopname=abc,place=mmm};
I want to split the items as like (shop1).And assign to another string
String1=shop1
string2=abc
string3=mmm
// Get User records from SQLite DB
ArrayList<HashMap<String, String>> userList = controller.getAllUsers();
// If users exists in SQLite DB
if (userList.size() != 0) {
// Set the User Array list in ListView
final ListAdapter adapter = new SimpleAdapter(second.this, userList, R.layout.view_user_entry, new String[] {
"shopId", "shopOrder","date","todayTarget","targetCompleted","shopHandled_person","shopName","salesmanName" }, new int[]
{ R.id.shopId,R.id.shopOrder,R.id.date,R.id.todayTarget,R.id.targetCompleted,R.id.shopHandled_person,R.id.shopName,R.id.salesmanName});
final ListView myList = (ListView) findViewById(android.R.id.list);
myList.setAdapter(adapter);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String items=myList.getItemAtPosition(position).toString();
}
The string items contains all the list values.So i want to split the values and passed in to second activity.
The right way to initialize String array is,
String[] items=new String[]{"shopOrder=shop1","shopname=abc","place=mmm"};
simpler approach would be to use split method of String to split the string on =.
split method would break your String in two parts, one before = and second after = signs, i.e yourString.split("=")[0] <- part before = sign, yourString.split("=")[1] <- part after = sign.
for (int i =0; i<items.length; i++){
System.out.println(items[i].split("=")[1]);
}
OR
you can use yourString.indexOf("=")+1 to find every thing after = sign in your string, you can then use substring, to print everything after = signs,
substring(int beginIndex, int endIndex).
for (int i =0; i<items.length; i++){
System.out.println(items[i].substring(items[i].indexOf("=")+1, items[i].length()));
}
output in both cases
shop1
abc
mmm
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);
}
});
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
}
});
I have a little problem sending the right id to another activity as extra.I'm getting id from database which I'm sending to the new activity so I can get the right data. But the problem is that my code is sending only the last id,which is on arraylist. How can I fix that?
Here is the code I'm using :
for(cursorTitle.move(0); cursorTitle.moveToNext(); cursorTitle.isAfterLast()) {
if (vf != null) {
vf.removeAllViews();
}
text = cursorTitle.getString(cursorTitle.getColumnIndex("title"));
cardsCount = cursorTitle.getString(cursorTitle.getColumnIndex("cardsCount"));
collId = Integer.parseInt(cursorTitle.getString(cursorTitle.getColumnIndex("objectId")));
Log.i("CollID","Collection ID : "+collId);
b = BitmapFactory.decodeFile("/sdcard/7073d92dce10884554d7e047f1c51cb6.jpg", null);
array = new ArrayList<Integer>();
array.add(collId);
vf = new ViewFlipper(MyCollectionList.this);
myListView = new ListView(MyCollectionList.this);
hm = new HashMap<String, Object>();
hm.put(IMAGE, b);
hm.put(TITLE, text);
hm.put(CARDS_COUNT, cardsCount +" Stampii");
items.add(hm);
final SimpleAdapter adapter = new SimpleAdapter(MyCollectionList.this, items, R.layout.main_listview,
new String[]{TITLE, CARDS_COUNT, IMAGE}, new int[]{ R.id.main_name, R.id.main_info, R.id.main_img});
myListView.setAdapter(adapter);
myListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id)
{
Intent previewMessage = new Intent(getParent(), MyCollectionId.class);
previewMessage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
TabGroupActivity parentActivity = (TabGroupActivity)getParent();
previewMessage.putExtra("collection_id", array.get(position));
parentActivity.startChildActivity("MyCollectionId", previewMessage);
}
});
}
Thanks in advance!
You're creating a new ArrayList in each iteration and then assigning only a single value to it. I don't think that is what you intended. You should instantiate the ArrayList outside of your loop. You'll also want to move all of your other one-time initialization code (ListView, SimpleAdapter, etc.) out of the loop.
What i got is,you need to populate a listview with the records you get in cursor.You are populating your listview in each iteration of for loop and that is what causes problem.i think,following should work for you. (Required changes for varibles should be made accordingly.)
Try this:
vf = new ViewFlipper(MyCollectionList.this);
myListView = new ListView(MyCollectionList.this);
array = new ArrayList<Integer>();
hm = new HashMap<String, Object>();
for(cursorTitle.move(0); cursorTitle.moveToNext(); cursorTitle.isAfterLast()) {
if (vf != null) {
vf.removeAllViews();
}
text = cursorTitle.getString(cursorTitle.getColumnIndex("title"));
cardsCount = cursorTitle.getString(cursorTitle.getColumnIndex("cardsCount"));
collId = Integer.parseInt(cursorTitle.getString(cursorTitle.getColumnIndex("objectId")));
Log.i("CollID","Collection ID : "+collId);
b = BitmapFactory.decodeFile("/sdcard/7073d92dce10884554d7e047f1c51cb6.jpg", null);
array.add(collId);
hm.put(IMAGE, b);
hm.put(TITLE, text);
hm.put(CARDS_COUNT, cardsCount +" Stampii");
items.add(hm);
}
final SimpleAdapter adapter = new SimpleAdapter(MyCollectionList.this, items, R.layout.main_listview,
new String[]{TITLE, CARDS_COUNT, IMAGE}, new int[]{ R.id.main_name, R.id.main_info, R.id.main_img});
myListView.setAdapter(adapter);
myListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id)
{
Intent previewMessage = new Intent(getParent(), MyCollectionId.class);
previewMessage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
TabGroupActivity parentActivity = (TabGroupActivity)getParent();
previewMessage.putExtra("collection_id", array.get(position));
parentActivity.startChildActivity("MyCollectionId", previewMessage);
}
Put array = new ArrayList<Integer>(); outside of for loop.
like,
array = new ArrayList<Integer>();
for(cursorTitle.move(0); cursorTitle.moveToNext(); cursorTitle.isAfterLast()) {
{
// your stuff
array.add(collId);
// your stuff
}