How to concatenate long String in StringBuffer for Android - android

I am facing one problem in StringBuffer concatination for appending large characters of String from JSONArray.
My data is huge and it is coming in log after iteration of 205 indexes of Array properly
but when I am appending each row String in StringBuffer or StringBuilder from JSONArray, so it is taking on 4063 characters only not appending all characters present in JSON Array but iteration doesn't break and goes till complete 204 rows.
String outputFinal = null;
try {
StringBuilder cryptedString = new StringBuilder(1000000);
JSONObject object = new JSONObject(response);
JSONArray serverCustArr = object.getJSONArray("ServerData");
Log.d("TAG", "SurverCust Arr "+serverCustArr.length());
for (int i = 0; i < serverCustArr.length(); i++) {
String loclCryptStr = serverCustArr.getString(i);
Log.d("TAG", "Loop Count : "+i);
cryptedString.append(loclCryptStr);
}
Log.d("TAG", "Output :"+cryptedString.toString());
CryptLib _crypt = new CryptLib();
String key = this.preference.getEncryptionKey();
String iv = this.preference.getEncryptionIV();
outputFinal = _crypt.decrypt(cryptedString.toString(), key,iv); //decrypt
System.out.println("decrypted text=" + outputFinal);
} catch (Exception e) {
e.printStackTrace();
}
My JSONArray contacts 119797 characters in 205 and after iteration for appending in StringBuffer, I have to decrypt it with library that takes string for decryption. But StringBuffer is not having complete data of 119797 characters.
And Exception is because string is not complete, I am enclosing files on link below for reference and also using cross platform CryptLib uses AES 256 for encryption easily find on Github
3 Files With Original and Logged text

