How to implement ASyncTask in my code - java

in my app I am trying to read a string out of a text file located online, and then save the contents to a variable. Here is my current code:
download.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
URL site = new URL("http://m.uploadedit.com/b029/1393133970157.txt");
Scanner s = new Scanner(site.openStream());
String num = s.nextLine();
}
catch(MalformedURLException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "String from file is: " + num,
Toast.LENGTH_LONG).show();
}
});
However this is giving me a force close. Here is the log: http://pastebin.com/2nsxmJz1
I believe that I need to implement an ASyncTask, but not sure how to go about doing so.

You can't use network communications on UI thread. As u correctly mentions you should use AsyncTask for such cases:
final AsyncTask<Object,Object,String> task = new AsyncTask<Object,Object,String>() {
protected String doInBackground(Object... o) {
try {
URL site = new URL("http://m.uploadedit.com/b029/1393133970157.txt");
Scanner s = new Scanner(site.openStream());
return s.nextLine();
}
catch(MalformedURLException e) {
throw new RuntimeException("Incorrect URL", e);
}
catch(IOException e) {
throw new RuntimeException("Can't fetch file content from url", e);
}
}
protected void onPostExecute(String r) {
Toast.makeText(getApplicationContext(), "String from file is: " + r,
Toast.LENGTH_LONG).show();
}
};
task.execute();

Related

