java.io.IOException: closed error in a non-stop loop inside an asynctask - loops

I try to create an asynctask that runs permanently (all the time my app is running). Thay task read every second a file on a server (status.xml).
My problem is that when I execute the app, I have an java.io.IOException: closed exception the second time I do :
reader.read(buffer); // HERE I HAVE AN IOException closed
(first loop is ok, then I have error each loop)
Thanks if someone can help me. I undesrtand the reason of the error, but I cannot find a solution...
Here is my code :
class StatusnAsync extends AsyncTask<Void, Void, Void> {
InputStream in = null;
int responseCode;
void Sleep(int ms) {
try {
Thread.sleep(ms);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
// inits for doInBackground thread
try {
URL url = new URL(address + "/status.xml");
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000 /* milliseconds */);
conn.setConnectTimeout(80000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected Void doInBackground(Void... arg0) {
while (not_end) {
try {
readStatus();
// Sleep 1 sec
Sleep(1000);
} catch (IOException e) {
e.printStackTrace ();
}
}
return null;
}
private void readStatus() throws IOException {
try {
conn.connect();
responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
in = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(in, 340);
// close the inputstream
in.close();
}
} catch (IOException e) {
e.printStackTrace ();
} finally {
if (in != null) in.close();
}
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer); // HERE I HAVE AN IOException closed
return new String(buffer);
}
}
Thank you.

Sorry for my question, I found my error, a stupid error.
Of course I need to openConnection for each GET.
I give the corrected code if it can help someone :
class StatusnAsync extends AsyncTask<Void, Void, Void> {
InputStream in = null;
int responseCode;
URL url;
void Sleep(int ms) {
try {
Thread.sleep(ms);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
// inits for doInBackground thread
try {
url = new URL(address + "/file.xml");
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
#Override
protected Void doInBackground(Void... arg0) {
while (not_end) {
try {
readStatus();
// Sleep 1 sec
Sleep(1000);
} catch (IOException e) {
e.printStackTrace ();
}
}
return null;
}
private void readStatus() throws IOException {
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000 /* milliseconds */);
conn.setConnectTimeout(80000 /* milliseconds */);
conn.connect();
responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
in = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(in, 340);
// close the inputstream
in.close();
}
} catch (IOException e) {
e.printStackTrace ();
} finally {
if (in != null) in.close();
}
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
}

Related

Can Async Task write in internal storage android?

Hi i need to download a file from url and save in internal storage,so the download process run in async task.
First, I have tried to write a string in a file with async task but give me error: Failed to create oat file.
The same code work without task, so my question is i must download the file in external storage and after move in internal?
private void writeInFile() {
FileOutputStream output = null;
String text = "TEXT";
try {
output = openFileOutput("nameFile.abc",Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
output.write(text.getBytes());
output.flush();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
But if i call this function in doInBackground of class that extend AsyncTask i receive the error.
LicenzaTask mt = new LicenzaTask(this);
mt.execute();
public class LicenzaTask extends AsyncTask<Void, Void, Void> {
private Context mContext;
public LicenzaTask(MainActivity mainActivity) {
mContext = mainActivity;
}
#Override
protected Void doInBackground(Void... voids) {
modifyFile();
return null;
}
private void modifyFile() {
File file = new File(mContext.getFilesDir() + "nome.abc");
String text = "text";
BufferedWriter output = null;
try {
output = new BufferedWriter(new FileWriter(file));
output.write(text);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
}
}
}
}

i am trying to autoconnect to bluetooth and return back from bluetooth settings to main activity ?can any one help me?

hello i am trying to autoconnect to bluetooth and return back to main activity,but i am not able to auto connect and return back from current activity to main activty....
Of course if there are more easy ways to do it I would appreciate it very much.
here is code==>
public class SimpleUiActivity extends Activity {
private static final String TAG = SimpleUiActivity.class.getSimpleName();
private static final int RESULT_OK = 1;
private static final int RQS_IMAGE = 2;
private static final int RQS_I = 3;
private BluetoothAdapter BA;
private Map<String, Gpio> mGpioMap = new LinkedHashMap<>();
Button ble;
Button campre;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
LinearLayout gpioPinsView = (LinearLayout) findViewById(R.id.gpio_pins);
LayoutInflater inflater = getLayoutInflater();
PeripheralManagerService pioService = new PeripheralManagerService();
for (String name : pioService.getGpioList()) {
View child = inflater.inflate(R.layout.list_item_gpio, gpioPinsView, false);
Switch button = (Switch) child.findViewById(R.id.gpio_switch);
button.setText(name);
gpioPinsView.addView(button);
Log.d(TAG, "Added button for GPIO: " + name);
try {
final Gpio ledPin = pioService.openGpio(name);
ledPin.setEdgeTriggerType(Gpio.EDGE_NONE);
ledPin.setActiveType(Gpio.ACTIVE_HIGH);
ledPin.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
try {
ledPin.setValue(isChecked);
} catch (IOException e) {
Log.e(TAG, "error toggling gpio:", e);
buttonView.setOnCheckedChangeListener(null);
// reset button to previous state.
buttonView.setChecked(!isChecked);
buttonView.setOnCheckedChangeListener(this);
}
}
});
mGpioMap.put(name, ledPin);
} catch (IOException e) {
Log.e(TAG, "Error initializing GPIO: " + name, e);
// disable button
button.setEnabled(false);
}
//-----------------
ble=(Button)findViewById(R.id.autobluetooth);
ble.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
ble.postDelayed(new Runnable() {
#Override
public void run() {
BA = BluetoothAdapter.getDefaultAdapter();
BA.enable();
Intent intent=new Intent(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
Log.i("aaa","i am here");
// startActivityForResult(intent, RQS_IMAGE);// Activity is started with requestCode 2
finish();
}
}, 10000);
}
});
//-----------------
//-----------------
campre=(Button)findViewById(R.id.camerapreview);
campre.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent1=new Intent(SimpleUiActivity.this,MainActivity.class);
startActivityForResult(intent1, RQS_I);// Activity is started with requestCode 3
}
});
//----------------
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==RESULT_OK) {
switch (requestCode) {
case RQS_IMAGE:
Log.i("abc", "i am here");
Toast.makeText(getApplicationContext(), "Bluetooth switched ON", Toast.LENGTH_LONG).show();
finish();
// textsource.setText(source.toString());
break;
case RQS_I:
break;
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
for (Map.Entry<String, Gpio> entry : mGpioMap.entrySet()) {
try {
entry.getValue().close();
} catch (IOException e) {
Log.e(TAG, "Error closing GPIO " + entry.getKey(), e);
}
}
mGpioMap.clear();
}
}

