Split the string in java - android

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

Related

if i have an jsonarray and i display it in listview and want a specifec item from the list how to do it?

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

Android - Using SimpleCursorAdapter in AutoCompleteTextView gives CursorIndexOutofBoundsException when user selects 3rd suggestion onwards

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);
}
});

How to get a part of a datastring from clicking a listview-item

I have a variable called current which holds the last clicked listview item data. The id of this data is to be used to query the db again for movies taht are similar.
The problem that current = id=17985, title=the matrix, year=1999 when all i need is the actual id-number. I have tried to use substring to only use the correct places of the string. This works for the matrix since its id is exactly 5 digits long, but as soon as i try to click movie with higher/lower amount of digits in its id of course it trips up.
String id = current.substring(4,9).trim().toString(); does not work for all movies.
Heres some code:
// search method: this is necessary cause this is the method thats first used and where the variable current is set. This is also the only method using three lines for getting data - id, title and year.
protected void search() {
data = new ArrayList<Map<String, String>>();
list = new ArrayList<String>();
EditText searchstring = (EditText) findViewById(R.id.searchstring);
String query = searchstring.getText().toString().replace(' ', '+');
String text;
text = searchquery(query);
try {
JSONObject res = new JSONObject(text);
JSONArray jsonArray = res.getJSONArray("movies");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
item = new HashMap<String, String>(2);
item.put("id",jsonObject.getString("id"));
item.put("title",jsonObject.getString("title"));
item.put("year", jsonObject.getString("year"));
data.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
aa = new SimpleAdapter(SearchTab.this, data,
R.layout.mylistview,
new String[] {"title", "year"},
new int[] {R.id.text1,
R.id.text2});
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(aa);
lv.setDividerHeight(5);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
Map<String, String> s = data.get((int) id);
current = s.toString();
}});
}
// similar method: this tries to build a list from the fetched data from "current"-string. As you can see i try to use 4,9 to only get right numbers, but this fails with others. Best would be to only to be ble to get the ID which I cant seem to do. The toast is just to see what is beeing fetched, much like a system out print.
protected void similar() {
data = new ArrayList<Map<String, String>>();
list = new ArrayList<String>();
String id = current.substring(4,9).trim().toString();
Toast.makeText(getApplicationContext(), id, Toast.LENGTH_SHORT).show();
String text;
text = similarquery(id);
try {
JSONObject res = new JSONObject(text);
JSONArray jsonArray = res.getJSONArray("movies");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
item = new HashMap<String, String>(2);
item.put("title",jsonObject.getString("title"));
item.put("year", jsonObject.getString("year"));
data.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
aa = new SimpleAdapter(SearchTab.this, data,
R.layout.mylistview2,
new String[] {"title", "year"},
new int[] {R.id.text1,
R.id.text2});
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(aa);
lv.setDividerHeight(5);
}
Use current.split(",")[0].split("=")[1]
edit - assuming of course that id is always the first in the comma separated list and will always be a name value pair delimited by '='
If you want to solve it via substring then you shouldn't use a predefined .substring(4,9). Use something like that:
String item = "id=17985, title=the matrix, year=1999";
String id = item.substring(item.indexOf("id=") + 3, item.indexOf(" ", item.indexOf("id=") + 3) - 1);
System.out.println("Your ID is: " + id);
// Works also for "test=asdf, id=17985, title=the matrix, year=1999"
It gets the String between "id=" and the next " " (space).

How do I ensure unique results when selecting random data?

I'm using XML to store a database of phrases where 5 of these phrases will be displayed to the user at a time. I need to ensure these 5 phrases are unique and, of course, just getting random data can't ensure that. I think I could do it if I could convert the string array that I'm using into a List, but I can't find good info on how to do that. Does anyone have any input on this?
public String getResults(){
// Get a random string from our results XML and return the string.
Resources r = getResources();
String[] resultsList = r.getStringArray(R.array.bossResults);
List<String> resultsArrayList = new ArrayList<String>(Arrays.asList(resultsList));
//ArrayList resultsArrayList = ;
String q = resultsList[rgenerator.nextInt(resultsList.length)];
return q;
//resultsList.remove(q);
}
private OnClickListener mAddListener = new OnClickListener()
{
public void onClick(View v)
{
//Declare our TextViews for population from the random results from XML
TextView t1 = new TextView(getApplicationContext());
t1=(TextView)findViewById(R.id.textView1);
TextView t2 = new TextView(getApplicationContext());
t2=(TextView)findViewById(R.id.textView2);
TextView t3 = new TextView(getApplicationContext());
t3=(TextView)findViewById(R.id.textView3);
TextView t4 = new TextView(getApplicationContext());
t4=(TextView)findViewById(R.id.textView4);
TextView t5 = new TextView(getApplicationContext());
t5=(TextView)findViewById(R.id.textView5);
// Get a random result for each textview
String result1 = getResults();
String result2 = getResults();
String result3 = getResults();
String result4 = getResults();
String result5 = getResults();
}
}
The easiest way is probably to rewrite getResults() to return all the strings you need (and additionally not load the "bossResults" array 5 times).
public List<String> getResults(int count){
// Get a random string from our results XML and return the string.
List<String> ret = new ArrayList<String>();
Resources r = getResources();
List<Integer> picked = new List<Integer>();
String[] resultsList = r.getStringArray(R.array.bossResults);
while (ret.size() < count) {
int i = rgenerator.nextInt(resultsList.length);
if (picked.contains(i)) { continue; }
picked.add(i);
ret.add(resultsList[i]);
}
return ret;
}
It might be slow for large values of count.
EDIT: It falls into an infinite loop if count is greater than the size of the array!
The easiest way is to remember which items you already selected and if you select one of them again, just discard it. This could be very slow, if the count of items to choose from is low. If that was the case, you could shuffle the whole array and return first n items.
I would make a change to getResults() to do all the work for you in one pass. This way it could remember what values have already been chosen, and shrink the values it then chooses from in the future....something like this:
public List<String> getResults(int count) {
List<String> results = new ArrayList<String>();
Resources r = getResources();
String[] resultsList = r.getStringArray(R.array.bossResults);
List<String> resultsArrayList = new ArrayList<String>(Arrays.asList(resultsList));
for(int i = 0; i < count; ++i) {
int next = rgenerator.nextInt(resultsArrayList.size());
String nextVal = resultsArrayList.remove(next);
results.add(nextVal);
}
return results;
}

Problems with the ViewBinder

I need to display a ListView with some images, and I'm using the following code:
dataText = (TextView)findViewById(R.id.data);
dataText.setText(camping.stringIn + " >> " + camping.stringOut);
l = name.length;
ArrayList<tipologia> tipologieList=new ArrayList<tipologia>();
tipologia[] tip = new tipologia[l];
for (int i = 0; i < l; i++)
{
int rand = new Random().nextInt(3);
availability[i] = String.format("%d", rand);
tip[i] = new tipologia(image[i]);
}
for(int i=0; i<tip.length; i++)
{
tipologieList.add(tip[i]);
}
ArrayList<HashMap<String, Object>> data=new ArrayList<HashMap<String,Object>>();
for(int i=0;i<tipologieList.size();i++){
tipologia t = tipologieList.get(i);
HashMap<String,Object> tipologieMap = new HashMap<String, Object>();
tipologieMap.put("image", t.getImm());
data.add(tipologieMap);
}
String[] from={"image"};
int[] to={R.id.personImage};
SimpleAdapterMod adapter=new SimpleAdapterMod(
getApplicationContext(),
data,
R.layout.tipologia,
from,
to);
adapter.setViewBinder(new ViewBinder() {
public boolean setViewValue(View view, Object data,
String textRepresentation) {
if(data instanceof String && view instanceof Immagine ){
((Immagine)view).loadFromURL((String)data);
}
return true;
}
else{
return false;
}
}
});
I have a problem: in the list there's space for 4 rows, and when I scroll down it happens that the image of the fifth row is the same of the image of the first row and the subsequent images are wrong too.
Can someone tell me why?
Thats because the first row's view is reused for the fifth row, as the first row is now no more visible. The problem is in your adapter class.
In getView() method, do not reuse convertview, instead return a new view everytime. This is not the recommended solution but to be used as last resort.

Categories

Resources