App crashes without catching any exception [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Can't create handler inside thread that has not called Looper.prepare() Android
(2 answers)
Can't create handler inside thread that has not called Looper.prepare()
(30 answers)
Closed 3 years ago.
So i'm into a tutorial at Udemy "The Complete Android N Developer Course" and trying to make lecture 86 about a weather app.
I use the API from here https://openweathermap.org/current#cityid and use JSON to get the data needed.
The app is working properly when i input a correct city name, but when the input is wrong or empty the app crashes without catching any exceptions.
I don't know why it is crashing and where to look. So i give you all the code i wrote. I tried to implement if statements here and there to try and find it but without any luck.
I would like to know where the problem is and how to fix it so the app doesn't crash anymore.
Thanks in advance.
public class MainActivity extends AppCompatActivity {
EditText editText;
String city = "";
TextView textView;
public void getWeather (View view) {
try {
city = URLEncoder.encode(editText.getText().toString(), "UTF-8");
if (editText.getText().toString() == "") {
Toast.makeText(MainActivity.this, "Could not find weather", Toast.LENGTH_SHORT).show();
textView.setText("Please enter a city.");
} else {
DownloadTask task = new DownloadTask();
task.execute("http://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=c6ef169a79d84674ef7e1414301eb5c4");
}
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(editText.getWindowToken(), 0);
} catch (UnsupportedEncodingException e1) {
Toast.makeText(MainActivity.this, "UnsupportedEncodingException", Toast.LENGTH_SHORT).show();
}catch (Exception e) {
Toast.makeText(MainActivity.this, "General exception (getWeather)", Toast.LENGTH_SHORT).show();
}
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection)url.openConnection();
InputStream in = null;
in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e1) {
Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
} catch (IOException e2) {
Toast.makeText(MainActivity.this, "IOException", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "General exception (doInBackground)", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject jsonObject = null;
jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
JSONArray jsonArray = new JSONArray(weatherInfo);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonPart = jsonArray.getJSONObject(i);
String main = "";
String description = "";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
if (main != "" && description != "") {
message += main + ": " + description + "\r\n";
}
}
if (message != "") {
textView.setText(message);
} else {
Toast.makeText(MainActivity.this, "Could not find weather", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e1) {
Toast.makeText(MainActivity.this, "JSONException", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "General exception (onPostExecute)", Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
textView = (TextView) findViewById(R.id.textView);
}
}
It is because you're trying to changes UI with background thread inside the doInBackground(Params...) method of AsyncTask with this line:
try {
...
return result;
} catch (MalformedURLException e1) {
Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
} catch (IOException e2) {
Toast.makeText(MainActivity.this, "IOException", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "General exception (doInBackground)", Toast.LENGTH_SHORT).show();
}
You should not call Toast inside the doInBackground(Params...). Do that inside the onPostExecute(Result).
You can avoid that by either ignoring the error or returning specific text in doInBackground. Something like this:
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
...
try {
...
return result;
} catch (MalformedURLException e1) {
result= "MalformedURLException";
} catch (IOException e2) {
result= "IOException";
} catch (Exception e) {
// do nothing and returning empty
result= "Exception";
}
return result;
}
#Override
protected void onPostExecute(String result) {
// check if there is an error
String errorMessage = "";
switch(result) {
case "MalformedURLException":
errorMessage = "MalformedURLException";
break;
case ""IOException":
errorMessage = "IOException";
break;
case "Exception":
errorMessage = "Exception";
break;
}
// there is an error, show a message.
if(!errorMessage.isEmpty()) {
Toast.makeText(MainActivity.this, "Could not find weather: " + errorMessage, Toast.LENGTH_SHORT).show();
return; // stop the process.
}
// do something when no error found.
}
}

Json parsing error: Value <?xml of type java.lang.String cannot be converted to JSONArray [duplicate]

This question already has an answer here:
JSON error "Value at result of type java.lang.String cannot be converted to JSONArray" in android
(1 answer)
Closed 5 years ago.
I am new to programming and I have small problem i am trying to make an app that will use json to read flickr api but i am getting the error mention in the description i was looking around but none of the solutions worked so i came here to ask
public class JSONPareser {
final String TAG = "JSONParser";
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// 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) throws UnsupportedEncodingException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
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();
}
}
that is my parser class and here is when i am calling json object
public class getData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Please wait");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String url = "https://api.flickr.com/services/feeds/photos_public.gne";
JSONPareser pareser = new JSONPareser();
String jsonStr = pareser.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONArray jsonArray = new JSONArray(jsonStr);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
FlickrModel model = new FlickrModel();
model.setLink(obj.getString("link"));
model.setDescription(obj.getString("description"));
model.setTitle(obj.getString("title"));
model.setAuthor(obj.getString("author"));
model.setTags(obj.getString("tags"));
flickrList.add(model);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + 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(Void result) {
super.onPostExecute(result);
if (dialog.isShowing()) {
dialog.dismiss();
}
thank you so much
Your service seens to be returning a XML instead of JSON, see the header

How to download a file after clicking a button (Android Studio)

I recently created an activity in my app. Now I wanted the user to download a .pdf file when he/she wants to view the guidelines. I wanted to implement this on a button. Any idea how to do this properly?
Heres my code below:
public class Exhibitor_Registration_Activity extends AppCompatActivity {
Button buttonDownload;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exhibitor_registration_);
this.setTitle("Buyer Registration");
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
myToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
final Button buttonDownload = (Button) findViewById(R.id.buttonDownload);
buttonDownload.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
try {
//this is the file you want to download from the remote server
String path ="http://www.manilafame.com/website-assets/downloads/exhibitor-application-kit/local/201704/1-Summary-of-Participation-Details-April-2017_MN_002.pdfp";
//this is the name of the local file you will create
String targetFileName = null;
boolean eof = false;
URL u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File("c:\\junk\\"+targetFileName));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = in.read(buffer)) > 0 ) {
f.write(buffer,0, len1);
}
f.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
I also got the source code from here and here.
if you want resumable, speed of download ...
follow this steps
create a class DownloadManager.java
public class DownloadManager extends AsyncTask<String,String,String>{
String downloadlink,fileDestination;
public static final int ON_INIT=100,ON_ERROR=102,ON_PROGRASS=103,ON_COMPLETED=104,STATUS_DOWNLOADED=1500,STATUS_NOT_YET=1501;
private onUpdateListener onUpdateListener;
private String downloadedPath="";
private long downloaded=0;
private File file;
private String returnData=null;
private File cacheDownloadFile;
public DownloadManager(String downloadlink,String fileDestinationPath){
this.downloadlink=downloadlink;
this.fileDestination=fileDestinationPath;
file=new File(fileDestination, Tools.getFileName(downloadlink));
cacheDownloadFile=new File(AppCostants.CHACHE_PATH+Tools.getFileName(downloadlink));
try {
if(cacheDownloadFile.isFile())
downloaded=Tools.getFileSize(cacheDownloadFile);
else
downloaded=0;
Log.d("FILE_DOWNLOAD_TAG_p",downloaded+" <- "+cacheDownloadFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
fireOnUpdate(ON_INIT,"init ...");
}
#Override
protected String doInBackground(String... params) {
try {
File dir=new File(fileDestination);
File chacheDir=new File(AppCostants.CHACHE_PATH);
if(!chacheDir.isDirectory())
chacheDir.mkdirs();
if(!dir.isDirectory()){
dir.mkdirs();
}
if(file.exists()) {
Log.d("FILE_DOWNLOAD_TAG","File exist return complete");
return "COMPLETED";//file exist
}
if(!cacheDownloadFile.exists()){
cacheDownloadFile.createNewFile();
}
Log.d("FILE_DOWNLOAD_TAG","LINK "+downloadlink);
URL url=new URL(downloadlink);
HttpURLConnection urlConnection= (HttpURLConnection) url.openConnection();
if(downloaded>0)
urlConnection.setRequestProperty("Range","byte="+downloaded);
urlConnection.connect();
int status = urlConnection.getResponseCode();
InputStream inputStream=urlConnection.getInputStream();
int totalSize=urlConnection.getContentLength();
if(totalSize<=downloaded){
returnData= "COMPLETED";
publishProgress("File checked "+Tools.getFileName(file.getAbsolutePath()));
return returnData;
}
this.downloadedPath=cacheDownloadFile.getAbsolutePath();
byte[] buffer=new byte[1024];
int bufferLength=0;
FileOutputStream fileOutput=new FileOutputStream(cacheDownloadFile);
long d=0;
long starttime=System.currentTimeMillis();
while ((bufferLength=inputStream.read(buffer))>0){
fileOutput.write(buffer,0,bufferLength);
downloaded+=bufferLength;
d+=bufferLength;
//String l=" "+Tools.getFileName(file.getAbsolutePath())+" ( "+Tools.convertMemory(downloaded)+" / "+Tools.convertMemory(totalSize)+" )";
String l=" "+Tools.convertMemory(downloaded)+" / "+Tools.convertMemory(totalSize)+" ( "+getDownloadSpeed(starttime,d)+" )";
publishProgress(l);
if(downloaded>=totalSize){
break;
}
}
Log.d("FILE_DOWNLOAD_TAG","DWONLOADED TO "+downloadedPath+" ("+cacheDownloadFile.length()+")");
fileOutput.close();
if(Tools.fileCopy(file,cacheDownloadFile)){
Log.d("FILE_DOWNLOAD_TAG","file Copied, delete cache");
cacheDownloadFile.delete();
}
returnData="COMPLETED";
} catch (MalformedURLException e) {
returnData=null;
e.printStackTrace();
publishProgress(e.toString());
Log.d("###################",e+"");
} catch (IOException e) {
returnData=null;
e.printStackTrace();
publishProgress(e.toString());
}
return returnData;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
fireOnUpdate(ON_PROGRASS,values[0]);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s!=null){
fireOnUpdate(ON_COMPLETED,downloadedPath);
}else{
fireOnUpdate(ON_ERROR,"Download failed");
}
}
public interface onUpdateListener{
void onUpdate(int code,String message);
}
public void setOnUpdateListener(onUpdateListener onUpdateListener){
this.onUpdateListener=onUpdateListener;
}
private void fireOnUpdate(int code,String message){
if(onUpdateListener!=null)
onUpdateListener.onUpdate(code,message);
}
private String getDownloadSpeed(long starttime,float totalDownloaded) {
long elapsedTime = System.currentTimeMillis() - starttime;
//byte :
float speed=1000f * totalDownloaded / elapsedTime;
return convert(speed);
}
private String convert(float value){
long kb=1024
,mb=kb*1024
,gb=mb*1024;
if(value<kb){
String speed=(value+"");
speed=speed.substring(0,speed.indexOf('.')+2);
return speed+" B/s";
}else if(value<mb){
value=value/kb;
String speed=(value+"");
speed=speed.substring(0,speed.indexOf('.'));
return (speed)+" KB/s";
}else if(value<gb){
value=(value/mb);
String speed=(value+"");
speed=speed.substring(0,speed.indexOf('.'));
return speed+" MB/s";
}
return "";
}
}
use this code in onClick()
DownloadManager downloadManager = new DownloadManager(url,filepath);
set event
downloadManager.setOnUpdateListener(new DownloadManager.onUpdateListener() {
#Override
public void onUpdate(int code, String message) {
if (code == DownloadManager.ON_COMPLETED) {
}
if(DownloadManager.ON_PROGRASS==code){}
}
});
start download by
downloadManager.execute();
lib setup
compile "commons-io:commons-io:+"
Tools.java
public static long getFileSize(File file) throws IOException {
FileOutputStream fileOutputStream=new FileOutputStream(file);
fileOutputStream.close();
return file.length();
}
public static boolean fileCopy(File dest,File source){
try {
FileUtils.copyFile(source,dest);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
It is really bad idea to download file in main thread.
Use separate Thread for this
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
//your downloading here
}
});
thread.start();
it`s better, but still not so good. There are some problems with it:
1) User know nothing about downloading
So better to show additional layout which overlays screen with progress bar, probably indeterminate if you want to write less code. Then after downloading is finished you just hide your layout.
You can use runOnUiThread inside run method in thread for it.
runOnUiThread(new Runnable() {
#Override
public void run() {
//just hide some popup
//or do what you want after downloading is finished
popupLayout.serVisibility(View.GONE);
}
});
2) If user will do action which re-creates activity/fragment (like changing screen orientaion) with running thread you will get memory leak and probably activity will not know about end of download.
There are few ways to solve this problem:
You can block screen orientation at this screen, at least while downloading. Probably easiest way in your case.
You can use downloading in foreground service. Its really good
practice, but you will have to learn about services.
You can try to interrupt downloading by calling thread.interrupt()
method in onDestroy of your Activity/Fragment
You can use something like rxJava/rxAndroid (so you don not use threads at all, but you need some time for learn rxJava)
UPD
About threads
Not so bad tutorial about threads in android
You can use AsyncTask instead of Thread, but I highly recommend to use threads especially for long operations.

Android UI from other thread

I'm creating an application that gets the get the homestatus from a server in json but this happens on another thread. this isn't a problem when i try to set most Items on the ui because i can set them in a static void. but when i try to create a new switch and space i can't call 'this' to create a new.
code for getting the homestatus:
public void loadHomeStatus()
{
if(socket != null) {`enter code here`
if (socket.isConnected()) {
Log.d("BtnUpdate","already connected");
return;
}
}
swAlarm = (Switch) findViewById(R.id.swAlarmState);
tvTemperature = (TextView) findViewById(R.id.tvTemprateur);
tvHumidity = (TextView) findViewById(R.id.tvHumidity);
llDevices = (LinearLayout) findViewById(R.id.llDevices);
new Thread() {
public void run() {
try
{
busyConnecting = true;
Log.d("loadHomeStatus","trying to connect to: " + host + ":" + port);
socket = new Socket(host, port);
uiConnected();
Log.d("loadHomeStatus","Connected");
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
DataInputStream is = new DataInputStream(socket.getInputStream());
os.writeBytes(password);
Log.d("Connect", "send: " + password);
while (socket.isConnected()) {
byte[] data = new byte[500];
int count = is.read(data);
String recieved = new String(data).trim();
Log.d("loadHomeStatus","recieved " + recieved );
if(recieved.toLowerCase() == "failed")
{
Log.d("loadHomeStatus","failed to log in");
}
else
{
try
{
homeStatus = new Gson().fromJson(recieved, HomeStatus.class);
uiLoadStatus();
} catch (Exception e)
{
Log.d("Error", e.toString());
}
}
}//end of while loop
Log.w("loadHomeStatus", "end connection thread ");
//ends thread
Thread.currentThread().interrupt();
return;
}
catch (UnknownHostException e)
{
e.printStackTrace();
Log.w("loadHomeStatus", "no Failed to connect: " + host + "-" + 8001);
}
catch (IOException e)
{
e.printStackTrace();
Log.w("loadHomeStatus", "no Failed to connect: " + host + "-" + 8001);
}
Log.w("loadHomeStatus","Connection ended");
socket = null;
busyConnecting = false;
uiDisconnected();
}
}.start();
}`
Code for setting ui
public static void uiLoadStatus()
{
if (homeStatus != null)
{
try {
tvTemperature.post(new Runnable()
{
public void run()
{
//Log.d("uiLoadStatus to string",homeStatus.toString());
tvTemperature.setText(homeStatus.temperature + "°C");
tvHumidity.setText(homeStatus.humidity + "%");
}
});
}
catch(Exception e)
{
Log.d("uiLoadStatus status fragment", e.toString());
}
try {
swAlarm.post(new Runnable()
{
public void run() {
swAlarm.setChecked(homeStatus.alarmState);
}
});
}
catch (Exception e)
{
Log.d("uiLoadStatus alarm fragment", e.toString());
}
}
try {
llDevices.post(new Runnable()
{
public void run() {
uiLoadDevices(); //this gives and error because it's not static
}
});
}
catch (Exception e)
{
Log.d("uiLoadStatus alarm fragment", e.toString());
}
}
public void uiLoadDevices()
{
for (int i = 0; i < homeStatus.lstDevices.size(); i++) {
String deviceAdd = homeStatus.lstDevices.get(i);
Space mySpace = new Space(this);
Switch mySwitch = new Switch(this);
mySpace.setMinimumHeight(50);
mySwitch.setText(homeStatus.getName(deviceAdd));
mySwitch.setChecked(homeStatus.getState(deviceAdd));
mySwitch.setTextSize(18);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.LEFT;
llDevices.addView(mySpace, lp);
llDevices.addView(mySwitch, lp);
}
}
You should use AsyncTask and put the network interaction part in the doInBackground() method. To update the UI components, implement those logics in the onPostExecute() method
uiLoadStatus is a static method (not sure why or if it has to be without looking at all of your code) and therefore you cannot call non-static methods from within it, such as uiLoadDevices
I would advise taking a look at your code and update your uiLoadStatus to not be static if at all possible. Abusing static can lead to sloppy code.