No value for JSONArray

Problem with JSONArray. This is my code, help me
This is my JsonObject and error..
Json errore: No value for {"Username":"rafyluc","Record":"500"}{"Username":"inkinati","Record":"600"}{"Username":"rafyluc","Record":"500"}{"Username":"inkinati","Record":"600"}
public class ListaAlunni extends AppCompatActivity {
private static ArrayList<Alunni> alunni;
AlunniListAdapter customAdapter;
private String TAG = ListaAlunni.class.getSimpleName();
private static String url = "http://192.168.1.11:80/webservice/lista.php";
ArrayList<HashMap<String, String>> itemList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lista_alunni);
getSupportActionBar().setTitle("Lista Alunni");
alunni = new ArrayList<Alunni>(10);
popola();
}
private void setTextLista() {
ListView ll = (ListView) findViewById(R.id.lista);
ll.setAdapter(new AlunniListAdapter(ListaAlunni.this, R.layout.lista_row, alunni));
}
private void popola() {
new AsyncTask<Object, Object, Object>() {
#Override
protected void onPreExecute() {
alunni = new ArrayList<Alunni>(10);
}
#Override
protected Object doInBackground(Object... params) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d("Debug_object", String.valueOf(jsonObj));
// Getting JSON Array node
// try {
//JSONArray jArray=new JSONArray(jsonStr);
JSONArray jArray = jsonObj.getJSONArray(jsonStr);
Log.d("DEBUG_json", String.valueOf(jArray));
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Log.i("TEST", "Username: " + json_data.getString("Username") +
", record: " + json_data.getString("Record")
);
String nome= json_data.getString("Username");
String record=json_data.getString("Record");
// alunni.add(new Alunni(nome,record));
HashMap<String, String> item = new HashMap<>();
item.put("Username", nome);
item.put("Record", record);
// adding item to item list
itemList.add(item);
}
} catch (final JSONException e) {
Log.e(TAG, "Json errore: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json errore: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Object o) {
setTextLista();
}
}.execute();
}
}
classe HttpHandler:
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Looking at your code, it seems JSONArray jArray = jsonObj.getJSONArray(jsonStr);
is causing the problem.
jsonObj.getJSONArray requires name of the property to be passed E.g. jsonObj.getJSONArray("array_property") but instead, it seems you are passing JSON string.
Also, before calling jsonObj.getJSONArray("array_property") you need to make sure that the array_property exists in the jsonObj

