In my code,first I access an address and I got the text file. In that, there are many picture links, such as http://dnight-math.stor.sinaapp.com/%E5%9C%B0%E7%90%861_img004.jpg. I use regular expression to find all the links to make a arraylist. Then I use downloadService to download all the pictures. When I first press a button to download ,it can run successfully. But it doesn't work if the button is pressed again and throws error. I think this bug is about thread but I don't know how to solve it.
HttpUtil.sendHttpRequest(address,
new HttpCallbackListener() {
#Override
public void onFinish(String response) {
try {
ArrayList<String> urlList = new ArrayList<>();
Pattern p = Pattern.compile("http:.*?.com/(.*?.(jpg|png))");
Matcher m = p.matcher(response);
StringBuffer buffer = new StringBuffer();
while (m.find()) {
m.appendReplacement(buffer, "<T>" + + m.group(1) + "</T>");
urlList.add(m.group());
}
m.appendTail(buffer);
response = buffer.toString();
Message m2 = Message.obtain();
m2.obj = response;
m2.what = 1;
mHandler.sendMessage(m2);
new DownloadService("/data/data/com.baodian/files",
urlList,
new DownloadStateListener() {
#Override
public void onFinish() {
}
#Override
public void onFailed() {
}
}, context).startDownload();
;
// JSONObject singleChoice=all.getjson
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onError(Exception e) {
}
});
public class HttpUtil {
public static void sendHttpRequest(final String address,
final HttpCallbackListener listener) {
new Thread(new Runnable() {
#Override
public void run() {
HttpURLConnection connection=null;
try {
URL url=new URL(address);
connection=(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setDoInput(true);
connection.setDoOutput(true);
InputStream in=connection.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(in,"gbk"));
StringBuilder response=new StringBuilder();
String line=null;
while ((line=reader.readLine())!=null) {
response.append(line);
}
if (listener!=null) {
listener.onFinish(response.toString());
}
} catch (Exception e) {
if (listener != null) {
listener.onError(e);
}
}
}
}).start();
}
}
If you look at SimY4's answer here,
he says that the error you're getting "means the thread pool is busy and queue is full as well".
What you currently do is call onFailed when you encounter the error. What you can do is implement
a supplementary enqueing scheme. You can cache the newer urls until the thread queue has space, create and enqueue
the new threads at that point.
The following thread might prove useful : Java executors: how to be notified, without blocking, when a task completes?
Related
I am reading an RSS newsfeed and want to check if the calling App has been cancelled/stopped (eg device rotated). Most RSS feeds have a loop in them which allows a statement in the loop to check for isCancelled(). I am using what is described as a Simplified SAX read. There is no loop. I call the parse, and have handlers for different items. I have one of them, (end Element) to check for isCancelled().
I get "unhandled exception: org.xml.sax.SAXException", on the red underlined throw statement. It will not compile.
I have tried as many combinations as I can think of where the try/catch statements go, and putting in the org.xml.sax.
I presume one option I have is to use one of teh RSS feed read options that has a loop, but if possible, I would like to use this simplified SAX read as it is supposed to be the most efficient.
public ArrayList<FeedItem> GetWithSimplifiedSax(String theUrl)
throws SAXException {
try {
url= new URL(theUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream inputStream = connection.getInputStream();
final FeedItem currentItem = new FeedItem();
RootElement root = new RootElement("rss");
final ArrayList<FeedItem> feedItems = new ArrayList<>();
android.sax.Element channel = root.getChild("channel");
android.sax.Element item = channel.getChild("item");
item.setEndElementListener(new EndElementListener(){
public void end() {
feedItems.add(currentItem.myCopy());
if(isCancelled()){
throw new SAXException("cancel");
//<<DOES NOT LIKE ABOVE LINE
// *** Gives unhandled exception:org.xml.sax.SAXException
}
}
});
item.getChild("title").setEndTextElementListener(new EndTextElementListener(){
public void end(String body) {
currentItem.setTitle(body);
}
});
item.getChild("link").setEndTextElementListener(new EndTextElementListener(){
public void end(String body) {
currentItem.setLink(body);
}
});
item.getChild("description").setEndTextElementListener(new EndTextElementListener(){
public void end(String body) {
currentItem.setDescription(body);
}
});
item.getChild("pubdate").setEndTextElementListener(new EndTextElementListener(){
public void end(String body) {
currentItem.setPubDate(body);
}
});
try {
Xml.parse(inputStream, Xml.Encoding.UTF_8, root.getContentHandler());
} catch(SAXException e){
Log.e("SAX", e.getMessage());
return null;
}
return feedItems;
} catch ( IOException e) {
Log.e("MYERROR", e.getMessage());
//e.printStackTrace();
return null;
} //catch (org.xml.sax.SAXException e) {
// Log.e("SAX", e.getMessage());
// //e.printStackTrace();
// return null;
//} //try catch
} //method: public ... simplified SAX
I added in the MainActivity a button click event:
public void addListenerOnButton()
{
btnClick = (Button) findViewById(R.id.checkipbutton);
btnClick.setOnClickListener(new OnClickListener()
{
byte[] response = null;
#Override
public void onClick(View arg0)
{
text = (TextView) findViewById(R.id.textView2);
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
for (int i = 0; i < ipaddresses.length; i++)
{
try
{
response = Get(ipaddresses[i]);
break;
} catch (Exception e)
{
text.setText("Connection Failed");
}
}
if (response!=null)
{
String a = null;
try
{
a = new String(response,"UTF-8");
text.setText(a);
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
Logger.getLogger("MainActivity(inside thread)").info(a);
}
}
});
t.start();
}
});
}
I wanted to create a break when it's entering the try block after doing the response = Get(ipaddresses[i]); in order to stop the for loop.
The problem is that after it's done the response = Get(ipaddresses[i]); when it's supposed to be doing the break, my program crashes.
On the android device I get the message:
unfortunately myapp has stopped
And when I click ok on the message the program just closes.
I can't figure out why the break makes the program crash.
This is the Get method:
private byte[] Get(String urlIn)
{
URL url = null;
String urlStr = urlIn;
if (urlIn!=null)
urlStr=urlIn;
try
{
url = new URL(urlStr);
} catch (MalformedURLException e)
{
e.printStackTrace();
return null;
}
HttpURLConnection urlConnection = null;
try
{
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
byte[] buf=new byte[10*1024];
int szRead = in.read(buf);
byte[] bufOut;
if (szRead==10*1024)
{
throw new AndroidRuntimeException("the returned data is bigger than 10*1024.. we don't handle it..");
}
else
{
bufOut = Arrays.copyOf(buf, szRead);
}
return bufOut;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
finally
{
if (urlConnection!=null)
urlConnection.disconnect();
}
}
The reason for the crash is most likely apparent from the stacktrace that you haven't shown us.
But the logic of that loop is pretty dubious ... to me.
Without the break, the loop iterates over all of the IP addresses, and tries Get on each one. At the end, response will be the last value returned by a Get call, which may or may not be null.
With the break, the loop terminates after the first IP address for which Get doesn't throw an exception ... irrespective of what the Get call returns. (That could be null.)
These could be the cause of your crash, but it could be something else. Either way, the logic is suspicious. (And calling a method Get is bad style!)
UPDATE
Given that the Get method catches exceptions and returns null on failure, the recommended structure for the code that calls it is:
for (int i = 0; i < ipaddresses.length; i++) {
response = Get(ipaddresses[i]);
if (response != null) {
break;
}
}
if (response == null) {
// notify connection failed
} else {
// process response
}
There is not need for a "belt and braces" try {...} catch in the calling code ... if you have already dealt with the expected exceptions in Get. And (IMO) you should (almost) never catch Exception, because that is liable to conceal bugs.
I recently started learning android development (am new to java as well) and I am currently working on a chat/messenger application
The problem I am facing, as the title says, is that the listview in which the messages are shown does not update on the device, unless scrolled, but it works fine on the virtual machine. I only tested on LG Optimus l5 II so far, but i need to fix this anyway.
I think it has something to do with multithreading, because this didn't happen until i added some new threads, so the adapter for listview, android manifest and rest I say are set up correctly. I can add them if it helps.
The 2 threads i added that might cause this:
Checks the connection status and if disconnected tries to reconnect.
The thread used for communicating with the server.
I tested running only with the second thread on, and the problem still occurs.
I want to specify this is the first time I try something like this (servers-client, multithreading, java, android (I'm still in college and they don`t teach us these kinds of stuff there) ), and had no documentation ahead regarding how I should set up the communication between the server and the client. This is the most efficient way I could think of.
this is at the end of onCreate:
StartConnectingRoutine(); // so you know where it all starts
and the code for it:
private void StartConnectingRoutine()
{
Thread t = new Thread()
{
#Override
public void run()
{
while(true)
{
if(!connected)
{
if( connect != null)
{
if(!connect.isAlive())
{
ConnectListener();
}
}
else
{
ConnectListener();
}
}
try {
sleep(CONNECTION_CHECK_TIME_MS); // this is set to 10000 (10 seconds)
} catch (InterruptedException e) {
Log.e("Intrerrupted", e.toString());
}
}
}
};
t.start();
}
and the connectListener():
private void ConnectListener()
{
Log.d("Connecting", "Connecting...");
connect = new Thread()
{
JSONObject info = new JSONObject();
String receivedMessage;
#Override
public void run()
{
try {
info.put("Name", user.GetName());
info.put("PORT", MY_PORT);
info.put("IPv4", getIpAddress());
} catch (JSONException e1) {
Log.e("JSON", "JSON error: " + e1.toString());
}
try
{
ServerSocket = new Socket(SERVER_IP, SERVER_PORT);
dis = new DataInputStream(ServerSocket.getInputStream());
dos = new DataOutputStream(ServerSocket.getOutputStream());
dos.writeUTF(info.toString());
dos.flush();
String response = dis.readUTF();
if(response.equals("connected"))
{
Log.d("Connect", "Connected!");
connected = true;
}
else
Log.d("Connect", "Failed to connect!");
while(connected)
{
receivedMessage = dis.readUTF();
DisplayNewMessage(new MMessage(receivedMessage, MMessage.MessageType.Received));
}
}catch(SocketException e)
{
try {
if(connected)
{
ServerSocket.close();
dis.close();
dos.close();
connected = false;
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
catch(Exception e)
{
Log.d("Connect", "Failed to connect");
Log.e("Connect", e.toString());
connected = false;
}
}
};
connect.start();
}
Fixed:
Reconnecting thread (i tried using asyncTask for this too, but it wouldn`t open the other asyncTask, even if I tried to open it from onProgressUpdate()-which it is supposed to be able to run ui thread components):
private void startConnectingRoutine()
{
Thread t = new Thread()
{
#Override
public void run()
{
Log.d("ConnectingRoutine", "Started connecting routine.");
while(true)
{
if(!connected)
{
startListener();
}
try {
sleep(CONNECTION_CHECK_TIME_MS);
} catch (InterruptedException e) {
Log.e("Intrerrupted", e.toString());
}
}
}
};
t.start();
}
Listener thread:
private void startListener()
{
new Listener().execute();
}
.
private class Listener extends AsyncTask<Long, String, Long>
{
#Override
protected Long doInBackground(Long... params) {
Log.d("Connecting...", "Connecting...");
JSONObject info = new JSONObject();
String receivedMessage;
try {
info.put("Name", user.GetName());
info.put("PORT", MY_PORT);
info.put("IPv4", getIpAddress());
} catch (JSONException e1) {
Log.e("JSON", "JSON error: " + e1.toString());
}
try
{
serverSocket = new Socket(SERVER_IP, SERVER_PORT);
dis = new DataInputStream(serverSocket.getInputStream());
dos = new DataOutputStream(serverSocket.getOutputStream());
dos.writeUTF(info.toString());
dos.flush();
String response = dis.readUTF();
if(response.equals("connected"))
{
Log.d("Connect", "Connected!");
connected = true;
}
else
Log.d("Connect", "Failed to connect!");
while(connected)
{
receivedMessage = dis.readUTF();
publishProgress(receivedMessage);
}
}
catch(Exception e)
{
Log.d("Connect", "Failed to connect");
Log.e("Connect", e.toString());
return null;
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
displayNewMessage(new MMessage(values[0], MMessage.MessageType.Received));
}
#Override
protected void onPostExecute(Long result) {
super.onPostExecute(result);
connected = false;
try{
if(serverSocket != null)
serverSocket.close();
if(dis != null)
dis.close();
if(dos != null)
dos.close();
}catch(Exception e)
{
Log.e("Listener", "There was a problem closing the connection: " + e.toString());
}
}
}
There are perhaps multiple things going wrong here, but two that jump out are:
You're calling DisplayNewMessage() from outside the UI thread.
You're not notifying the adapter that its dataset has changed.
I urge you to look in to better mechanisms for executing tasks in the background than simply creating a Thread. Using AsyncTasks would be a good start, but you'll need to take special care to handle tasks between configuration changes (such as rotating the device).
Furthermore, your code is very difficult to read as you capitalize your method names. This is against Java code conventions. You will make things easier for yourself by formatting your code neatly (a good IDE helps with that) and learning to follow conventions!
okay so i created a inner class which extends AsycTask in order for my code to run outwith the UI thread. However i'm getting this error so i assume this means some part of my onPostExecute needs to be done in doInBackground however i cant figure out exactly what this is
public class asyncTask extends AsyncTask<String, Integer, String> {
ProgressDialog dialog = new ProgressDialog(PetrolPriceActivity.this);
#Override
protected void onPreExecute() {
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
dialog.setMax(100);
dialog.setMessage("loading...");
dialog.show();
}
#Override
protected String doInBackground(String...parmans){
{
for(int i = 0; i < 100; i++){
publishProgress(1);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String urlString = petrolPriceURL;
String result = "";
InputStream anInStream = null;
int response = -1;
URL url = null;
try {
url = new URL(urlString);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
return null;
}
URLConnection conn = null;
try {
conn = url.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
return null;
}
// Check that the connection can be opened
if (!(conn instanceof HttpURLConnection))
try {
throw new IOException("Not an HTTP connection");
} catch (IOException e) {
// TODO Auto-generated catch block
return null;
}
try
{
// Open connection
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
// Check that connection is OK
if (response == HttpURLConnection.HTTP_OK)
{
// Connection is OK so open a reader
anInStream = httpConn.getInputStream();
InputStreamReader in= new InputStreamReader(anInStream);
BufferedReader bin= new BufferedReader(in);
// Read in the data from the RSS stream
String line = new String();
while (( (line = bin.readLine())) != null)
{
result = result + "\n" + line;
}
}
}
catch (IOException ex)
{
try {
throw new IOException("Error connecting");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
}
#Override
protected void onProgressUpdate(Integer...progress){
dialog.incrementProgressBy(progress[0]);
}
#Override
protected void onPostExecute(String result) {
// Get the data from the RSS stream as a string
errorText = (TextView)findViewById(R.id.error);
response = (TextView)findViewById(R.id.title);
try
{
// Get the data from the RSS stream as a string
result = doInBackground(petrolPriceURL);
response.setText(result);
Log.v(TAG, "index=" + result);
}
catch(Exception ae)
{
// Handle error
errorText.setText("Error");
// Add error info to log for diagnostics
errorText.setText(ae.toString());
}
if(dialog.getProgress() == dialog.getMax())
dialog.dismiss();
}
}
if someone could point out my error as well as show an example of where the code is suppose to go in my doInBackground that would be great. Thanks
problem:
result = doInBackground(petrolPriceURL);
you are implicitly calling the doInbackground method in the onPostExecute which will actually run in your UI thread instead on a different thread thus resulting to Android:NetworkOnMainThreadException.
Also it is unnecessary to call doInBackground that it is already executed before onPostExecute when you execute your Asynctask. Just directly use the result parameter of the onPostExecute.
sample:
#Override
protected void onPostExecute(String result) {
// Get the data from the RSS stream as a string
errorText = (TextView)findViewById(R.id.error);
response = (TextView)findViewById(R.id.title);
response.setText(result);
if(dialog.getProgress() == dialog.getMax())
dialog.dismiss();
}
I suspect the error is related to this part of your code:
try
{
// Get the data from the RSS stream as a string
result = doInBackground(petrolPriceURL);
response.setText(result);
Log.v(TAG, "index=" + result);
}
doInBackgound is called automatically when you call asynctask.execute. To start your task correctly you should (1) create a new instance of your task; (2) pass the string params you need to use in doInBackground in the execute method; (3) use them; (4) return the result to onPostExecute.
For Example:
//in your activity or fragment
MyTask postTask = new MyTask();
postTask.execute(value1, value2, value3);
//in your async task
#Override
protected String doInBackground(String... params){
//extract values
String value1 = params[0];
String value2 = params[1];
String value3 = params[2];
// do some work and return result
return value1 + value2;
}
#Override
protected void onPostExecute(String result){
//use the result you returned from you doInBackground method
}
You should try to do all of your "work" in the doInBackground method. Reutrn the result you want to use on the main/UI thread. This will automaticlly be passed as an argument to the onPostExecute method (which runs on the main/UI thread).
i am trying to poll a database in a server and check if any new records are added, and if any i'm going to send a http request to the java application with the new record.
This is the GET request:
public class PHPDataChecker implements Runnable {
public static String output;
public void run(){
try {
URL url = new URL("http://taxi.net/login.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I'm using a scheduler and here is that code:
public class Main {
private static boolean canStop=false;
public static void stopPHPDataChecker() {
canStop=true;
}
public static void runnner() {
// Setup a task for checking data and then schedule it
PHPDataChecker pdc = new PHPDataChecker();
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
final ScheduledFuture<?> pdcHandle = scheduler.scheduleAtFixedRate(pdc, 0L, 10L, TimeUnit.MILLISECONDS);// Start schedule
scheduler.schedule(new Runnable() {
public void run() {
System.out.println(">> TRY TO STOP!!!");
pdcHandle.cancel(true);
Main.stopPHPDataChecker();
System.out.println("DONE");
}
}, 10L, TimeUnit.MILLISECONDS);
do {
if (canStop) {
scheduler.shutdown();
}
} while (!canStop);
System.out.println("END");
}
another two programs to periodically poll it
RunMain.java:
public class RunMain implements Runnable {
public void run(){
Main m=new Main();
m.runnner();
}}
checkSchedule.java:
public class checkSchedule {
public static void main(String[] args) {
RunMain m = new RunMain();
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
final ScheduledFuture<?> pdcHandle = scheduler.scheduleAtFixedRate(m, 0L, 10L, TimeUnit.SECONDS);
}
}
This doensn't poll the database correctly is there anything wrong with the codings ?
this is the output i see in the nebeans IDE
Output from Server ....
{"return":"0"}
Output from Server ....
{"return":"0"}
TRY TO STOP!!!
DONE
END
TRY TO STOP!!!
DONE
END
TRY TO STOP!!!
DONE
END
TRY TO STOP!!!
DONE
END
TRY TO STOP!!!
DONE
END
TRY TO STOP!!!
DONE
END
TRY TO STOP!!!
DONE
END
TRY TO STOP!!!
DONE
END
TRY TO STOP!!!
DONE
END
TRY TO STOP!!!
DONE
END