messed up with publishProgress method while using it in AsyncTask - java

I am trying to implement simple internal data storage code.In it I want to show ProgressDialog for some background process which will increment by 5 while calling publishProgress(). But it gives me error like the following,
The method publishProgress(R.integer...) in the type AsyncTask<String,R.integer,String> is not applicable for the arguments (int)
following is the code.
public class loadSomeStuff extends AsyncTask<String, integer, String>
{
ProgressDialog dailog;
protected void onPreExecute()
{
//example of setting up something
dailog=new ProgressDialog(MainActivity.this);
dailog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dailog.setMax(100);
dailog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String collected=null;
FileInputStream fis=null;
for(int i=1; i<=20; i++)
{
publishProgress(5);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
dailog.dismiss();
try {
fis=openFileInput(FileName);
byte[] dataArray = new byte[fis.available()];
while(fis.read(dataArray)!= -1)
{
collected=new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fis.close();
return collected;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
protected void onProgressUpdate(Integer...progress)
{
dailog.incrementProgressBy(5);
}
protected void onPostExecute(String result)
{
DataResults.setText(result);
}
}

Generics cannot use value types so your AsyncTask needs to use Integer:
extends AsyncTask<String, Integer, String>

try this :
extends AsyncTask<String, Integer, String>
Integer with a capital I

I have tried your code on my machine and its working fine without any error.
You can check now with my code.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadSomeStuff objSomeStuff = new loadSomeStuff();
objSomeStuff.execute();
}
public class loadSomeStuff extends AsyncTask<String, Integer, String>
{
ProgressDialog dailog;
protected void onPreExecute()
{
//example of setting up something
dailog=new ProgressDialog(MainActivity.this);
dailog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dailog.setMax(100);
dailog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String collected=null;
FileInputStream fis=null;
for(int i=1; i<=20; i++)
{
publishProgress(5);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
dailog.dismiss();
try {
fis=openFileInput("");
byte[] dataArray = new byte[fis.available()];
while(fis.read(dataArray)!= -1)
{
collected=new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fis.close();
return collected;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
protected void onProgressUpdate(Integer...progress)
{
dailog.incrementProgressBy(5);
}
protected void onPostExecute(String result)
{
//DataResults.setText(result);
Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG).show();
}
}
}

Alright I think you may have messed up with some namespaces. Here is what you need to do
Organize your imports Ctrl+Shift+O. make sure there is no invalid import. it may have happned if you copy & paste code from any other source.
Clean your project.
AsyncTask should look like this:
public class LoadSomeStuff extends AsyncTask<String, Integer, String>
Let me know if you still cant resolve it .

simple answer is that
in the Question Code Mention is
AsyncTask< String, integer, String>
But change that for progress updated
AsyncTask< String, Integer, String>
if use AsyncTask**< String, String, String>** then should be Cast into Interger for
progress update.

Related

Perform something only after completing doInBackground in AsyncTask

In my AsyncTask I do a quite a long operation inside doInBackground() which assigns a value to a variable after completion of doInBackground().
I use the value of that variable to setup a part of the user interface in postExecute().
The problem is that doinbackground() is quite a long operation and postExecute() finishes first. That way I fail to obtain the value.
Here's what the problem is
private class bigwork extends AsyncTask<String, Void, Boolean> {
String foo = null;
#Override
protected void onPreExecute() {
}
#Override
protected Boolean doInBackground(final String... args) {
// Long operation sets variable 'foo' a new value
}
#Override
protected void onPostExecute(final Boolean success) {
// Make use of foo here
}
The problem is the value of foo I get in postExecute() is still null.
Usually you would pass the String directly to onPostExecute:
private class bigwork extends AsyncTask<String, Void, String>
{
#Override
protected void onPreExecute() {
}
#Override
protected Boolean doInBackground(final String... args) {
// Long operation
set variable 'foo' a new value
return foo;
}
#Override
protected void onPostExecute(String foo) {
if (foo != null) {
// success
}
// Make use of foo here
}
Override onPostExecute() function to perform some task after doInBackground() function has finished.Like this:
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
ServiceHandler sh = new ServiceHandler();
jsonStr=sh.makeServiceCall(arg0[0], ServiceHandler.GET);
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.i("jsin", jsonStr);
if(pd.isShowing()){
pd.dismiss();
}
try {
js = new JSONObject(jsonStr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray results =null;
try {
results = js.getJSONArray("results");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i = 0; i< results.length();i++)
{
JSONObject c = null;
try {
c = results.getJSONObject(i);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
placeName = c.getString(TAG_NAME);
ratings = c.getDouble(TAG_RATING);
HashMap<String, String> rest = new HashMap<String, String>();
rest.put(TAG_NAME, placeName);
rest.put(TAG_RATING, ratings+"");
placeList.add(rest);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ListAdapter adapter = new SimpleAdapter(getActivity().getApplicationContext(), placeList, R.layout.list_item, new String[]{TAG_NAME}, new int[]{R.id.list_text});
lv.setAdapter(adapter);
}
I am making http request in my doInBackground and after successful reply i am parsing json in onPostExecute() and displaying in a listview and obviously this code is in class extending AsyncTask class.
You should pass the parameter directly to onPostExecute. Quoting from the Android Developer Reference:
protected void onPostExecute (Result result)
Runs on the UI thread after doInBackground(Params...). The specified result is the value returned by doInBackground(Params...).
In case you need to pass more than one parameter wrap them in a class like:
public class MyClass
{
public String string1;
public String string2;
public MyClass(String a, String b){
string1 = a;
string2 = b;
}
}
Hope this helps.
Best regards.

Public class implementing runnable won't start-Android

When i click on an item in my listview, I would like to have a new thread start and execute the desired tasks I have defined for it in the Connect2 class, however, as far as I can tell the thread is not starting or showing any indication of as why it isn't starting. If anybody could help diagnose a problem in the code or point me in the right direction to fix this issue I would greatly appreciate it. Thanks!
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_directory);
final ListView fileDirectory=(ListView) findViewById(R.id.DirectoryView);
final ArrayAdapter adapter=new ArrayAdapter(this, android.R.layout.simple_list_item_1, SocketConnection.remoteList);
fileDirectory.setAdapter(adapter);
fileDirectory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(FileDirectory.this, "The click works", Toast.LENGTH_SHORT).show();
FileDirectory.listItem=i;
new Connect2().execute("");
adapter.notifyDataSetChanged();
}
});
}
public class Connect2 extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params){
runConnectCode();
return null;
}
}
public void runConnectCode(){
String itemTemp=SocketConnection.remoteList.toArray()[FileDirectory.listItem].toString();
SocketConnection.PW.write(itemTemp);
//SocketConnection.DOS.flush();
SocketConnection.currentF.concat("\\"+itemTemp);
SocketConnection.PW.write(SocketConnection.currentF);
//SocketConnection.DOS.flush();
try{
Object object=SocketConnection.OIS.readObject();
SocketConnection.remoteList=(ArrayList<String>) object;
} catch(IOException e){
System.out.println(e);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}//run()
Try to run your thread using runOnUiThread();
Try to create class extend Asynctask and call your code in doinbackground() method like this:
public class Connect2 extends AsyncTask<String , String , String>
{
#Override
protected String doInBackground(String... params) {
runConnectCode();
return null;
}
}
public void runConnectCode ()
{
String itemTemp = SocketConnection.remoteList.toArray() [FileDirectory.listItem].toString();
try {
SocketConnection.DOS.writeUTF(itemTemp);
SocketConnection.DOS.flush();
} catch (IOException e) {
System.out.println(e);
}
try {
SocketConnection.currentF.concat("\\" + itemTemp);
SocketConnection.DOS.writeUTF(SocketConnection.currentF);
SocketConnection.DOS.flush();
} catch (IOException e) {
System.out.println(e);
}
try {
Object object = SocketConnection.OIS.readObject();
SocketConnection.remoteList = (ArrayList<String>) object;
} catch (IOException e) {
System.out.println(e);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Finally, call this whenever you want:
new Connect2().execute("");

Simple progress dialog onClick and hide when finish operation

I want show a progress dialog (with a progressbar or circle this is indifferent to me) when i click the button. Actually i can show it but i don't know how hide it after finish the operations inside at onclick. This is the code:
copy.setOnClickListener(new OnClickListener() {
public void onClick(View v){
ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setProgressStyle(R.style.NewDialog);
progressDialog.setMessage("Loading...");
progressDialog.show();
String datafolder = Environment.getDataDirectory().getAbsolutePath()+File.separator+"app";
File customfolder=new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString()+File.separator+"BackupApps");
String comando = "cp -r /data/app /sdcard/BackupApps";
Process suProcess = null;
try {
suProcess = Runtime.getRuntime().exec("su");
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
try {
os.writeBytes(comando + "\n");
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
os.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.writeBytes("exit\n");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
How can i do it?
First define inner class like this in your class
class SaveTask extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setProgressStyle(R.style.NewDialog);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String datafolder = Environment.getDataDirectory()
.getAbsolutePath() + File.separator + "app";
File customfolder = new File(Environment
.getExternalStorageDirectory().getAbsolutePath().toString()
+ File.separator + "BackupApps");
String comando = "cp -r /data/app /sdcard/BackupApps";
Process suProcess = null;
try {
suProcess = Runtime.getRuntime().exec("su");
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
DataOutputStream os = new DataOutputStream(
suProcess.getOutputStream());
try {
os.writeBytes(comando + "\n");
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
os.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.writeBytes("exit\n");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
}
call this in your onClick() like this..
here we haven't passing any data to AsynchTask so here i am passing null
copy.setOnClickListener(new OnClickListener() {
public void onClick(View v){
SaveTask task = new SaveTask();
task.execute(null, null, null);
}
Start a AsyncTask on onClick method like this:
public void onClick(View v){
YourAsyncTask asyncTask = new AsyncTask(context);
asyncTask.execute();
}
And in your AsyncTask create a ProgressDialog on onPreExecute(), do your stuff in doInBackground() and dismiss the ProgressDialog on onPostExecute():
public class YourAsyncTask extends AsyncTask<Void, Void, Void> {
private Context ctx;
private ProgressDialog progressDialog;
public YourAsyncTask(Context ctx) {
this.ctx = ctx;
}
#Override
protected void onPreExecute() {
ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setProgressStyle(R.style.NewDialog);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String datafolder = Environment.getDataDirectory().getAbsolutePath()+File.separator+"app";
File customfolder=new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString()+File.separator+"BackupApps");
String comando = "cp -r /data/app /sdcard/BackupApps";
Process suProcess = null;
try {
suProcess = Runtime.getRuntime().exec("su");
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
try {
os.writeBytes(comando + "\n");
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
os.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.writeBytes("exit\n");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
protected void onPostExecute(Void res) {
progressDialog.hide();
progressDialog.dismiss();
}
don't foget to declare the progressDialog global variable
#Override
public void onClick(View v) {
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setProgressStyle(R.style.NewDialog);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
String datafolder = Environment.getDataDirectory().getAbsolutePath()+File.separator+"app";
File customfolder=new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString()+File.separator+"BackupApps");
String comando = "cp -r /data/app /sdcard/BackupApps";
Process suProcess = null;
try {
suProcess = Runtime.getRuntime().exec("su");
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
try {
os.writeBytes(comando + "\n");
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
os.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.writeBytes("exit\n");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (progressDialog!=null) {
progressDialog.dismiss();
}
}
};
task.execute((Void[])null);
}
Add progressDialog.dismiss(); in the last line on onClick and in all the catch so that it will disappear even if an Exception is thrown

How to get the new data update from a json url in android?

I am working in an online radio streaming project. I play the stream from a url and parsing the sound track info from another json url. All that I did is I repeatedly parse the json after every 10 seconds thats why when the sound track is changing I can get the track info of that specific track. But the json file is being updated 30+ sec before the track changes, thats why sometimes there is a noticeable dissimilarity between the track and the track info.
Here is my asyncTask class where I am playing the stream.
public class RadioPlayer extends AsyncTask<String, Void, Void> {
MediaPlayer mediaPlayer = new MediaPlayer();
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(String... params) {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(params[0]);
mediaPlayer.prepare();
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// might take long! (for buffering, etc)
mediaPlayer.start();
return null;
}
#Override
protected void onPostExecute(Void result) {
}
and here is the handler where I am updating the track info after every 10 seconds:
private void getSongStatistics() {
r = new Runnable() {
public void run() {
try {
title = tsp.parseInitiator();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
Log.i("title", title);
try {
String[] subTitles = title.split("-");
tvTitle.setText(subTitles[1]);
tvArtist.setText(subTitles[0]);
} catch (Exception e) {
tvArtist.setText(title);
}
handler.postDelayed(this, 10000);
}
}
};
handler.postDelayed(r, 10000);
}
Is there any solution by which I may get rid of this weird problem?
Use push instead of polling to update data.

How to embed an Internet Request Code and get results that are implemented within one OnClickListener

I am creating an Online Dictionary Android App.
I am using JSON to request for definitions for a word which the user inputs.
This input is into the variable "text" everytime the search button is clicked.
The Inputted word is then appended into the API request URL which returns the definition......which is stored in variable "result" in the bottom method OnPost Execute()
My TextView should then be set to this String.
I Therefore put the entire JSON and HTTPrequest code within the onClickLIstener because the user input always changes and requests everytime, but im getting an error at the "throws ClientProtocolException" after the "public JSONObject lastTweet(String word)" the error is "Syntax error on tokens, delete these tokens" I am Using Enclipse Indigo.
Here Is my Code:
public class Dictionary extends Activity {
String finalresult;
HttpClient client = new DefaultHttpClient();
TextView ansa;
JSONObject json;
Button Search;
EditText input;
String text;
final static String URL = "http://api.wordnik.com/v4/word.json/";
final static String URL2 = "/definitions?api_key=<MY API KEY>";
String fresult;
Dictionary dic = new Dictionary();
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.dictionary);
ansa = (TextView) findViewById(R.id.ansa);
input = (EditText) findViewById(R.id.input);
Search = (Button) findViewById(R.id.search);
Search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
text = input.getText().toString();
public JSONObject lastTweet(String word)
throws ClientProtocolException, IOException, JSONException{
new Read().execute("text");
StringBuffer strBuff = new StringBuffer();
strBuff.append(URL);
strBuff.append(word);
strBuff.append(URL2);
HttpGet get = new HttpGet(strBuff.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
}else{
Toast.makeText(Dictionary.this, "error", Toast.LENGTH_LONG);
return null;
}
}
class Read extends AsyncTask<String, Integer, String>{
#Override
public String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet(text);
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
fresult = result;
// TODO Auto-generated method stub
}
}
ansa.setText(fresult);
}
});
}
public JSONObject lastTweet(String word)
throws ClientProtocolException, IOException, JSONException{
new Read().execute("text");
StringBuffer strBuff = new StringBuffer();
strBuff.append(URL);
strBuff.append(word);
strBuff.append(URL2);
HttpGet get = new HttpGet(strBuff.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
}else{
Toast.makeText(Dictionary.this, "error", Toast.LENGTH_LONG);
return null;
}
}
class Read extends AsyncTask<String, Integer, String>{
#Override
public String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet(text);
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
fresult = result;
// TODO Auto-generated method stub
}
}
}
Any Suggestions?
Have you tried moving the request code to another class?

Categories

Resources