Codenameone closing a socket

There seems to be no way of disconnecting a socket without causing a connection reset error on the server side.
I'm using the com.codename1.io.Socket and com.codename1.io.SocketConnection implementations within a tester app. My code is as follows:
private SpanLabel lblStatus;
private SpanLabel lblIncoming;
private CustomSocketConnection con;
private Thread tIncoming;
public ConnectForm() {
con = getSocketConnection();
Button btnConnect = getConnectButton();
Button btnDisconnect = getDisconnectButton();
Button btnSendMessage = getSendMessageButton();
lblStatus = getInfoLabel();
lblIncoming = getIncomingLabel();
setLayout(new BoxLayout(BoxLayout.Y_AXIS));
addComponent(btnConnect);
addComponent(btnDisconnect);
addComponent(btnSendMessage);
addComponent(lblStatus);
addComponent(lblIncoming);
}
private Button getConnectButton() {
Button btn = new Button("Connect (localhost)");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Socket.connect("localhost", 8687, con);
}
});
return btn;
}
private Button getDisconnectButton() {
Button btn = new Button("Disconnect");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//??? I don't know how to do this
try {
tIncoming.join();
} catch (Exception e) {
e.printStackTrace();
tIncoming.interrupt();
}
}
});
return btn;
}
private Button getSendMessageButton() {
Button btn = new Button("Send Message");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
con.os.write("Hello".getBytes());
con.os.write(Integer.parseInt("04", 16)); //end of transmit
con.os.flush();
lblStatus.setText("Message Sent");
} catch (Exception e) {
e.printStackTrace();
}
}
});
return btn;
}
private SpanLabel getInfoLabel() {
return new SpanLabel("Disconnected");
}
private SpanLabel getIncomingLabel() {
return new SpanLabel("...");
}
private CustomSocketConnection getSocketConnection() {
return new CustomSocketConnection();
}
class CustomSocketConnection extends SocketConnection {
public OutputStream os;
public InputStream is;
#Override
public void connectionError(int errorCode, String message) {
lblStatus.setText("Error Connecting. ErrorCode: " + errorCode + " Message: " + message);
}
#Override
public void connectionEstablished(InputStream is, OutputStream os) {
lblStatus.setText("Connected :)");
this.is = is;
this.os = os;
spawnIncomingMessageWatcher();
}
}
private void spawnIncomingMessageWatcher() {
tIncoming = new Thread(new Runnable() {
public void run() {
String s = "";
int eot = Integer.parseInt("04", 16);
while (con.isConnected()) {
try {
int temp;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (((temp = con.is.read()) != -1) && (temp != eot)) {
baos.write(temp);
}
lblIncoming.setText(new String(baos.toByteArray()));
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
tIncoming.start();
}
With the getDisconnectButton() method, I do not know how to properly disconnect from the server, as the SocketConnection object does not seem to have an appropriate method for this.
If you call close() on either the Input- or OutputStream then you close the Socket, code from Socket.SocketInputStream class link.
public void close() throws IOException {
closed = true;
if(Util.getImplementation().isSocketConnected(impl)) {
Util.getImplementation().disconnectSocket(impl);
con.setConnected(false);
}
}
So first send close instruction to Server and then close a stream.
Hope this helps,

Servlet File concurrency

I have quite a simple question really.
I wrote a servlet for suppliers to upload XML-files to.
These files get written to a location on the server.
All the files get renamed with a timestamp.
Is there a risk of concurrency problems with the code below?
I ask because we receive files from a supplier, that look like
they have content from 2 different XML-files
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
public String getServletInfo() {
return "Short description";
}// </editor-fold>
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
File dirToUse;
boolean mountExists = this.getDirmount().exists();
if (!mountExists) {
this.log("MOUNT " + this.getDirmount() + " does not exist!");
dirToUse = this.getDiras400();
} else {
dirToUse = this.getDirmount();
}
boolean useSimpleRead = true;
if (request.getMethod().equalsIgnoreCase("POST")) {
useSimpleRead = !ServletFileUpload.isMultipartContent(request);
}
if (useSimpleRead) {
this.log("Handle simple request.");
handleSimpleRequest(request, response, dirToUse);
} else {
this.log("Handle Multpart Post request.");
handleMultipart(request, response, dirToUse);
}
}
protected void handleMultipart(HttpServletRequest request,
HttpServletResponse response, File dir) throws IOException,
ServletException {
try {
FileItemFactory fac = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fac);
List<FileItem> items = upload.parseRequest(request);
if (items.isEmpty()) {
this.log("No content to read in request.");
throw new IOException("No content to read in request.");
}
boolean savedToDisk = true;
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
getFilename(request);
File diskFile = new File(dir, this.getFilename(request));
item.write(diskFile);
if (!diskFile.exists()) {
savedToDisk = false;
}
}
if (!savedToDisk) {
throw new IOException("Data not saved to disk.");
}
} catch (FileUploadException fue) {
throw new ServletException(fue);
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
protected void handleSimpleRequest(HttpServletRequest request,
HttpServletResponse response, File dir) throws IOException {
// READINPUT DATA TO STRINGBUFFER
InputStream in = request.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuffer sb = new StringBuffer();
String line = reader.readLine();
while (line != null) {
sb.append(line + "\r\n");
line = reader.readLine();
}
if (sb.length() == 0) {
this.log("No content to read in request.");
throw new IOException("No content to read in request.");
}
//Get new Filename
String newFilename = getFilename(request);
File diskFile = new File(dir, newFilename);
saveDataToFile(sb, diskFile);
if (!diskFile.exists()) {
throw new IOException("Data not saved to disk.");
}
}
protected abstract String getFilename(HttpServletRequest request);
protected void saveDataToFile(StringBuffer sb, File diskFile) throws IOException {
BufferedWriter out = new BufferedWriter(new FileWriter(diskFile));
out.write(sb.toString());
out.flush();
out.close();
}
getFileName implementation:
#Override
protected String getFilename(HttpServletRequest request) {
Calendar current = new GregorianCalendar(TimeZone.getTimeZone("GMT+1"));
long currentTimeMillis = current.getTimeInMillis();
System.out.println(currentTimeMillis);
return "disp_" + request.getRemoteHost() + "_" + currentTimeMillis + ".xml";
}
Anyway, thanks in advance!
There would not be synchronization problems but there can be race conditions, for example, two threads might return the same file name using the method getFileName()

Resources