create array of keys from an object Android - android

I'm wanting to create an array of all keys within an object does anyone know how to do this in Android? in iOS I have done this
NSDictionary *variablesDictionary = [[NSDictionary alloc] init];
// ^^ full of variables and keys...
NSString *finalString = #"";
if(variablesDictionary != nil){
NSArray *keysArray = [variablesDictionary allKeys];
for(NSString *singleKey in keysArray) {
finalString = [finalString stringByAppendingString:[NSString stringWithFormat:#"&%#=%#", singleKey, [variablesDictionary objectForKey:singleKey]]];
}
}
//final string will = '&key=variable&key=variable&key=variable&key=variable' etc...
heres what i have tried so far. heres my global actions
public final static void startAPICallRequest(Context activityContext, String request, String apiLocation, Object postVarsObj, Object getVarsObj){
long unixTimeStamp = System.currentTimeMillis() / 1000L;
if(getVarsObj != null){
Array keysArray = getVarsObj.keySet().toArray();
StringBuilder sb = new StringBuilder();
for (String key : getVarsObj.keySet()) {
sb.append("&");
sb.append(key);
sb.append("=");
sb.append(getVarsObj.get(key).toString());
}
final String will = sb.toString();
}
}

// for Map<String, Object>
StringBuilder sb = new StringBuilder();
for (String key : map.keySet()) {
sb.append("&");
sb.append(key);
sb.append("=");
sb.append(map.get(key).toString());
}
final String will = sb.toString();

If using a map, you'll want to take a look at the keySet() functionality. Here is an example

Related

How to create a string / string array from a .txt/.xml file?

I know it has been asked a million times, but I just can't find anything that Works, and I just started learning to code
I'm trying to use regex to tell when the user types any of 118 different patterns, so you can guess it'd be a really long string, and I have all the patterns in a .txt/.xml file and I want to create a string or array with these patterns
The code:
public class MainActivity extends AppCompatActivity {
private TextView tv1;
private EditText et3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView)findViewById(R.id.tv1);
et3 = (EditText)findViewById(R.id.et3);
}
public void boton (View view){
String text = et3.getText().toString();
//String[] symbolsArr = {"He|","H|","Os|","O"};
//StringBuffer sb = new StringBuffer();
//for(int i = 0; i < symbolsArr.length; i++) { //all of this is just to convert an array to a single string
// sb.append(symbolsArr[i]);
//
String symbols = "Zr|Zn|Yb|Y|Xe|W|V|U|Ts|Tm|Tl|Ti|Th|Te|Tc|Tb|Ta|Sr|Sn|Sm|Si|Sg|Se|Sc|Sb|S|Ru|Rn|Rh|Rg|Rf|Re|Rb|Ra|Pu|Pt|Pr|Po|Pm|Pd|Pb|Pa|P|Os|Og|O|Np|No|Ni|Nh|Ne|Nd|Nb|Na|N|Mt|Mo|Mn|Mg|Md|Mc|Lv|Lu|Lr|Li|La|Kr|K|Ir|In|I|Hs|Ho|Hg|Hf|He|H|Ge|Gd|Ga|Fr|Fm|Fl|Fe|F|Eu|Es|Er|Dy|Ds|Db|Cu|Cs|Cr|Co|Cn|Cm|Cl|Cf|Ce|Cd|Ca|C|Br|Bk|Bi|Bh|Be|Ba|B|Au|At|As|Ar|Am|Al|Ag|Ac";
//The really long string with all the patterns
Pattern p = Pattern.compile(symbols);
Matcher m = p.matcher(text);
tv1.setText("");
while (m.find()){
tv1.append("found " + m.group() + "\n");
}
}
}
It depends of how do you want to storage the file.
For example let`s use assets.
Put file data.txt in assets(you can create this in File/New/Folder/Assets Folder)
After that you can create method, wich help you to get string from assetFile
public String getStringFromAssetFile(Context context, String nameFile)
{
String str = "";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(context.getAssets().open(nameFile)));
String line;
while ((line = reader.readLine()) != null) {
str += line;
}
} catch (IOException ex) {
ex.printStackTrace();
}
return str;
}
Now you can use this method to create a string or array with these patterns
String symbols = getStringFromAssetFile(MainActivity.this, "data.txt");

Problems splitting string at first empty space

I have a string which i need to split at the first empty space.
Somehow I can not get it to split, the string stays untouched.
Could somebody help?
String in question:
https://test.com/info/dsfs76/933/TT Maps 2015.12
https://test.com/info/dsfs76/933/TT and Maps 2015.12 need to be 2 seperate parts which are added to an arraylist.
My code attempt:
if (str.contains(linkElem.getLinkAddress() + " ")) {
String[] temp = str.split(" ");
for (String temp : Arrays.asList(temp)) {
arraytest.add(temp);
}
}
From the code you provided, there is no such String strtemp
Maybe you should be splitting str instead?
String[] temp = str.split(" ");
You can use String tokenizer to do that like this:
StringTokenizer st = new StringTokenizer(linkElem.getLinkAddress(), " ");
String a = st.nextToken();//string before " "
String b = st.nextToken();//string after " "
i know it is completely unelegant and dumb but it works %)
String string = "https://test.com/info/dsfs76/933/TT Maps 2015.12";
StringBuilder stringBuilder = new StringBuilder();
ArrayList<String> list = new ArrayList<>();
boolean whiteSpaceFound = false;
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) == ' ' && !whiteSpaceFound) {
list.add(stringBuilder.toString());
stringBuilder = new StringBuilder();
whiteSpaceFound = true;
} else {
stringBuilder.append(string.charAt(i));
}
}
if (whiteSpaceFound || list.isEmpty()) {
list.add(stringBuilder.toString());
}

Android: How to set substrings in lowercase in my string?

I want to set all my hashtags in lowercase in a string:
"Hello I'm a men #Athlete et I'm going to do sport #NeverGiveUp"
Should become:
"Hello I'm a men #athlete et I'm going to
do sport #nevergiveup"
if your problem is how to convert all to simple letters hope this helps
String myString = "HashTag";
String myNewSimpleLetterString = myString.substring(0,5).toLowerCase(); //subString will get the characters from 0 - 5
Try this code
Just pass your string to this method this method returns formatted String
public static String changeFormat(String beforeFormatStr) {
String[] arrStr = beforeFormatStr.split(" ");
String afterFormatStr = "";
int wordPos = 0;
for (String word : arrStr) {
String changeStr = word;
if (word.contains("#")) {
changeStr = word.toLowerCase();
}
if (wordPos == 0) {
afterFormatStr += changeStr;
} else {
afterFormatStr += " " + changeStr;
}
wordPos++;
}
return afterFormatStr;
}
You can use Regular expression for finding and replacing hashtags to lowercase. Like :
String line = "Hello I'm a men #Athlete et I'm going to do sport #NeverGiveUp";
String regEx = "\\S*#(?:\\[[^\\]]+\\]|\\S+)"; //Regular expression for matching hashtag
StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(line);
while (m.find())
{
// Avoids throwing a NullPointerException in the case that you
// Don't have a replacement defined in the map for the match
String repString = m.group();
if (repString != null)
repString = repString.toLowerCase();
m.appendReplacement(sb, repString);
}
m.appendTail(sb);
String replacedHashtag = sb.toString();
Hash is not a string, so you have to use Regx matcher and Pattern to achieve this.
List<String> obtained_hashwords = new ArrayList<>();
String text_data = "Hello I'm a men #Athlete et I'm going to do sport #NeverGiveUp and I want to format this string";
Pattern pattern = Pattern.compile("#\\w+");
Matcher matcher = pattern.matcher(text_data);
while (matcher.find())
{
obtained_hashwords.add(matcher.group());
Log.d("Hash word",matcher.group());
}
for (String obtained_hashword:obtained_hashwords)
{
String no_hash = obtained_hashword.replace("#","");
String lower_case_word = "#"+no_hash.toLowerCase();
text_data = text_data.replace(obtained_hashword,lower_case_word);
}
Log.d("changed line",text_data);

Convert Hex String to String

HI I have to tried multiple ways to convert Hex String to ASCII String but not getting success. While before I have done the same but now I am not able to achieve it.
My Code is
private static String hexToASCII(String hexValue)
{
StringBuilder output = new StringBuilder("");
for (int i = 0; i < hexValue.length(); i += 2)
{
String str = hexValue.substring(i, i + 2);
output.append((char) Integer.parseInt(str, 16));
}
return output.toString();
}
but it is returning garbage value like b��¡
and my Hex String is
621c8002008a820101a10a8c0341c2009c0341c2008302010288008a0105
Please help me if someone has also suffered from the same issue and fixed it.
Thanks ....
Try this out
public class HextoAsscii {
public static void main(String args[])
{
String hex="621c8002008a820101a10a8c0341c2009c0341c2008302010288008a0105";
String str="";
str= hexToASCII(hex);
}
private static String hexToASCII(String hexValue)
{
StringBuilder output = new StringBuilder("");
for (int i = 0; i < hexValue.length(); i += 2)
{
if(i+2<=hexValue.length())
{
String str = hexValue.substring(i, i + 2);
output.append(Integer.parseInt(str, 16));
}
}
System.out.println(output.toString());
return output.toString();
}
}

Android CSV parser problem

I am having an issue while parsing a CSV file. It is only 2 rows of data with a comma separating them. Row one is a date and row 2 is a value. The date field will always have dates in it but sometimes the value is blank (or null?). When it gets to the null value I get a StringIndexOutOfBoundsException and the app crashes. I am logging each loop and can see the data but as soon as I get to a null value it stops looping and gives the error. If there are no null values then it works perfect. Here is my code:
BufferedReader buf = new BufferedReader(new StringReader(file));
String line = null;
while ((line = buf.readLine()) != null) {
try {
String date = null, value = null;
String[] RowData = line.split(",");
date = RowData[0];
value = RowData[1]; (this is the row it crashes on)
This is what the CSV looks like:
2011-08-28 09:16,8.23
2011-08-28 09:15,8.24
2011-08-28 09:14,8.26
2011-08-28 09:13,8.34
2011-08-28 09:12,
2011-08-28 09:11,10.72
2011-08-28 09:10,
2011-08-28 09:09,
the value at 09:13 is the last thing in logcat before I get the error.
This fixed it:
if(RowData.length == 2) {
date = RowData[0];
value = RowData[1];
} else {
date = RowData[0];
value = "0";
}
I wrote a 0 in the value field so later processes will not choke on the null value. Thanks for all your help guys!
You want to do this or something like it:
String date = null, value = null;
String[] RowData = line.split(",");
date = RowData[0];
if(RowData.length ==2)value = RowData[1]; (this is the row it crashes on)
Or some variation of it e.g. if(RowData.length < 2) dont attempt to read the value. Its a pretty standard thing - if you ask an array for an index of a value it doesn't have Java will crash.
Why write your own CSV parsing when you could use a library that has already been written which will do it for you? Perhaps OpenCSV would help you achieve your CSV parsing goal.
Check the length of RowData before you try to access it. It looks like split() is returning an array with a single object but you're trying to access the second object, which is indeed out of bounds.
public class CityParser {
DocumentBuilderFactory factory;
DocumentBuilder builder;
Document doc;
Element ele;
int mediaThumbnailCount;`enter code here`
boolean urlflag;
CityListBean objBean = null;
Vector<CityListBean> vecCityList;
public CityParser() {
}
public Vector<CityListBean> getCityData() {
vecCityList = new Vector<CityListBean>();
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(
"http://heresmyparty.com/cms/index.php?option=com_chronocontact&chronoformname=add_event_form_download");
HttpResponse response = httpClient.execute(httpGet, localContext);
// String result = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
CSVReader csvreader = new CSVReader(reader);
String[] nextLine;
while ((nextLine = csvreader.readNext()) != null) {
CityListBean objcitylist = new CityListBean();
// nextLine[] is an array of values from the line
objcitylist.setText_title(nextLine[5]);
objcitylist.setText_host(nextLine[6]);
objcitylist.setText_price(nextLine[7]);
objcitylist.setDate(nextLine[8]);
objcitylist.setText_venue(nextLine[11]);
objcitylist.setAddress(nextLine[12]);
objcitylist.setLatitude(nextLine[13]);
objcitylist.setLongitude(nextLine[14]);
objcitylist.setFile(nextLine[15]);
objcitylist.setText_description(nextLine[16]);
objcitylist.setCity(nextLine[17]);
vecCityList.addElement(objcitylist);
}
/*for (int i = 0; i < vecCityList.size(); i++) { CityListBean
objcity = (CityListBean) vecCityList.get(i);
System.out.println("Cf_id : " + objcity.getCityName());
System.out.println("-----------------------------------"); }*/
} catch (Exception ex) {
ex.printStackTrace();
}
return vecCityList;
}
}
==========================================================================================
public class CSVReader {
private BufferedReader br;
private boolean hasNext = true;
private char separator;
private char quotechar;
private int skipLines;
private boolean linesSkiped;
public static final char DEFAULT_SEPARATOR = ',';
public static final char DEFAULT_QUOTE_CHARACTER = '"';
public static final int DEFAULT_SKIP_LINES = 0;
public CSVReader(Reader reader) {
this(reader, DEFAULT_SEPARATOR, DEFAULT_QUOTE_CHARACTER,
DEFAULT_SKIP_LINES);
}
public CSVReader(Reader reader, char separator, char quotechar, int line) {
this.br = new BufferedReader(reader);
this.separator = separator;
this.quotechar = quotechar;
this.skipLines = line;
}
public String[] readNext() throws IOException {
String nextLine = getNextLine();
return hasNext ? parseLine(nextLine) : null;
}
private String getNextLine() throws IOException {
if (!this.linesSkiped) {
for (int i = 0; i < skipLines; i++) {
br.readLine();
}
this.linesSkiped = true;
}
String nextLine = br.readLine();
if (nextLine == null) {
hasNext = false;
}
return hasNext ? nextLine : null;
}
private String[] parseLine(String nextLine) throws IOException {
if (nextLine == null) {
return null;
}
List<String> tokensOnThisLine = new ArrayList<String>();
StringBuffer sb = new StringBuffer();
boolean inQuotes = false;
do {
if (inQuotes) {
// continuing a quoted section, reappend newline
sb.append("\n");
nextLine = getNextLine();
if (nextLine == null)
break;
}
for (int i = 0; i < nextLine.length(); i++) {
char c = nextLine.charAt(i);
if (c == quotechar) {
// this gets complex... the quote may end a quoted block, or escape another quote.
// do a 1-char lookahead:
if( inQuotes // we are in quotes, therefore there can be escaped quotes in here.
&& nextLine.length() > (i+1) // there is indeed another character to check.
&& nextLine.charAt(i+1) == quotechar ){ // ..and that char. is a quote also.
// we have two quote chars in a row == one quote char, so consume them both and
// put one on the token. we do *not* exit the quoted text.
sb.append(nextLine.charAt(i+1));
i++;
}else{
inQuotes = !inQuotes;
// the tricky case of an embedded quote in the middle: a,bc"d"ef,g
if(i>2 //not on the begining of the line
&& nextLine.charAt(i-1) != this.separator //not at the begining of an escape sequence
&& nextLine.length()>(i+1) &&
nextLine.charAt(i+1) != this.separator //not at the end of an escape sequence
){
sb.append(c);
}
}
} else if (c == separator && !inQuotes) {
tokensOnThisLine.add(sb.toString());
sb = new StringBuffer(); // start work on next token
} else {
sb.append(c);
}
}
} while (inQuotes);
tokensOnThisLine.add(sb.toString());
return (String[]) tokensOnThisLine.toArray(new String[0]);
}
public void close() throws IOException{
br.close();
}
}
Have you tried to check first
if (RowData[1]!=null) or possibly if (RowData[1]!="")
I don't see why that would cause your app to crash though,
it should just set value to null or ""

Categories

Resources