Hi every oneI'm new in android
I'm trying to save a binary file with Asynctask and show process in a TextView
This is the layout:
<TextView
android:id="#+id/textView_pecent"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
And this is my java code:
private class hideit extends AsyncTask<String, Integer, Boolean> {
#Override
protected Boolean doInBackground(String... urls) {
try{
int c;
while((c = Data.read()) != -1) {
Data.write(c);
}
}catch (IOException e){
e.printStackTrace();
}
return true;
}
protected void onProgressUpdate(Integer... progress) {
textview.setText(INTEGER.toStirng(x)); //x =0
x++
}
protected void onPostExecute(Boolean result) {
Toast.makeText(getActivity(),"Done", Toast.LENGTH_LONG).show();
}
}
How do i use publish process?
I searched a lot but everyone use sleep or for or while loop but you can't do your process with sleep
I'm so confused how can i use this function to show my process in TextView?
Should i call it many times?
Thanks
edit:
This is an example:
protected String doInBackground(Integer... params) {
for (; count <= params[0]; count++) {
try {
Thread.sleep(1000);
publishProgress(count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Task Completed.";
}
How can i add below code to the example
try{
int c;
while((c = Data.read()) != -1) {
Data.write(c);
}
}catch (IOException e){
e.printStackTrace();
}
return true;
}
Related
I'm trying to search for devices and equipment which are connected to the same wifi network to which my device is connected. I using the following code but until now I haven't had any success
new AsyncTask<Void, Void, Boolean>() {
URL[] urls;
URL proveUrl;
HttpURLConnection con;
private boolean next(int position){
if (position++ < urls.length){
try {
proveUrl = new URL(urls[position].getHost() + ":36000");
} catch (MalformedURLException e) {
Toast.makeText(SDCardImagesActivity.this, "Malformed URL", Toast.LENGTH_SHORT).show();
}
return true;
}else{
return false;
}
}
#Override
protected void onPreExecute() {
wifiManager.getScanResults().toArray(urls);
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
proveUrl =new URL(urls[0].getHost() + ":36000");
} catch (MalformedURLException e) {
Toast.makeText(SDCardImagesActivity.this, "Malformed URL", Toast.LENGTH_SHORT).show();
}
return prove();
}
#Override
protected void onProgressUpdate(Void... values) {
direccionIp = proveUrl.getHost();
super.onProgressUpdate(values);
}
private Boolean prove(){
int position = 0;
try {
con = (HttpURLConnection) proveUrl.openConnection();
BufferedInputStream req = new BufferedInputStream(con.getInputStream());
} catch (IOException e) {
if (next(position)){
position++;
prove();
}else{
return false;
}
}
return true;
}
};
Somebody knows how to do this? Thanks
1) I already read all questions about that here, so please tell me more, than just url from SO...
2) I want to return only ONE variable from asynctask, but it can be message error or user details. So I decided to return ArrayList with indexes 0 (for error messages) and 1 (for success).
AsyncTask
public class LoginGet extends AsyncTask<String, ProgressBar, ArrayList<String>> {
...
public ArrayList<String> result = new ArrayList<String>();
public LoginGet(Context mContext, String loginText, String passwordText) {
//Get values form LoginActivity
}
protected void onPreExecute(){
super.onPreExecute();
// progressDialog
}
#Override
protected ArrayList doInBackground(String... arg0){
try {
// Making HTTP Request
try {
// Creating HTTP client
...
...
JSONObject jObject = new JSONObject(json);
success = jObject.getString("success");
result.add(0, "");
result.add(1, "");
if (success != null) {
if (success == "1") {
result.add(1, jObject.getString("hash"));
return result;
} else if (success == "0") {
result.add(0, jObject.getString("error"));
return result;
}
} else {
result.add(0, "Error while logging.");
return result;
}
// writing response to log
Log.d("Http Response:", response.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}catch (Exception e) {
}
return result;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
((LoginActivity)context).getResult(result);
progressDialog.dismiss();
}
}
LoginActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
...
if (loginText.compareTo("") == 0 || passwordText.compareTo("") == 0) {
...
}else{
LoginGet loginPost = new LoginGet(LoginActivity.this,loginText,passwordText);
loginPost.execute();
}
}
});
}
// Get result from asynctask LoginGet
public void getResult(ArrayList<String> result){
if (result.get(0) != "") {
loginButton.setEnabled(true);
Toast.makeText(LoginActivity.this, result.get(0), Toast.LENGTH_SHORT).show();
} else if (result.get(1) != "") {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Login", result.get(1));
editor.commit();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}
}
Error:
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at cz.jacon.smsapp.LoginActivity.getResult(LoginActivity.java:57)
at cz.jacon.smsapp.background.LoginGet.onPostExecute(LoginGet.java:121)
at cz.jacon.smsapp.background.LoginGet.onPostExecute(LoginGet.java:30)
3) In my AsyncTask I have result.add(0, ""); and result.add(1, "");, so why is the ArrayList size 0?
In my opinion result.add(0, ""); isn't even reached, since the try block might be failing.
And sadly you have an empty catch block, just waiting to skip them errors:
catch (Exception e) {
}
Your solution would be to add these
result.add(0, "");
result.add(1, "");
to the very beginning of the doInBackground or even to the constructor and you should be fine.
This is my first async task, which gets called first, it gets data from server and then onPostExecute it executes other async task, which downloads and sets image.
private class GetData extends AsyncTask<String, Void, Void> {
private final HttpClient client = new DefaultHttpClient();
private String content;
private String error = null;
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... progress) {
}
#Override
protected Void doInBackground(String... params) {
try {
HttpGet httpget = new HttpGet(params[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
content = client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
error = e.getMessage();
cancel(true);
} catch (IOException e) {
error = e.getMessage();
cancel(true);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (error == null) {
try {
JSONObject dataDishes = new JSONObject(content);
Log.d("DISHES", dataDishes.toString());
ArrayList<DishModel> dishData = new ArrayList<DishModel>();
for (int i = 0; i < 8; i++) {
DishModel model = new DishModel();
model.setName("Company " + i);
model.setDesc("desc" + i);
//TODO: set data img
new GetImage(model).execute("http://example.com/" + (i + 1) + ".png");
dishData.add(model);
}
ListView listAllDishes = (ListView) getView().findViewById(R.id.listView);
DishRowAdapter adapterAllDishes = new DishRowAdapter(getActivity(),
R.layout.dish_row, dishData);
listAllDishes.setAdapter(adapterAllDishes);
} catch (JSONException e) {
Log.d("DISHES", e.toString());
}
} else {
Log.e("DISHES", error);
}
}
}
This is another async task, it downloads image and onPostExecute it sets image to passed model.
private class GetImage extends AsyncTask<String, Void, Void> {
private DishModel model;
private Bitmap bmp;
public getImage(DishModel model) {
this.model = model;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... progress) {
}
#Override
protected Void doInBackground(String... params) {
try {
URL url = new URL(params[0]);
Log.d("DISHES", params[0]);
try {
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
Log.d("DISHES", e.toString());
}
} catch (MalformedURLException e) {
Log.d("DISHES", e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
model.setPhoto(bmp);
}
}
It works if I do both data/image download proccess in one AsyncTask doInBackground(String... params), but it doesnt when I split data and image downloading into seperate async tasks. Furthermore I dont get any exceptions or errors.
UPDATE: Images shows up when i switch views..
At first, getImage and getData are classes, and classes names in Java are capitalized.
Technically, you can run another AsyncTask from onProgressUpdate() or onPostExecute() - https://stackoverflow.com/a/5780190/1159507
So, try to put the breakpoint in second AsyncTask call and debug is it called.
This class causing me android.os.NetworkOnMainThreadException,i know that i have to use asyncTask to make it but i can't figure out how because i am using 1 fragments and this make my application very slow especially when i laod bitmaps, can any one help me please.
public class ContainerData {
static public Context context;
public ContainerData() {
}
public static ArrayList<Feed> getFeeds(String feedurl){
SAXParserFactory fabrique = SAXParserFactory.newInstance();
SAXParser parseur = null;
ArrayList<Feed> feeds = null;
try {
parseur = fabrique.newSAXParser();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
URL url = null;
try {
url = new URL(feedurl);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
DefaultHandler handler = new ParserXMLHandler();
try {
parseur.parse(url.openConnection().getInputStream(), handler);
feeds = ((ParserXMLHandler) handler).getData();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return feeds;
}
}
If you use AsyncTask make sure getFeeds is called inside the doInBackground(...) callback
Regardless of whether you use a fragment or not, you're still trying to perform Network activity on the main thread.
Create a generic class that extends AsyncTask which can perform all your parsing.
public class MyTaskHandler extends AsyncTask<String, Integer, Boolean>
{
#Override
protected void onPreExecute()
{
//Could display progress dialog here
}
#Override
protected Boolean doInBackground(String... params)
{
//Implement your parser here
}
#Override
protected void onPostExecute(Boolean result)
{
//Check result, dismiss dialog etc
}
}
Then create a new instance of MyTaskHandler and run it...
MyTaskHandler myTask = new MyTaskHandler();
myTask.execute("http://www.myxmlsite.com/lists.xml");
The execute method can take (String... params) so you can pass for example a URL,and retrieve it in doInBackground(String... params)
#Override
protected Boolean doInBackground(String... params)
{
//Implement your parser here
String urlToParse = params[0];
}
Best of luck.
I have written a code to download some data from internet. Than i wanted to put it into asyncTask. And after that downloading stopped working. It looks like it cant finish try{} part so skips to exeption.
From main activity "Nekaj" i call loadData() class, which extends AsyncData. From there i call "oto" class inside try command. "oto" class is used to read stuff from internet and returns array of strings. This worked when i called oto class directly from "Nekaj"class. What did I do wrong with using AsyncTask?
Here is the code:
public class Nekaj extends Activity {
TextView Tkolo, Tbroj1;
String[] brojevi_varijabla;
String privremena_varijabla = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.bez_provjere_739);
Tkolo = (TextView) findViewById(R.id.Xkolo);
Tbroj1 = (TextView) findViewById(R.id.Xbroj1);
/*
* try { privremena_varijabla = test.kolo_739();
* Tkolo.setText(privremena_varijabla); } catch (Exception e) { // TODO
* Auto-generated catch block e.printStackTrace(); }
*/
new loadData().execute();
}
public class loadData extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
Oto test = new Oto();
try {
brojevi_varijabla = test.brojevi_739();
if (Integer.valueOf(brojevi_varijabla[0]) > 10) {
Tbroj1.setText("" + brojevi_varijabla[0]);
} else {
Tbroj1.setText(" " + brojevi_varijabla[0]);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
public class Oto {
public String[] brojevi_739() throws Exception {
int i = 0;
int uvjet = 0;
int varijabla = 0;
char[] znak = { '>', '<' };
BufferedReader in = null;
String data[] = null;
String provjera = "date-info";
int[] polje = new int[2];
try {
HttpClient klijent = new DefaultHttpClient();
URI webstranica = new URI(
"https://www.aaa.bb");
HttpGet zahtjev = new HttpGet();
zahtjev.setURI(webstranica);
HttpResponse odgovor = klijent.execute(zahtjev);
in = new BufferedReader(new InputStreamReader(odgovor
.getEntity().getContent()));
StringBuffer brojevi = new StringBuffer("");
String brojevi_string = null;
String neki_string = null;
String red = "";
in.skip(21000);
while ((red = in.readLine()) != null) {
varijabla = red.indexOf(provjera);
if (varijabla != -1) {
// 1. KOLO
if (uvjet == 0) { // onda sadrži taj
// substring
// !!!!
red = in.readLine(); // sada string red sadrži ono
// što
// želim, još moram samo to
// izrezati!!
do {
if (i == 0) {
varijabla = red.indexOf(znak[i]);
}
else {
varijabla = red.indexOf(znak[i], polje[0]);
}
if (varijabla != -1) // ako taj znak postoji u
// stringu
{
if (i == 0) {
polje[i] = varijabla + 1;
}
else {
polje[i] = varijabla;
}
i++;
}
} while (i <= 1);
neki_string = red.substring(polje[0], polje[1]);
Tkolo.setText(neki_string);
provjera = "Dobitna kombinacija";
uvjet++;
continue;
}
}
}
in.close();
brojevi_string = brojevi.toString();
data = brojevi_string.split("\n");
return data;
} finally {
if (in != null) {
try {
in.close();
return data;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}}
What you are doing wrong is Tbroj1.setText() inside the doInBackground() method. What you have to do is to use the onPostExecute method to post your data on the UI:
public class loadData extends AsyncTask<String, Integer, Boolean> {
protected Long doInBackground(String... arg0) {
Oto test = new Oto();
Boolean result = false;
try {
brojevi_varijabla = test.brojevi_739();
result = true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
protected void onPostExecute(Boolean result) {
if(result){
if (Integer.valueOf(brojevi_varijabla[0]) > 10) {
Tbroj1.setText("" + brojevi_varijabla[0]);
} else {
Tbroj1.setText(" " + brojevi_varijabla[0]);
}
}
}
}
Actually, You are trying to update UI in doInBackGround() of your AsyncTask, so its not allowed (doInBack.. runs in non UI Thread..), So put the UI updation code in onPostExecute() of AsyncTask..
Try this and let me know what happen..
public class loadData extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
Oto test = new Oto();
try {
brojevi_varijabla = test.brojevi_739();
if(brojevi_varijabla != null)
return brojevi_varijabla[0];
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result)
{
if(result != null)
{
if (Integer.valueOf(result) > 10) {
Tbroj1.setText("" + result;
} else {
Tbroj1.setText(" " + result);
}
}
}
}
use onPostExecute(Void result1) {}
to catch the result and perform the action required over there
You can't manipulate UI elements directly on a non-UI (background) thread, which is where doInBackground() always runs. The usual way of using AsyncTask is to get the data in doInBackground(), return it as a value, and then process the UI changes in onPostExecute(). For example:
public class loadData extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
Oto test = new Oto();
try {
brojevi_varijabla = test.brojevi_739();
if (Integer.valueOf(brojevi_varijabla[0]) > 10) {
return "" + brojevi_varijabla[0];
} else {
return " " + brojevi_varijabla[0];
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) Tbroj1.setText(result);
}
}