Read all lines from BufferedReader before continuing - android

I am having a bit of an issue with my app. I receive a data through a socket, via a BufferedReader. I loop round with while ((sLine = reader.readLine ()) != null) and append the sLine to a StringBuilder object. I also spend a new line \n to the builder.
The plan is that once the builder is all finished, String sTotal = builder.toString()is called and a total is passed to the next routine.
However, the next routine is instead being called once for each line rather than with the string as a whole. The routine call is outside the loop above so I really don't know why!
Hope someone can help...
Edit: Code extract below.
public void run() {
try {
oServerSocket = new ServerSocket(iPort);
while ((!Thread.currentThread().isInterrupted()) && (!bStopThread)) {
try {
oSocket = oServerSocket.accept();
this.brInput = new BufferedReader(new InputStreamReader(this.oSocket.getInputStream()));
StringBuilder sbReadTotal = new StringBuilder();
String sReadXML = "";
while ((sReadXML = brInput.readLine()) != null) {
sbReadTotal.append("\n");
sbReadTotal.append(sReadXML);
}
sReadXML = sbReadTotal.toString();
Log.d("XMLDATA", sReadXML);
processXML(sReadXML);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
/* Nothing Yet */
e.printStackTrace();
}
}

If you're exiting your internal while loop, it means you reached the end of your input stream (that's when readLine() returns null according to the docs).
You should be looking into the client, and not the server. What's establishing the client socket? Are you sure it's not establishing a separate connection for each line it sends?

Related

Reading a large text file with over 130000 line of text

How can i read a large text file into my Application?
This is my code but it does not work. My code must read a file called list.txt. The code worked only with a file with only 10.000 lines.
can someone helps me?
Thanks!
My code:(Worked with small files, but not with large files)
private void largefile(){
String strLine2="";
wwwdf2 = new StringBuffer();
InputStream fis2 = this.getResources().openRawResource(R.raw.list);
BufferedReader br2 = new BufferedReader(new InputStreamReader(fis2));
if(fis2 != null) {
try {
LineNumberReader lnr = new LineNumberReader(br2);
String linenumber = String.valueOf(lnr);
while ((strLine2 = br2.readLine()) != null) {
wwwdf2.append(strLine2 + "\n");
}
// Toast.makeText(getApplicationContext(), linenumber, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), wwwdf2, Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Since you are processing a large file, you should process the data in chunks . Here your file reading is fine but then you keep adding all rows in string buffer and finally passing to Toast.makeText(). It creates a big foot-print in memory. Instead you can read 100-100 lines and call Toast.makeText() to process in chunks. One more thing, use string builder instead of string buffer go avoid unwanted overhead of synchronization. You initializing wwwdf2 variable inside the method but looks it is a instance variable which I think is not required. Declare it inside method to make it's scope shorter.

Load simple JSON file into 2 dimensional Array in Android

Driving myself crazy over the simplest thing. I have a JSON file called config.txt. The file is shown below.
{
"UsePipesInGuestData": true
}
All I want to do is get a 2 dimensional array such that:
Array[0] = UsePipesInGuestData and
Array[1] = true
I have been trying for 4 hours with various attempts, my most recent is shown below:
private void getConfig(){
//Function to read the config information from config.txt
FileInputStream is;
BufferedReader reader;
try {
final File configFile = new File(Environment.getExternalStorageDirectory().getPath() + "/guestlink/config.txt");
if (configFile.exists()) {
is = new FileInputStream(configFile);
reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
while (line != null) {
line = reader.readLine();
if(line!= null) {
line = line.replace("\"", ""); //Strip out Quotes
line = line.replace(" ", ""); //Strip out Spaces
if ((!line.equals("{")) || (!line.equals("}"))) {
} else {
String[] configValue = line.split(":");
switch (configValue[0]) {
case "UsePipesInGuestData":
if (configValue[1].equals("true")) {
sharedPreferences.edit().putString("UsePipes", "true").apply();
} else {
sharedPreferences.edit().putString("UsePipes", "false").apply();
}
break;
}
}
}
}
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I cannot seem to ignore the lines with the { and } in them.
Clearly there MUST be an easier way. JAVA just seems to take an extremely large amount of code to do the simplest thing. Any help is greatly appreciated.
I believe your condition is incorrect. You try to read the file in the else of the condition (!line.equals("{")) || (!line.equals("}")). Simplifying, your code will run when the following happens:
!(!{ || !}) => { && } (applying De Morgan's law)
This means you will only run your code when the line is "{" AND it is "}" which is a contradiction. Try using simple conditions, like (!line.equals("{")) && (!line.equals("}")) (this is when you want to execute your code).
Additionally, you may be getting end of line characters (\n) in your string, which will make your condition fail ("{\n" != "{"). I suggest you debug and see the actual values you're getting in those lines.

Get actual time from internet ?

How to get 'current(actual) time' or 'network operator's time' programmatically if device time is changed ?
I'm trying to get current time through 'getLastKnownLocation' method of 'LocationManager' class. But it gives last location time, but I need current time.
Can anyone tell me a clue about the correct way to get actual time from internet ?
If possible without using any external library.
Thanks in advance.
According to this answer you can get the current time from an NTP server.
support.ntp.org library
Add to your dependency
String timeServer = "server 0.pool.ntp.org";
NTPUDPClient timeClient = new NTPUDPClient();
InetAddress inetAddress = InetAddress.getByName(timeServer);
TimeInfo timeInfo = timeClient.getTime(inetAddress);
long returnTime = timeInfo.getReturnTime();
System.out.println(returnTime)
You can use a rest full api provided by geo names http://www.geonames.org/login it will require lat and long for this purpose for example
http://api.geonames.org/timezoneJSON?lat=51.5034070&lng=-0.1275920&username=your_user_name
For Android:
Add to gradle app module:
compile 'commons-net:commons-net:3.3'
Add to your code:
...
String TAG = "YOUR_APP_TAG";
String TIME_SERVER = "0.europe.pool.ntp.org";
...
public void checkTimeServer() {
try {
NTPUDPClient timeClient = new NTPUDPClient();
InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
TimeInfo timeInfo = timeClient.getTime(inetAddress);
long setverTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();
// store this somewhere and use to correct system time
long timeCorrection = System.currentTimeMillis()-setverTime;
} catch (Exception e) {
Log.v(TAG,"Time server error - "+e.getLocalizedMessage());
}
}
NOTE: timeInfo.getReturnTime() as mentioned in an earlier answer will get you local system time, if you need server time you must use timeInfo.getMessage().getTransmitTimeStamp().getTime().
Getting the time from the third-party servers is not reliable most of the times and some of them are paid services.
If you want to get the exact time and check with the phone whether it is correct or not, irrespective of the proper way, you can use the following simple trick to get the actual time.
private class GetActualTime extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
try {
HttpURLConnection urlConnection = null;
StringBuilder result = new StringBuilder();
try {
URL url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
if (code == 200) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = bufferedReader.readLine()) != null)
result.append(line);
in.close();
}
else {
return "error on fetching";
}
return result.toString();
} catch (MalformedURLException e) {
return "malformed URL";
} catch (IOException e) {
return "io exception";
} finally {
if (urlConnection != null) {urlConnection.disconnect();
}
}
} catch (Exception e) { return "null"; }
}
#Override
protected void onPostExecute(String time) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("h:mm");
String times = mdformat.format(calendar.getTime());
try {
String areatime = time.substring(time.indexOf(String.valueOf(times)), time.indexOf(String.valueOf(times)) + 5).trim();
Toast.makeText(this, "The actual time is " + areatime, Toast.LENGTH_SHORT).show();
}
catch(IndexOutOfBoundsException e){
Toast.makeText(this, "Mobile time is not same as Internet time", Toast.LENGTH_SHORT).show();
}
}
}
}
Call the class in the onCreate();
new GetActualTime().execute("https://www.google.com/search?q=time");
So this is actually getting the time from Google. This works pretty awesomely in my projects. In order to check whether the system time is wrong, you can use this trick. Instead of depending on the time servers, you can trust Google.
As it is more sensitive in checking, even a minute ahead or lag will catch the exception. You can customise the code if you want to handle that.
Try this :
System.currentTimeMillis();

Strange behaviour when receiving data

I'm developing an Android app that requires me to get some data from the server, this data is comes as JSON data, I have to receive like 7 JSON Objects, I'm using regular socket programming to get this data, and I get it by launching a thread that will wait for a data to come from the server.
I'm using the following method:
public String getServerRespons() throws JSONException {
String responseLine, server_response = null_string;
try {
input = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
} catch (IOException e) {
}
int count = 0;
boolean first = true;
try {
while (true)
{
if((responseLine = input.readLine()) == null){
break;
}
first = false;
server_response = server_response + responseLine;
//
// some processing to make sure it's a valid JSON
//
if(count == 0){ // related to the Processing Lines result
System.out.println(server_response);
return response; // when commenting that line everything is ok
}
}
} catch (IOException e) {
Login.errorMessage.setText(conn_err);
}
return null;
}
With that way i got like only two or three JSON Objects of the seven ones. BUT, when commenting the return Line and let it completes with the receiving process I got all the seven Objects efficiently and each Object is separated which makes me make sure that the processing i made to validate the JSON is going so well.
I think int count is always 0 in your example so the return statement is always hit.

android bluetooth application unresponsive during phone call

I have an application which communicates with a bluetooth device via async task
if I receive a phone call and during the call I return to the app
the screen dims and the application is unresponsive
back button doesn't work... and no ANR dialog is shown
any ideas?
here is the code which handles the connection:
#Override
protected Object doInBackground(Object... params) {
//boolean protocolUpdated;
int read = 0; // The amount of bytes read from the socket.
byte[] buff = new byte[MessageHandler.BUFFERSIZE]; // The data buffer.
byte[] tmpSend = null; // Misc bytes arrays returned from ProtocolParser as answers to send after decoding calls.
in = null;
out = null;
try {
if (Float.parseFloat(version) > 2.2){
Method m = dev.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
sock = (BluetoothSocket) m.invoke(dev, 1);
}
else sock = dev.createRfcommSocketToServiceRecord(UUID_RFCOMM_GENERIC); // UUID is constant for serial BT devices.
sock.connect(); // connect to the BT device. This is rather heavy, may take 3 secs.
sendMessage(MESSAGE_CONNECTION_ESTABLISHED);
in = sock.getInputStream();
out = sock.getOutputStream();
timer = new Timer();
startFinishTimer(); //initialize finish timer
while(read != -1) { // read = -1 means EOF.
do { // as long as there is anything to send in the send queue - send it.
tmpSend = parser.nextSend();
if(tmpSend != null){
String msg = parseMessage(tmpSend);
Log.d("Writing:",msg);
out.write(tmpSend);
}
} while(tmpSend != null);
read = in.read(buff); // read. This is a blocking call, to break this, interrupt the thread.
timer.cancel();
startFinishTimer(); //read is a blocking call so timer should be restarted only after read bytes.
parser.parse(buff,read); // parse the read message using the logic in the ProtocolParser derived class.
tmpSend = parser.getPool(); // if pool ack is required - send it.
if (tmpSend != null){
Log.d("Writing:",parseMessage(tmpSend));
out.write(tmpSend);
}
if (read != 0){
Log.d("Read:",parseMessage(buff));
tmpSend = parser.getAnswer(); // if answer is required (based on message) - send it.
if(tmpSend != null){
out.write(tmpSend);
}
}
else {
Exception e = new IOException();
throw e;
}
}
}catch (IOException e){
e.printStackTrace();
Log.d("Connection: ", "Bluetooth Connection CRASHED!");
sendMessage(MESSAGE_CONNECTION_LOST);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
Actually there is not enough context to find your problem.
Make sure that you launch this task from Main thread in other case PostExecute will be attached to wrong thread, you could get a race.
Make sure that you don't send same message to multiple handlers in your code.
Message it's a linked list and your could get ANR in that case.
Get /data/anr/traces.txt to make sure that it's not ANR.
You could make sure by time in the beginning of the file.

Categories

Resources