How to add a String to another String array in android? - java

This my java code, here i have to add a string "RFID" in a String Array itemtypes and i have to stored it in an another string array item.But im getting an error.
String[] itemtype;
String[] item;
\...........
.........../
try {
response = (SoapPrimitive) envelope.getResponse();
Koradcnos = response.toString();
} catch (SoapFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
itemtypes = Koradcnos.split(";");
item=itemtypes+"RFID";//here im getting error
} catch (Exception er) {
//Helper.warning("Error", er.toString(),this);
}
imageId = new int[itemtypes.length];
for (int i = 0; i < itemtypes.length; i++)
if (itemtypes[i].equals("Yarn")) {
imageId[i] = R.drawable.yarnitem;

You need to work around for this :
Using with Arrays.copyOf
item = Arrays.copyOf(itemtypes , itemtypes.length + 1);
item[item.length - 1] = "RFID";
Or direct split from Koradcnos
item = (Koradcnos + ";RFID").split(";");

You cannot concatenate string with a list String.split() method returns a String array.
Instead of item=itemtypes+"RFID" iterate through the array as:
for (int i=0; i < itemtypes.length(); i++) {
item[i] = itemtypes[i] + "RFID";
}
Also I think the variable name will be itemtypes instead of itemtype

itemtypes is String array,it can't be modified,if you want to get a new array adding another element,you can use System.arrayCopy
System.arraycopy(Object src,
int srcPos,
Object dest,
int destPos,
int length)
Like this:
item = new String[itemtypes.length+1];
System.arraycopy(itemtypes,0,item,0,itemtypes.length);
item[itemtypes.length] = "RFID";

Related

Java get java.awt.Color from string

So I have a string that looks something like this:
text java.awt.Color[r=128,g=128,b=128]text 1234
How could I pop out the color and get the rgb values?
You can get the rgb values from that string with this:
String str = "text java.awt.Color[r=128,g=128,b=128]text 1234";
String[] temp = str.split("[,]?[r,g,b][=]|[]]");
String[] colorValues = new String[3];
int index = 0;
for (String string : temp) {
try {
Integer.parseInt(string);
colorValues[index] = string;
index++;
} catch (Exception e) {
}
}
System.out.println(Arrays.toString(colorValues)); //to verify the output
The above example extract the values in an array of Strings, if you want in an array of ints:
String str = "text java.awt.Color[r=128,g=128,b=128]text 1234";
String[] temp = str.split("[,]?[r,g,b][=]|[]]");
int[] colorValues = new int[3];
int index = 0;
for (String string : temp) {
try {
colorValues[index] = Integer.parseInt(string);
index++;
} catch (Exception e) {
}
}
System.out.println(Arrays.toString(colorValues)); //to verify the output
As said before, you will need to parse the text. This will allow you to return the RGB values from inside the string. I would try something like this.
private static int[] getColourVals(String s){
int[] vals = new int[3];
String[] annotatedVals = s.split("\\[|\\]")[1].split(","); // Split the string on either [ or ] and then split the middle element by ,
for(int i = 0; i < annotatedVals.length; i++){
vals[i] = Integer.parseInt(annotatedVals[i].split("=")[1]); // Split by the = and only get the value
}
return vals;
}

Assign a unique key to repeated Arraylist items. and Keep track of Ordering in java

I have a data like :
in an arraylist of Strings I am collecting names .
example:
souring.add(some word);
later I have something in souring = {a,b,c,d,d,e,e,e,f}
I want to assign each element a key like:
0=a
1=b
2=c
3=d
3=d
4=e
4=e
4=e
5=f
and then I store all ordering keys in an array . like:
array= [0,1,2,3,3,4,4,4,5]
heres my code on which I am working :
public void parseFile(String path){
String myData="";
try {
BufferedReader br = new BufferedReader(new FileReader(path)); {
int remainingLines = 0;
String stringYouAreLookingFor = "";
for(String line1; (line1 = br.readLine()) != null; ) {
myData = myData + line1;
if (line1.contains("relation ") && line1.endsWith(";")) {
remainingLines = 4;//<Number of Lines you want to read after keyword>;
stringYouAreLookingFor += line1;
String everyThingInsideParentheses = stringYouAreLookingFor.replaceFirst(".*\\((.*?)\\).*", "$1");
String[] splitItems = everyThingInsideParentheses.split("\\s*,\\s*");
String[] sourceNode = new String[10];
String[] destNode = new String[15];
int i=0;
int size = splitItems.length;
int no_of_sd=size;
tv.setText(tv.getText()+"size " + size + "\n"+"\n"+"\n");
sourceNode[0]=splitItems[i];
// here I want to check and assign keys and track order...
souring.add(names);
if(size==2){
destNode[0]=splitItems[i+1];
tv.setText(tv.getText()+"dest node = " + destNode[0] +"\n"+"\n"+"\n");
destination.add(destNode[0]);
}
else{
tv.setText(tv.getText()+"dest node = No destination found"+"\n"+"\n"+"\n");
}
} else if (remainingLines > 0) {
remainingLines--;
stringYouAreLookingFor += line1;
}
}
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
How can I do this?
can any one help me in this..?
I would advise you to use ArrayList instead of String[]
So, if you want to add an element you just write
ArrayList<String> list = new ArrayList<String>;
list.add("whatever you want");
Then, if you want to avoid repetitions just use the following concept:
if(!list.contains(someString)){
list.add(someString);
}
And if you want to reach some element you just type:
list.get(index);
Or you can easily find an index of an element
int index=list.indexOf(someString);
Hope it helps!
Why don't you give it a try, its take time to understand what you actually want.
HashMap<Integer,String> storeValueWithKey=new HashMap<>();
// let x=4 be same key and y="x" be new value you want to insert
if(storeValueWithKey.containsKey(x))
storeValueWithKey.get(x)+=","+y;
else
storeValueWithKey.put(z,y); //Here z is new key
//Than for searching ,let key=4 be value and searchValue="a"
ArrayList<String> searchIn=new ArrayList<>(Arrays.asList(storeValueWithKey.get("key").split(",")));
if(searchIn.contains("searchValue"))
If problem still persist than comment

Initializing array for JSON data advice

I am trying to store data gotton from JSON to an normal string array. The problem is i cant seem to initialize the array size according to the number for JSON data.
For now i declare the array size my own:
String[] path= new String[5];
This is the JSON part:
class Loadpath extends AsyncTask {
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_imageDB, "GET",params);
try {
JSONArray productObj = json.getJSONArray(TAG_IMAGEDB); // JSON Array
// looping through All path
for (int i = 0; i < productObj.length(); i++) {
JSONObject image = productObj.getJSONObject(i);
path[i] = image.getString(TAG_PATH);
}
} else {
displayPath.setText("No path");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
So my goal is the array size is gotten from the JSON.length().. Any idea how I can achieve this?
initialize the mStrings[ ] array size according to the JSONArray length as:
String[] mStrings; //<< Declare array as
mStrings = new String[productObj.length()]; //<<initialize here
for (int i = 0; i < productObj.length(); i++) {
JSONObject image = productObj.getJSONObject(i);
mStrings[i] = image.getString(TAG_PATH);
}
and it is good if you use ArrayList instead of String Array as for getting values from Jsonobject as:
ArrayList<String> mStrings=new ArrayList<String>(;
for (int i = 0; i < productObj.length(); i++) {
JSONObject image = productObj.getJSONObject(i);
mStrings.add(image.getString(TAG_PATH));
}
Maybe u can use List instead of String array

Extract specific value from a filter-list (auto-complete field)

in my application I'm trying to extract the values from a filter list (auto-complete field).
In that field I have [ID, Name] ex [j342234, A,S]. I was able to retrieve the whole criteria by
doing this
Object Filterlistresult = fliterList.getCriteria();
but now I want to get extract ID part only from that field. Any Ideas?
Thank you in advance.
// here I get the values from a web server and insert them to the work Vector
public void parseJSONResponceInWB(String jsonInStrFormat) {
try {
JSONObject json = new JSONObject(jsonInStrFormat);
JSONArray jArray = json.getJSONArray("transport");
for (int i = 1; i < jArray.length(); i++) {
JSONObject j = jArray.getJSONObject(i);
ID = j.getString("ID");
Name = j.getString("Name");
WBenchVector.addElement(ID + " " + Name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// adding the values to the filter list
private void RequestAutoComplete() {
String[] returnValues = new String[WBenchVector.size()];
System.out.print(returnValues);
for (int i = 0; i < WBenchVector.size(); i++) {
returnValues[i] = (String) WBenchVector.elementAt(i);
}
autoCompleteField(returnValues);
}
// creating the filter list field
private void autoCompleteField(String[] returnValues) {
filterLst = new BasicFilteredList();
filterLst.addDataSet(ID, returnValues, "",
BasicFilteredList.COMPARISON_IGNORE_CASE);
autoFld.setFilteredList(filterLst);
}
Finally i'm getting what the user select using this
AutoFieldCriteria = filterLst.getCriteria();
Thank you Nate. I actually fixed the problem.
I converted the filterField Object to String and then I looked for the index of the first space, and substring the first word
Object AutoFieldCriteria = filterLst.getCriteria();
String AutoFieldString = AutoFieldCriteria.toString();
int spacePos = AutoFieldString.indexOf(" ");
String AutoFieldFirstWord = AutoFieldString.substring(0,spacePos);
Thanks again.

Convert Json Array to normal Java list

Is there a way to convert JSON Array to normal Java Array for android ListView data binding?
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
If you don't already have a JSONArray object, call
JSONArray jsonArray = new JSONArray(jsonArrayString);
Then simply loop through that, building your own array. This code assumes it's an array of strings, it shouldn't be hard to modify to suit your particular array structure.
List<String> list = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
list.add( jsonArray.getString(i) );
}
Instead of using bundled-in org.json library, try using Jackson or GSON, where this is a one-liner. With Jackson, f.ex:
List<String> list = new ObjectMapper().readValue(json, List.class);
// Or for array:
String[] array = mapper.readValue(json, String[].class);
Maybe it's only a workaround (not very efficient) but you could do something like this:
String[] resultingArray = yourJSONarray.join(",").split(",");
Obviously you can change the ',' separator with anything you like (I had a JSONArray of email addresses)
Using Java Streams you can just use an IntStream mapping the objects:
JSONArray array = new JSONArray(jsonString);
List<String> result = IntStream.range(0, array.length())
.mapToObj(array::get)
.map(Object::toString)
.collect(Collectors.toList());
Use can use a String[] instead of an ArrayList<String>:
It will reduce the memory overhead that an ArrayList has
Hope it helps!
String[] stringsArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length; i++) {
parametersArray[i] = parametersJSONArray.getString(i);
}
I know that question is about JSONArray but here's example I've found useful where you don't need to use JSONArray to extract objects from JSONObject.
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
String jsonStr = "{\"types\":[1, 2]}";
JSONObject json = (JSONObject) JSONValue.parse(jsonStr);
List<Long> list = (List<Long>) json.get("types");
if (list != null) {
for (Long s : list) {
System.out.println(s);
}
}
Works also with array of strings
Here is a better way of doing it: if you are getting the data from API. Then PARSE the JSON and loading it onto your listview:
protected void onPostExecute(String result) {
Log.v(TAG + " result);
if (!result.equals("")) {
// Set up variables for API Call
ArrayList<String> list = new ArrayList<String>();
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.get(i).toString());
}//end for
} catch (JSONException e) {
Log.e(TAG, "onPostExecute > Try > JSONException => " + e);
e.printStackTrace();
}
adapter = new ArrayAdapter<String>(ListViewData.this, android.R.layout.simple_list_item_1, android.R.id.text1, list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText( ListViewData.this, "Position :" + itemPosition + " ListItem : " + itemValue, Toast.LENGTH_LONG).show();
}
});
adapter.notifyDataSetChanged();
adapter.notifyDataSetChanged();
...
we starting from conversion [ JSONArray -> List < JSONObject > ]
public static List<JSONObject> getJSONObjectListFromJSONArray(JSONArray array)
throws JSONException {
ArrayList<JSONObject> jsonObjects = new ArrayList<>();
for (int i = 0;
i < (array != null ? array.length() : 0);
jsonObjects.add(array.getJSONObject(i++))
);
return jsonObjects;
}
next create generic version replacing array.getJSONObject(i++) with POJO
example :
public <T> static List<T> getJSONObjectListFromJSONArray(Class<T> forClass, JSONArray array)
throws JSONException {
ArrayList<Tt> tObjects = new ArrayList<>();
for (int i = 0;
i < (array != null ? array.length() : 0);
tObjects.add( (T) createT(forClass, array.getJSONObject(i++)))
);
return tObjects;
}
private static T createT(Class<T> forCLass, JSONObject jObject) {
// instantiate via reflection / use constructor or whatsoever
T tObject = forClass.newInstance();
// if not using constuctor args fill up
//
// return new pojo filled object
return tObject;
}
You can use a String[] instead of an ArrayList<String>:
Hope it helps!
private String[] getStringArray(JSONArray jsonArray) throws JSONException {
if (jsonArray != null) {
String[] stringsArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
stringsArray[i] = jsonArray.getString(i);
}
return stringsArray;
} else
return null;
}
We can simply convert the JSON into readable string, and split it using "split" method of String class.
String jsonAsString = yourJsonArray.toString();
//we need to remove the leading and the ending quotes and square brackets
jsonAsString = jsonAsString.substring(2, jsonAsString.length() -2);
//split wherever the String contains ","
String[] jsonAsStringArray = jsonAsString.split("\",\"");
To improve Pentium10s Post:
I just put the elements of the JSON array into the list with a foreach loop. This way the code is more clear.
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
jsonArray.forEach(element -> list.add(element.toString());
private String[] getStringArray(JSONArray jsonArray) throws JSONException {
if (jsonArray != null) {
String[] stringsArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
stringsArray[i] = jsonArray.getString(i);
}
return stringsArray;
} else
return null;
}
You can use iterator:
JSONArray exportList = (JSONArray)response.get("exports");
Iterator i = exportList.iterator();
while (i.hasNext()) {
JSONObject export = (JSONObject) i.next();
String name = (String)export.get("name");
}
I know that the question was for Java. But I want to share a possible solution for Kotlin because I think it is useful.
With Kotlin you can write an extension function which converts a JSONArray into an native (Kotlin) array:
fun JSONArray.asArray(): Array<Any> {
return Array(this.length()) { this[it] }
}
Now you can call asArray() directly on a JSONArray instance.
How about using java.util.Arrays?
List<String> list = Arrays.asList((String[])jsonArray.toArray())

Categories

Resources