Dont use StringBuffer , instead use StringBuilder ..here's the detailed Explaination
http://stackoverflow.com/questions/11908665/max-size-for-string-buffer
Hope this helps. :)
EDIT
this is the code that i used to read whole string ...
public void parseLongString(String sourceFile, String path) {
String sourceString = "";
try {
BufferedReader br = new BufferedReader(new FileReader(sourceFile));
// use this for getting Keys Listing as Input
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
br.close();
sourceString = sb.toString();
sourceString = sourceString.toUpperCase();
System.out.println(sourceString.length());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File file = new File(path);
FileWriter fileWriter = null;
BufferedWriter bufferFileWriter = null;
try {
fileWriter = new FileWriter(file, true);
bufferFileWriter = new BufferedWriter(fileWriter);
} catch (IOException e1) {
System.out.println(" IOException");
e1.printStackTrace();
}
try {
fileWriter.append(sourceString);
bufferFileWriter.close();
fileWriter.close();
} catch (IOException e) {
System.out.println("IOException");
e.printStackTrace();
}
}
and this is outPut file where i am just converting it to uppercase .
https://www.dropbox.com/s/yecq0wfeao672hu/RealTextCypher%20copy_replaced.txt?dl=0
hope this helps!
EDIT 2
If u are still looking for something ..you can also try STRINGWRITER
syntax would be
StringWriter writer = new StringWriter();
try {
IOUtils.copy(request.getInputStream(), writer, "UTF-8");
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String theString = writer.toString();

Related

reading Text from file in assets

i have an text file in my assets folder called test.txt. It contains a string in the form
"item1,item2,item3
How do i read the text into and array so that I can then toast any one of the three items that are deliminated by a comma
After reading post here the way to load the file is as follows
AssetManager assetManager = getAssets();
InputStream ims = assetManager.open("test.txt");
But cant work out how to get into an array
your help is appreciated
Mark
This is one way:
InputStreat inputStream = getAssets().open("test.txt");
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String[] myArray = TextUtils.split(byteArrayOutputStream.toString(), ",");
Here is a sample code :
private void readFromAsset() throws UnsupportedEncodingException {
AssetManager assetManager = getAssets();
InputStream is = null;
try {
is = assetManager.open("your_path/your_text.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String line = "";
try {
while ((line = reader.readLine()) != null) {
//Read line by line here
}
} catch (IOException e) {
e.printStackTrace();
}
}

Parsing SHOUTcast 7.html metadata on Android

I am trying to check the status of a SHOUTcast stream using this URL:
http://85.17.167.136:8684/7.html
... which returns data like:
<HTML><meta http-equiv="Pragma" content="no-cache"></head><body>7,1,77,100,7,128,+44(0)7908 340 811 Follow Us #visionradiouk</body></html>
I know that the after the first comma returns 1 if the stream is up and running or returns 0 if the stream is down. My problem is getting the html of that page? I use this code, which works on other websites like Google etc.
TextView tView = (TextView) findViewById(R.id.textView1);
String htmlCode = "";
try {
URL url = new URL("http://85.17.167.136:8684/7.html");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine())!= null)
htmlCode += inputLine;
System.out.println(htmlCode);
tView.setText(htmlCode);
in.close();
} catch (Exception e){
System.out.println("error");
}
}
Any ideas on what I am doing wrong?
Heres Pulsarman325's working solution, tidied up, with a little extra stuff i had to add to get it to work (try/catch and variable initialisations)
String url = "http://molestia.ponify.me:8062";
URL url2=null;
try
{
url2 = new URL(url + "/7.html");
}
catch (MalformedURLException e1)
{
e1.printStackTrace();
}
URLConnection con=null;
try
{
con = url2.openConnection();
}
catch (IOException e1)
{
e1.printStackTrace();
}
con.setRequestProperty("User-Agent", "Mozilla/5.0");
Reader r = null;
try
{
r = new InputStreamReader(con.getInputStream());
}
catch (IOException e)
{
e.printStackTrace();
}
StringBuilder buf = new StringBuilder();
int ch=0;
while (true)
{
try
{
ch = r.read();
}
catch (IOException e)
{
e.printStackTrace();
}
if (ch < 0)
break;
buf.append((char) ch);
}
String str = buf.toString();
String trackinfo = str.split(",")[6].split("</body>")[0];
Log.d("HTML", trackinfo);

Append data in Json file

I have this type of JSON:
{
"stampi":
[
{
"nome": "Ovale Piccolo 18.2x13.5cm",
"lunghezza": 18.2,
"larghezza": 13.5,
"altezza": 4,
"volume": 786.83
},
{
"nome": "Ovale Grande 22.5x17.4cm",
"lunghezza": 22.5,
"larghezza": 17.4,
"altezza": 4,
"volume": 1246.54
}
]
}
and normally I read with this code:
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open("stampi.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
myjson_stampi = sb.toString();
and after use the array inside the program.
I have create a menu that add new value inside the JSON file but i have a problem ...this is the code:
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open("stampi.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
myjson_stampi = sb.toString();
try {
// Creating JSONObject from String
JSONObject jsonObjMain = new JSONObject(myjson_stampi);
// Creating JSONArray from JSONObject
JSONArray objNames = jsonObjMain.names();
System.out.println(objNames.toString());
jsonArray_stampi = jsonObjMain.getJSONArray("stampi");
int num_elem = jsonArray_stampi.length();
jsonObjMain.put( "nome","prova");
jsonObjMain.put( "lunghezza",22);
jsonObjMain.put( "larghezza", 10);
jsonObjMain.put( "altezza", 4);
jsonObjMain.put( "volume", 10.5);
jsonArray_stampi.put( jsonObjMain );
try {
FileWriter file = new FileWriter("c:\\test.json");
//file.write(jsonArray_stampi.);
file.write( JSON.stringify(jsonArray_stampi) );
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} });
why can't work correctly?
the num_elem variable are 2 always..help me!
thx Andrea
You have to create a new JSONObject and then add new data to it and then append to the existing object.
JSONObject jsonObjMain = new JSONObject(myjson_stampi); //Your existing object
JSONObject jO = new JSONObject(); //new Json Object
JSONArray jsonArray_stampi = jsonObjMain.getJSONArray("stampi"); //Array where you wish to append
//Add data
jO.put( "nome","prova");
jO.put( "lunghezza",22);
jO.put( "larghezza", 10);
jO.put( "altezza", 4);
jO.put( "volume", 10.5);
//Append
jsonArray_stampi.put(jO);
Also you should write back the complete jsonObject back to the file.
file.write(JSON.stringify(jsonObjMain));
Looks like you're trying to write to a file called c:\\test.json. Try using the proper Android way to write to files with openFileOutput. Examples are here.
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}

Extracting data from server takes too much time- android

I have a android application, where i extract data from the multiple urls and save then as arraylist of string. It works fine, but for fetching data from 13 urls, it takes close to 15-20 sec. Where as fetching the data from same set of urls take 3-4 sec in same app built using phonegap. Here is the code below.
#Override
protected String doInBackground(String... params) {
client = new DefaultHttpClient();
for(int i=0;i<url.size();i++)
{
get = new HttpGet(url.get(i));
try {
response = client.execute(get);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
entity = response.getEntity();
InputStream is = null;
try {
is = entity.getContent();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line = null;
do {
try {
line = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
buffer.append(line);
} while (line != null);
String str = buffer.toString();
param.add(str);
}
return null;
}
Could anyone please suggest how i can speed this execution and reduce the extraction time.
You could try starting a separate thread for each iteration from the for loop.
Smth like this :
for(int i = 0; i < url.size(); i++){
//start thread that gets data from url and adds it to the list
}

Android HttpEntity object... Best ways to reuse it?

I'm having a software who is doing a http GET request and then I am receiving an HttpEntity response.
This is fine to me. The problem is that I want to use read this response 2 times and I dont know which way is the best.
If I convert the entity to a string, then when I try to access again the entity, Im getting an exception that the entity has been consumed.
If I try to use the getContent method to use the InputStream I dont find a way to reread the inputStream 2 times as i need.
Can someone tell me how I can save the httpEntity result as a way I can reuse it twice ?? Shoud I create a file ? How I do that ? What about performance to write a file each time I do a GET ? How to delete that file on each call ? Where to save the file ?
If you have any other ideas, thanks for the help.
I will appreciate code examples.
I finally found how to convert a stream to a string so I did the following thing :
//Get the answer from http request
if(httpResponse!=null)
entity = httpResponse.getEntity();
else
entity = null;
//Display the answer in the UI
String result;
if (entity != null) {
//First, Open a file for writing
FileOutputStream theXMLFile=null;
try{
theXMLFile=openFileOutput("HttpResponse.dat", MODE_PRIVATE);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("ResultService Exception :", e.getMessage());
}
try {
if(theXMLFile!=null) {
//Save the stream to a file to be able to re read it later.
entity.writeTo(theXMLFile);
//Entity is consumed now and cannot be reuse ! Lets free it.
entity=null;
//Now, lets read this file !
FileInputStream theXMLStream=null;
try {
//Open the file for reading and convert to a string
theXMLStream = openFileInput("HttpResponse.dat");
result=com.yourutilsfunctionspackage.ServiceHelper.convertStreamToString(theXMLStream);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("ResultService Exception :", e.getMessage());
result=null;
}
theXMLStream.close();
theXMLStream=null;
//Use the string for display
if(result!=null)
infoTxt.setText(getText(R.string.AnswerTitle) + " = " +result);
try {
//Reopen the file because you cannot use a FileInputStream twice.
theXMLStream = openFileInput("HttpResponse.dat");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("ResultService Exception :", e.getMessage());
}
//Re use the stream as you want for decoding xml
if(theXMLStream!=null){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder=null;
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(builder!=null)
{
Document dom=null;
try {
dom = builder.parse(theXMLStream);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(dom!=null){
Element racine = dom.getDocumentElement();
NodeList nodeLst=racine.getElementsByTagName("response");
Node fstNode = nodeLst.item(0);
if(fstNode!=null){
Element fstElmnt = (Element) fstNode;
String CallingService=fstElmnt.getAttribute("service");
etc....
//Function taken from internet http://www.kodejava.org/examples/266.html
public static String convertStreamToString(InputStream is) throws IOException {
/*
* To convert the InputStream to String we use the
* Reader.read(char[] buffer) method. We iterate until the
* Reader return -1 which means there's no more data to
* read. We use the StringWriter class to produce the string.
*/
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
return writer.toString();
} else {
return null;
}
}

Categories

Resources