I am making an app that gets data from SOAP. When it has the data it must put it in a listview.
the result string is:
it_id=636207115 :#=1:price=1,18|it_id=636207115 :#=1:price=1,18|it_id=636205395 :#=1:price=0,92
I now have to split the string like this: it_id=636207115 :#=1:price=1,18 , as you can see the string splits at the '| '.
But now i have to split the string again to get three strings from that. But i cant figure out how to split it then. I need to split that string at the ':' and put it then in the listview.
If anyone knows how to split split the string please let me know!
First Encode your String and then use spilt() and than Decode String to Original
try {
str = URLEncoder.encode("t_id=636207115 :#=1:price=1,18|it_id=636207115 :#=1:price=1,18|it_id=636205395 :#=1:price=0,92", "UTF-8");
}
catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String abc[] = str.split("%7C"); // %7C is Encoded | by which you want to spilt the String
// Loop Through the Array and Decode the String !
for (int i = 0; i < abc.length; i++) {
try {
abc[i] = URLDecoder.decode(abc[i], "UTF-8");// Decoding String and Stroring it back to Array
System.out.println(abc[i]);// Testing String
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String selectedFromList = text.getText().toString();
String abc[] = selectedFromList.split(","); // %7C is Encoded | by which you want to spilt the String
for (int i = 0; i < abc.length; i++) {
try {
if(i==abc.length-1)
Log.i("deepika deepika ::", abc[i]);
tvCountryName.setText(abc[i]);
edit.putString(COUNTRY, abc[i]);
edit.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String selectedFromList = "hello, hi, how are you, guys";
String abc[] = selectedFromList.split(",");
for (int i = 0; i < abc.length; i++) {
try {
Log.i("deepika deepika ::", abc[i]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Related
I have read the other questions with the same title but none have helped with my issue and nothing online has helped either.
I am new to Java and am trying to get a basic program running but I keep getting the aforementioned error.
Code below.
package loopy;
import java.io.*;
public class loopy {
public static void main (String[] args) {
// TODO: Use a loop to print every upper case letter
for (int i = 65; i < 91; i++) {
System.out.println((char)i);
}
// TODO: Get input from user. Print the same input back but with cases swapped.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
String input = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
toggleStringCase(input);
}
// TODO: Implement this function to return the opposite case of the letter given. DO NOT USE any built in functions.
// How to handle the case where the char given is not a letter?
private static char toggleCase(char c) {
return c;
}
// TODO: Implement this function to toggle the case each char in a string. Use toggleCase() to help you.
private static String toggleStringCase(String str) {
return str;
}
}
Where it says toggleStringCase(input); is where I am getting the error trying to pass the variable to a function.
Nothing i have read suggests what I might be doing wrong.
I am sure it must be a basic error but could someone please point me in the right direction.
Have I missed some syntax somewhere?
input only has scope in the try block, move the call there. Also, I would prefer a try-with-resources over explicitly closing in with another try block. But, it should be noted that closing in also closes System.in (which is a global variable) and great care should be taken in doing so (since any future attempts to read from System.in will fail)
try (BufferedReader in = new BufferedReader(new InputStreamReader(System.in))) {
String input = in.readLine();
toggleStringCase(input);
} catch (IOException e) {
e.printStackTrace();
}
You have to move your variable [input] to your scope.
cause you declare it inside a try block, but want to use out of the scope.
public class loopy {
public static void main (String[] args) {
// TODO: Use a loop to print every upper case letter
for (int i = 65; i < 91; i++) {
System.out.println((char)i);
}
String input=null;
// TODO: Get input from user. Print the same input back but with cases swapped.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
input = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
toggleStringCase(input);
}
// TODO: Implement this function to return the opposite case of the letter given. DO NOT USE any built in functions.
// How to handle the case where the char given is not a letter?
private static char toggleCase(char c) {
return c;
}
// TODO: Implement this function to toggle the case each char in a string. Use toggleCase() to help you.
private static String toggleStringCase(String str) {
return str;
}
}
variable input can't be solved to a variable since you don't have an input variable in the scope of your main method (the scope where you are using the input variable as a parameter of toggleStringCase method). You only have input variable in the scope of your try which means that input variable is only accessible within the try and since you are using input variable outside the try that is why it produces the error.
There are 2 possible ways to fix this:
To fix this you should move your declaration of input variable in the scope of your main method. I have updated your code below:
package loopy;
import java.io.*;
public class loopy {
public static void main (String[] args) {
// TODO: Use a loop to print every upper case letter
String input = ""; // DECLARE input HERE so that it can be used in the scope of your main method
for (int i = 65; i < 91; i++) {
System.out.println((char)i);
}
// TODO: Get input from user. Print the same input back but with cases swapped.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
input = in.readLine(); // get the actual input
// The try/catch below are commented out since you can combine it to the try/catch above
// START
//} catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
//}
//try {
// END
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
toggleStringCase(input);
}
// TODO: Implement this function to return the opposite case of the letter given. DO NOT USE any built in functions.
// How to handle the case where the char given is not a letter?
private static char toggleCase(char c) {
return c;
}
// TODO: Implement this function to toggle the case each char in a string. Use toggleCase() to help you.
private static String toggleStringCase(String str) {
return str;
}
}
Or you can move the function call for toggleStringCase inside your try-catch. Refer to the code below.
package loopy;
import java.io.*;
public class loopy {
public static void main (String[] args) {
// TODO: Use a loop to print every upper case letter
for (int i = 65; i < 91; i++) {
System.out.println((char)i);
}
// TODO: Get input from user. Print the same input back but with cases swapped.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
String input = in.readLine(); // get the actual input
toggleStringCase(input); // MOVE IT HERE
// The try/catch below are commented out since you can combine it to the try/catch above
// START
//} catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
//}
//try {
// END
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// toggleStringCase(input); // was moved inside try-catch
}
// TODO: Implement this function to return the opposite case of the letter given. DO NOT USE any built in functions.
// How to handle the case where the char given is not a letter?
private static char toggleCase(char c) {
return c;
}
// TODO: Implement this function to toggle the case each char in a string. Use toggleCase() to help you.
private static String toggleStringCase(String str) {
return str;
}
}
classic eg of scope problem. The var input is only accessible inside the try block or what is under the braces {}
Move your toggleStringCase(input); in the try block of input itself
public class loopy {
public static void main (String[] args) {
// TODO: Use a loop to print every upper case letter
for (int i = 65; i < 91; i++) {
System.out.println((char)i);
}
// TODO: Get input from user. Print the same input back but with cases swapped.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
String input = in.readLine();
toggleStringCase(input); // moved
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Or you can declare String input outside try block with some default/init value like
String input = "default value";// moved
try {
input = in.readLine();
toggleStringCase(input);
}
I currently have a file download process in my java class, listed below, to take all the data in an SQL table and put it in a CSV file for user download. However, when I download the file, all the data is good except it will cut off at random points (usually around line 20 of the data, given there are at least over 100 lines of data). I want to ask, what if making the cutoff? Is it session time related or is the code just problematic?
public String processFileDownload() {
DataBaseBean ckear = new DataBaseBean();
ckear.clearContens();
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
Map<String, Object> m = fc.getExternalContext().getSessionMap();
dbase = (DbaseBean) m.get("dbaseBean");
message = (MessageBean) m.get("messageBean");
dataBean = (DataBean) m.get("dataBean");
dbmsUser = (DbmsUserBean) m.get("dbmsUserBean");
FileOutputStream fos = null;
String path = fc.getExternalContext().getRealPath("/temp");
String tableName = dbmsUser.getTableName();
String fileNameBase = tableName + ".csv";
java.net.URL check = getClass().getClassLoader().getResource(
"config.properties");
File check2 = new File(check.getPath());
path = check2.getParent();
String fileName = path + "/" + dbmsUser.getUserName() + "_"
+ fileNameBase;
File f = new File(fileName);
try {
f.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
dbase.connect();
dbase.setQueryType("SELECT");
dbase.executeSQL("select * from " + tableName);
if (dbase.getResultSet() == null) {
FacesContext.getCurrentInstance().addMessage("myForm3:errmess",
new FacesMessage("Table doesn't exist!"));
return "failed";
}
Result result = ResultSupport.toResult(dbase.getResultSet());
downlaodedrows = result.getRowCount();
Object[][] sData = result.getRowsByIndex();
String columnNames[] = result.getColumnNames();
StringBuffer sb = new StringBuffer();
try {
fos = new FileOutputStream(fileName);
for (int i = 0; i < columnNames.length; i++) {
sb.append(columnNames[i].toString() + ",");
}
sb.append("\n");
fos.write(sb.toString().getBytes());
for (int i = 0; i < sData.length; i++) {
sb = new StringBuffer();
for (int j = 0; j < sData[0].length; j++) {
sb.append(sData[i][j].toString() + ",");
}
sb.append("\n");
fos.write(sb.toString().getBytes());
}
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String mimeType = ec.getMimeType(fileName);
FileInputStream in = null;
byte b;
ec.responseReset();
ec.setResponseContentType(mimeType);
ec.setResponseContentLength((int) f.length());
ec.setResponseHeader("Content-Disposition", "attachment; filename=\""
+ fileNameBase + "\"");
try {
in = new FileInputStream(f);
OutputStream output = ec.getResponseOutputStream();
while (true) {
b = (byte) in.read();
if (b < 0)
break;
output.write(b);
}
} catch (NullPointerException e) {
fc.responseComplete();
return "SUCCESS";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
fc.responseComplete();
return "SUCCESS";
}
The problem seems to be that you are simply appending commas between values and it's likely one of the values you are writing contains a delimiter, line separator or quote character, which will "break" the CSV format if not correctly escaped.
It would be way easier and faster to use CSV library for that. uniVocity-parsers comes with pre-built routines to dump your resultset into properly formatted CSV. In your case, you could use this library in the following manner:
ResultSet resultSet = dbase.getResultSet();
// Configure the output format as needed before actually dumping the data:
CsvWriterSettings writerSettings = new CsvWriterSettings(); //many settings here, check the tutorials & examples.
writerSettings.getFormat().setLineSeparator("\n");
writerSettings.setHeaderWritingEnabled(true); // we want the column names to be printed out as well.
// Then create a routines object:
CsvRoutines routines = new CsvRoutines(writerSettings);
// The write() method takes care of everything. The resultSet and any other resources required are closed by the routine.
routines.write(resultSet, new File(fileName), "UTF-8");
Hope this helps
Disclaimer: I'm the author of this library. It's open source and free (Apache 2.0. license)
I am trying to read from 45 pages that are all the same (except for the part im reading of course) and write them in a list of line lists.
I wrote this code so far:
public static ArrayList<ArrayList<String>> linesWeNeed(){
ArrayList<ArrayList<String>> returnListList = new ArrayList<ArrayList<String>>();
for(int i = 1; i<=45; i++){
int pageNum=(i*20)-20;
System.out.println("PageNum"+pageNum);
URL url=null;
try {
url = new URL("http://tq.mot.gov.il/index.php?option=com_moofaq&iotype=w&view=category&lang_ovrrde=ENG&id=3&Itemid=29&limitstart="+pageNum);
} catch (MalformedURLException e) {
System.out.println("Oh uh!");
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
} catch (IOException e) {
System.out.println("FATAL ERROR");
e.printStackTrace();
}
ArrayList<String> lineCodes = new ArrayList<String>();
ArrayList<String> linesWeNeed = new ArrayList<String>();
String line;
try {
readLines:
while((line=in.readLine())!=null){
if(line.contains("</tr></table></div></div></li></ul></div></div><br /></div>")){
break readLines;
}
lineCodes.add(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int o = 1; o>=lineCodes.size(); o++){
String readLine = lineCodes.get(o-1);
if(o>=297){
linesWeNeed.add(readLine);
}
}
returnListList.add(linesWeNeed);
}
return returnListList;
}
There are no errors, but for some reason every list in the arraylist the methods return is empty. Why?
Thanks in advance!
for(int o = 1; o>=lineCodes.size(); o++){
Your loop condition is back to front. Try <=.
for(int o = 1; o>=lineCodes.size(); o++){
Double-check the loop condition there; seems like that block is never going to execute...
I'm trying to create a simple recorder which gives 'pause' and 'resume' functionality to the user.
Since Android does not support this directly, I'm creating individual files whenever the user presses 'Pause' and 'Resume' with the suffixes _1, _2, so on.
I use the code below to concatenate them
public void mergeAllAndSave() {
// TODO Auto-generated method stub
Enumeration<FileInputStream> allRecordings;
Vector<FileInputStream> audiofiles = new Vector<FileInputStream>();
for (int i = 1; i < count+1; i++) {
try {
audiofiles.add(new FileInputStream(Environment.getExternalStorageDirectory().getPath() + "/"+ AUDIO_RECORDER_FOLDER + "/" + _filename + "_"+ i + file_exts[currentFormat]));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
allRecordings = audiofiles.elements();
SequenceInputStream siStream = new SequenceInputStream(allRecordings);
try {
FileOutputStream foStream = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/"+ AUDIO_RECORDER_FOLDER + "/" + _filename + file_exts[currentFormat]);
int temp;
while ((temp = siStream.read() ) != -1) {
foStream.write(temp);
}
foStream.close();
siStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The code works fine. It gives me a single file. However it contains the contents of the first file only. Logcat does not show any errors, whatsoever.
Anyone with any ideas what is the mistake I am making?
Thanks.
Answer to this question is here.
PS: I cannot add this as a comment because I do not have sufficient reputation.
I am trying to decode the data encoded in the image. The encoding works fine and the data size of image also changes but for some reason the decoded data is an empty string. Either the encoded data get lost or this code has some mistake.
int temp,tempText=0,x=0,p=0;
try
{
image= ImageIO.read(new File("C:\\Users\\Desktop\\Encoded.png"));
}
catch (IOException e)
{
e.printStackTrace();
}
for(int i=0;i<image.getWidth();i++)
{
for(int j=0;j<image.getHeight();j++)
{
pixels[i][j]=image.getRGB(i, j);
}
}
for(int i=0;i<Width;i++)
{
for(int j=0;j<Height;j++)
{
temp=pixels[i][j];
int change=0;
for(int k=0;k<4;k++) // 4 iterations for 4bytes of every pixel
{
if(k==0)
{
change=1;
}
else
if(k==1)
{
change=256;
}
else
if(k==2)
{
change=65536;
}
else
if(k==3)
{
change = 16777216;
}
tempText=tempText | (pixels[i][j] & change);
p++;
if(p==8) // because character is of 8bits
{
myString.concat(String.valueOf(tempText));// Writing decoded data in string
p=0;
tempText=0;
}
}
}
// Writing in file
try
{
file = new File("C:\\Users\\Desktop\\Retreive.txt");
fw = new FileWriter(file);
bw= new BufferedWriter(fw);
bw.write(myString);
bw.close();
}
catch (Exception e)
{
e.printStackTrace();
}
Kindly notify me if any mistake I am making or any thing this code is lacking.
String.concat doesn't change the string you call it on, but instead returns a new string. So if you use myString = myString.concat(...) instead, you might get better results. If tempText contains a character code, you could cast it to a char (since String.valueOf returns the string representation of the int):
// Writing decoded data in string
// myString = myString.concat(String.valueOf(tempText));
myString += (char) tempText;
instead of:
myString.concat(String.valueOf(tempText));// Writing decoded data in string