Running multiple Asyntask simultaneously

I have server client communication program at server side I have camera and that camera I am controlling by my android application as client it is working but the problem is when the server memory is full then server is stopping the camera and sending a message to client and and if client want to stop camera by it self then client is sending command to server and server stop the camera .
The problem is there only I am not getting the massage if I am getting the massage of "memory full" then I am not getting the massage "stopping camera "when user want to kill by itself and if am manage to get the "stopping camera " message then I am not getting the "memory full massage "
here is my code please help me
thanks in advance
/** here is the recording start button I am calling a asyntask for recording
* Record and store video at battery control unit(server end) at background
*/
record=(ImageButton)findViewById(R.id.record);
record.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if(socket==null){
Toast.makeText(getApplicationContext(), "connection not establised", Toast.LENGTH_SHORT).show();
}
else{
pDialog.show();
suspended=false;
start=false;
new CommunicationTaskrec().execute();
}
}
});
/**
* Async task for the record, which runs on back ground.
*/
public class CommunicationTaskrec extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... params) {
String str = "3";
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
} catch (IOException e1) {
e1.printStackTrace();
}
out.println(str);
String resultrec="testing the UI Thread update";
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
try {
resultrec = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
//Log.d("inside bg thread", resultrec);
mHandler.obtainMessage(MESSAGE_READ, resultrec).sendToTarget();
out.flush();
// new Thread(new RecThread()).start();
// new CommunicationTaskmemorycheck().execute();
return resultrec;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
//here is the message handler case
/**
* Creating a dialog box which shows a timer for the recording time
*/
case MESSAGE_READ:
final String readBuf = (String) msg.obj;
String string1 ="no enough space left on device";
if(readBuf !=null){
if(readBuf.equalsIgnoreCase(string1))
{
pDialog.dismiss();
Toast.makeText(MainActivity.this, "NO Enough Space Left for Recording Please Remove some files at server end.", Toast.LENGTH_LONG).show();
}
else{
pDialog.dismiss();
Toast.makeText(MainActivity.this, readBuf, Toast.LENGTH_LONG).show();
//here is the dialog box where I have a stop button also by which user stopping the ///camera manually
View viewlist=MainActivity.this.getLayoutInflater().inflate(R.layout.timer, null);
dialog = new Dialog(MainActivity.this);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
dialog.setContentView(viewlist);
dialog.setTitle("Status.....");
dialog.setCancelable(false);
TextView text = (TextView) dialog.findViewById(R.id.valuerec);
text.setText("Want to stop the Recording ?");
TextView cur_val = (TextView) dialog.findViewById(R.id.curvaluerec);
cur_val.setText("Recording Duration..");
Button stop = (Button) dialog.findViewById(R.id.start);
mChronometer = (Chronometer) dialog.findViewById(R.id.chronometer);
mChronometer.start();
dialog.show();
//here a asyntask and it is used for getting the memory full message
//it run contentiously on background and when the memory is full it //recieve "memory full massage"
task = new AsyncTask<Void, Void, Void>() {
String result=null;
protected Void doInBackground(Void... params) {
Runnable action = new Runnable() {
public void run() {
mHandler.obtainMessage(MESSAGE_READcreate, result).sendToTarget();
}
};
try {
do {
//Pause work if control is paused.
//tControl.waitIfPaused();
//Stop work if control is cancelled.
if (tControl.isCancelled()) {
suspended=true;
break;
}
while(!suspended){
String string1 ="memory full";
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
try {
result = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if((result!=null && result.equalsIgnoreCase(string1)) )
{
mHandler.obtainMessage(MESSAGE_READcreate, result).sendToTarget();
result=null;
suspended=true;
start=true;
runOnUiThread(action);
break;
}
}
}while (!suspended);
} catch (Exception e) {
}
return null;
}
};
task.execute();
//here is the dialog box stop button where I have a runnable thread which is used for send //command to server when user want to stop recording manually
stop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
task.cancel(true);
tControl.cancel();
suspended=true;
dialog.dismiss();
dialog=null;
mChronometer.stop();
pDialog.show();
//this is the runnable thread where I am getting "stopping //camera "massage
new Thread(new Runnable() {
#SuppressLint("ShowToast")
public void run() {
while (true) {
String str = "8";
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
} catch (IOException e) {
e.printStackTrace();
}
out.println(str);
String resultcap=null;
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
try {
resultcap = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
mHandler.obtainMessage(MESSAGE_READstoprunning, resultcap).sendToTarget();
out.flush();
//suspended=false;
break;
}
}
}
).start();
}
});
}
}
else{
pDialog.dismiss();
Toast.makeText(MainActivity.this, "error server not respondingrec", Toast.LENGTH_LONG).show();
}
break;
change execute() to executeOnExecutor(AsynTask.ThreadpoolExecutor)
AsyncTasks doc
When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.
If you truly want parallel execution, you can invoke
executeOnExecutor(java.util.concurrent.Executor, Object[])
with THREAD_POOL_EXECUTOR.

Categories

Resources