I am trying to make an application to show current epoch time which is being updated real time on start of a button and another button stops it. I am trying to use Async task for that purpose but I am stuck with errors as not being taken in async task can not be applied to java.lang.string.
Please help.
package com.example.sangeeta.epochtimer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.os.AsyncTask;
import android.provider.Settings.System;
import android.os.SystemClock;
import java.util.Calendar;
public class MainActivity extends ActionBarActivity {
TextView textonee;
Button start, stop;
long epochtime;
boolean pressstate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pressstate = false;
start = (Button) findViewById(R.id.button1);
stop = (Button) findViewById(R.id.button2);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pressstate = true;
new Operation().execute("");
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//shutdown();
pressstate = false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class Operation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
while (pressstate) {
Calendar rightNow = Calendar.getInstance();
// offset to add since we're not UTC
//long offset = rightNow.get(Calendar.ZONE_OFFSET) +
//rightNow.get(Calendar.DST_OFFSET);
//long sinceMidnight = (rightNow.getTimeInMillis() + offset) %
//(24 * 60 * 60 * 1000);
epochtime=rightNow.getTimeInMillis();
this.publishProgress(""+epochtime);
}
return null;
}
protected void onPostExecute(String result) {
textonee = (TextView) findViewById(R.id.textViewepo);
//textonee.setText("" + epochtime); // txt.setText(result);
// might want to change "executed" for the returned string passed
// into onPostExecute() but that is upto you
super.onProgressUpdate(result);
textonee.setText(result[0]);
}
}
};
You need to override onProgressUpdate instead of onPostExecute in order to publish progress correctly.
private class Operation extends AsyncTask<String, String, Void> {
#Override
protected void doInBackground(String... params) {
while (pressstate) {
Calendar rightNow = Calendar.getInstance();
// offset to add since we're not UTC
//long offset = rightNow.get(Calendar.ZONE_OFFSET) +
//rightNow.get(Calendar.DST_OFFSET);
//long sinceMidnight = (rightNow.getTimeInMillis() + offset) %
//(24 * 60 * 60 * 1000);
epochtime=rightNow.getTimeInMillis();
this.publishProgress(""+epochtime);
}
}
protected void onProgressUpdate(String result) {
textonee = (TextView) findViewById(R.id.textViewepo);
//textonee.setText("" + epochtime); // txt.setText(result);
// might want to change "executed" for the returned string passed
// into onPostExecute() but that is upto you
super.onProgressUpdate(result);
textonee.setText(result[0]);
}
protected void onPostExecute(Void... voids) {
// NO-OP
}
private class Operation extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
while (pressstate) {
Calendar rightNow = Calendar.getInstance();
// offset to add since we're not UTC
//long offset = rightNow.get(Calendar.ZONE_OFFSET) +
//rightNow.get(Calendar.DST_OFFSET);
//long sinceMidnight = (rightNow.getTimeInMillis() + offset) %
//(24 * 60 * 60 * 1000);
epochtime=rightNow.getTimeInMillis();
this.publishProgress(""+epochtime);
}
return null;
}
protected void onPostExecute(String result) {
textonee = (TextView) findViewById(R.id.textViewepo);
//textonee.setText("" + epochtime); // txt.setText(result);
// might want to change "executed" for the returned string passed
// into onPostExecute() but that is upto you
super.onProgressUpdate(result);
textonee.setText(result);
}
}
Try this
Related
After trawling for ages trying to find an understandable solution to my problems i gave up and came here to see if you can help.
My Objective : Update a TextView to count from 1 to 99999 every second without hanging the main thread.
package com.myapp.counter;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBackgroundThread myThread = new myBackgroundThread();
myThread.execute();
}
private class myBackgroundThread extends AsyncTask<Void,Integer,Void>
{
int maxTimer = 99999;
int i = 0;
//Assign the textView in MainActivity to a variable myCounter.
TextView myCounter = (TextView)findViewById(R.id.idCounter);
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
// Toast.makeText(getApplicationContext(),"InBackground",Toast.LENGTH_SHORT).show();
//Tried Toasting a message upon this starting but just threw an error
//Guess because i tried to add a UI component in a background task.
for(int i = 0; i < maxTimer; i++)
{
publishProgress(i);
}
return null;
}
//onProgressUpdate is never firing from publishProgress...
protected void onProgressUpdate(Integer i) {
Toast.makeText(getApplicationContext(),i,Toast.LENGTH_SHORT).show();
//Updatet he counter from 000 to 1,2,3,4 etc.
myCounter.setText(i);
}
protected void onPostExecute(Void result)
{
}
}
public void startTimer(View view)
{
TextView myText = (TextView)findViewById(R.id.textView);
// Toast.makeText(this,"Started...", Toast.LENGTH_SHORT).show();
}
public void stopTimer(View view) {
Toast.makeText(this, "Stopped...", Toast.LENGTH_SHORT).show();
}
}
I cannot seem to see why publishProgress does NOT fire from and I wanted to execute the ASyncTask from an button press.
I have 3 elements 2 buttons startTimer and stopTimer and 1 textview to update in the background.
Many thanks all.
Ty something like this :
protected class InitTask extends AsyncTask<Context, Integer, String> {
// -- run intensive processes here
// -- notice that the datatype of the first param in the class definition matches the param passed to this
// method
// -- and that the datatype of the last param in the class definition matches the return type of this method
#Override
protected String doInBackground(Context... params) {
// -- on every iteration
// -- runs a while loop that causes the thread to sleep for 50 milliseconds
// -- publishes the progress - calls the onProgressUpdate handler defined below
// -- and increments the counter variable i by one
int i = 0;
while (i <= 50) {
try {
Thread.sleep(50);
publishProgress(i);
i++;
}
catch (Exception e) {
Log.i("makemachine", e.getMessage());
}
}
return "COMPLETE!";
}
// -- gets called just before thread begins
#Override
protected void onPreExecute() {
Log.i("makemachine", "onPreExecute()");
super.onPreExecute();
}
// -- called from the publish progress
// -- notice that the datatype of the second param gets passed to this method
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
Log.i("makemachine", "onProgressUpdate(): " + String.valueOf(values[0]));
_percentField.setText((values[0] * 2) + "%");
_percentField.setTextSize(values[0]);
}
// -- called if the cancel button is pressed
#Override
protected void onCancelled() {
super.onCancelled();
Log.i("makemachine", "onCancelled()");
_percentField.setText("Cancelled!");
_percentField.setTextColor(0xFFFF0000);
}
// -- called as soon as doInBackground method completes
// -- notice that the third param gets passed to this method
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i("makemachine", "onPostExecute(): " + result);
_percentField.setText(result);
_percentField.setTextColor(0xFF69adea);
_cancelButton.setVisibility(View.INVISIBLE);
}
}
}
I have a gridView in my app containing images. Images are loaded from json over the web. I want that when a user click on any image in the gridView a new activity will open container the image clicked by the user. The images are loaded from links defined in json. I tried but didn't get desired result.
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import com.dragedy.dream.adapter.MyArrayAdapter;
import com.dragedy.dream.model.MyDataModel;
import com.dragedy.dream.parser.JSONParser;
import com.dragedy.dream.utils.InternetConnection;
import com.dragedy.dream.utils.Keys;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class memechoose extends AppCompatActivity {
private GridView gridView;
private ArrayList<MyDataModel> list;
private MyArrayAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memechoose);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/**
* Array List for Binding Data from JSON to this List
*/
list = new ArrayList<>();
/**
* Binding that List to Adapter
*/
adapter = new MyArrayAdapter(this, list);
/**
* Getting List and Setting List Adapter
*/
gridView = (GridView) findViewById(R.id.gridView);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i= new Intent(memechoose.this, MemeEditorActivity.class);
i.putExtra("image_path", list.get(position).getImage());
startActivity(i);
}
});
/**
* Just to know onClick and Printing Hello Toast in Center.
*/
if (InternetConnection.checkConnection(getApplicationContext())) {
new GetDataTask().execute();
}
}
/**
* Creating Get Data Task for Getting Data From Web
*/
class GetDataTask extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
/**
* Progress Dialog for User Interaction
*/
dialog = new ProgressDialog(memechoose.this);
dialog.setTitle("Hey Wait Please...");
dialog.setMessage("I am getting your JSON");
dialog.show();
}
#Nullable
#Override
protected Void doInBackground(Void... params) {
/**
* Getting JSON Object from Web Using okHttp
*/
JSONObject jsonObject = JSONParser.getDataFromWeb();
try {
/**
* Check Whether Its NULL???
*/
if (jsonObject != null) {
/**
* Check Length...
*/
if(jsonObject.length() > 0) {
/**
* Getting Array named "contacts" From MAIN Json Object
*/
JSONArray array = jsonObject.getJSONArray(Keys.KEY_MEME);
/**
* Check Length of Array...
*/
int lenArray = array.length();
if(lenArray > 0) {
for(int jIndex = 0; jIndex < lenArray; jIndex++) {
/**
* Creating Every time New Object
* and
* Adding into List
*/
MyDataModel model = new MyDataModel();
/**
* Getting Inner Object from contacts array...
* and
* From that We will get Name of that Contact
*
*/
JSONObject innerObject = array.getJSONObject(jIndex);
String image = innerObject.getString(Keys.KEY_MEME_PIC);
/**
* Getting Object from Object "phone"
*/
model.setImage(image);
/**
* Adding name and phone concatenation in List...
*/
list.add(model);
}
}
}
} else {
}
} catch (JSONException je) {
Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
/**
* Checking if List size if more than zero then
* Update ListView
*/
if(list.size() > 0) {
adapter.notifyDataSetChanged();
} //else {
// Snackbar.make(findViewById(R.id.parentLayout), "No Data Found", Snackbar.LENGTH_LONG).show();
// }
}
}
}
and the activity in which i want to display the images is as follows:
public class MemeEditorActivity extends AppCompatActivity {
private Toolbar toolbar;
private MemeEditorActivity selfRef;
private SharedPreferences setting;
private LinearLayout linlaHeaderProgress;
private float memeEditorLayoutWidth;
private float memeEditorLayoutHeight;
private LinearLayout tutorial;
private LinearLayout memeEditorLayout;
private MemeEditorView memeEditorView;
private ImageView forwardButtonImageView;
private Bitmap memeBitmap;
private File cacheImage_forPassing;
private File myDir;
private String dataDir;
private boolean firsttimes;
private boolean tutorialPreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_meme_editor);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
selfRef = this;
// Transparent bar on android 4.4 or above
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT)
{
Window window = getWindow();
// Translucent status bar
window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// Translucent navigation bar
window.setFlags(
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
// Initialize progress bar
linlaHeaderProgress = (LinearLayout)findViewById(R.id.linlaHeaderProgress);
linlaHeaderProgress.bringToFront();
// Initialize tutorial
setting = PreferenceManager
.getDefaultSharedPreferences(MemeEditorActivity.this);
SharedPreferences prefre = getSharedPreferences("Meme_Pref", Context.MODE_PRIVATE);
firsttimes = prefre.getBoolean("Meme_Pref", true);
tutorialPreference = setting.getBoolean("Tutor_Preference", false);
SharedPreferences.Editor firstTimeEditor = prefre.edit();
// See if tutorial is needed to be shown
tutorial = (LinearLayout)findViewById(R.id.meme_editor_tutorial);
tutorial.setEnabled(false);
tutorial.setOnClickListener(new View.OnClickListener()
{
# Override
public void onClick(View view)
{
tutorial.setVisibility(View.GONE);
tutorial.setEnabled(false);
}
});
if(firsttimes)
{
tutorial.setVisibility(View.VISIBLE);
tutorial.bringToFront();
tutorial.setEnabled(true);
firstTimeEditor.putBoolean("Meme_Pref", false);
firstTimeEditor.commit();
}
else if(tutorialPreference)
{
tutorial.setVisibility(View.VISIBLE);
tutorial.bringToFront();
tutorial.setEnabled(true);
tutorialPreference = setting.getBoolean("Tutor_Preference", false);
}
else
{
tutorial.setVisibility(View.GONE);
tutorial.setEnabled(false);
}
// Get the data directory for the app
PackageManager m = getPackageManager();
dataDir = getPackageName();
try
{
PackageInfo p = m.getPackageInfo(dataDir, 0);
dataDir = p.applicationInfo.dataDir;
myDir = new File(dataDir+"/cache");
if(!myDir.exists())
myDir.mkdirs();
if(myDir.setWritable(true))
Log.i("meme", "myDir is writable");
else
Log.i("meme", "myDir is not writable");
}catch(PackageManager.NameNotFoundException e)
{
Log.w("yourtag", "Error Package name not found ", e);
}
// Get the intent and get the image path to be the meme image
Intent shareIntent = getIntent();
String imagePath = shareIntent.getStringExtra("image_path");
// Create the SandboxView
setting = PreferenceManager
.getDefaultSharedPreferences(MemeEditorActivity.this);
// final int memeSize = Integer.valueOf(setting.getString("image_size","720"));
final int memeSize = setting.getInt("image_size", 720);
Log.i("meme", "memeSize = "+memeSize);
memeEditorLayout = (LinearLayout)findViewById(R.id.memeEditorLayout);
memeEditorLayout.setGravity(Gravity.CENTER);
try
{
Log.i("imagePath", imagePath);
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
memeEditorView = new MemeEditorView(this, bitmap);
memeEditorView.setLayoutParams(new ViewGroup.LayoutParams(memeSize, memeSize));
// Scale the sand box and add it into the layout
ViewTreeObserver viewTreeObserver = memeEditorLayout
.getViewTreeObserver();
// For getting the width and height of a dynamic layout during
// onCreate
viewTreeObserver
.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
#RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
# Override
public void onGlobalLayout()
{
memeEditorLayout.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
memeEditorLayoutWidth = memeEditorLayout.getHeight();
memeEditorLayoutHeight = memeEditorLayout.getWidth();
float scalingFactor = memeEditorLayoutWidth/(float)memeSize;
Log.i("memeEditorLayoutWidth", Float.toString(memeEditorLayoutWidth));
Log.i("ScaleFactor", Float.toString(scalingFactor));
memeEditorView.setScaleX(scalingFactor);
memeEditorView.setScaleY(scalingFactor);
}
});
memeEditorLayout.addView(memeEditorView);
// Set save button on click method
forwardButtonImageView = (ImageView)findViewById(R.id.forwardButtonImage);
forwardButtonImageView.setOnClickListener(new View.OnClickListener()
{
# Override
public void onClick(View arg0)
{
forwardButtonImageView.setEnabled(false);
Forward forward = new Forward();
forward.execute();
}
});
}catch(OutOfMemoryError e)
{
Toast.makeText(selfRef, "Your device is out of memory.", Toast.LENGTH_LONG).show();
finish();
}catch(Exception e)
{
Log.i("Meme Editor Activity", e.toString());
Toast.makeText(selfRef, "Ops, something went wrong.", Toast.LENGTH_LONG).show();
finish();
}
}
// Delete a files
private void deleteFile(File file)
{
if(file!=null)
{
Log.i("deleteFile", file.toString()+((file.exists())?" is Exist.":"is not exist!!!!"));
// Check if the file exist
if(file.exists())
// Clear the file inside if it is a directory
if(file.isDirectory())
{
String[] children = file.list();
for(int i = 0;i<children.length;i++)
{
File f = new File(file, children[i]);
if(f.delete())
Log.i("deleteFile", f.getAbsolutePath()+" is deleted....");
else
Log.i("deleteFile", f.getAbsolutePath()+" is not deleted!!!!");
}
}
}
}
# Override
protected void onPause()
{
// Hide the progress bar
linlaHeaderProgress.setVisibility(View.GONE);
forwardButtonImageView.setEnabled(true);
super.onPause();
}
# Override
protected void onResume()
{
super.onResume();
memeEditorView.setEnabled(true);
memeEditorView.resume();
}
# Override
protected void onDestroy()
{
// Try to delete cache if possible
// deleteFile(myDir);
// bp_release();
//memeEditorView.destroyDrawingCache();
super.onDestroy();
}
# Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.meme_editor, menu);
return true;
}
# Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch(item.getItemId())
{
case R.id.reset_sandbox:
memeEditorView.reset();
return true;
case R.id.action_settings:
Intent intent = new Intent(selfRef, MainActivity.class);
startActivity(intent);
return true;
case android.R.id.home:
// When the action bar icon on the top right is clicked, finish this
// activity
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// save image to a specific places
private void saveImage()
{
// Create the file path and file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String fname = timeStamp+".png";
cacheImage_forPassing = new File(myDir, fname);
// Remove duplicates
if(cacheImage_forPassing.exists())
cacheImage_forPassing.delete();
// Try save the bitmap
try
{
FileOutputStream out = new FileOutputStream(cacheImage_forPassing);
memeBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
Log.i("memeCacheLocation", cacheImage_forPassing.toString());
}catch(Exception e)
{
e.printStackTrace();
}
}
// Async task for onClick
class Forward extends AsyncTask<Object,Object,Object>
{
// Before forwarding
# Override
protected void onPreExecute()
{
super.onPreExecute();
linlaHeaderProgress.setVisibility(View.VISIBLE);
linlaHeaderProgress.bringToFront();
memeEditorView.pause();
memeEditorView.invalidate();
}
// Forwarding
# Override
protected String doInBackground(Object ... arg0)
{
Intent forward = new Intent(selfRef, MainActivity.class);
memeEditorView.setDrawingCacheEnabled(true);
memeEditorView.buildDrawingCache();
memeBitmap = Bitmap.createBitmap(memeEditorView.getDrawingCache());
saveImage();
forward.putExtra("cs4295.memcreator.memeImageCache",
cacheImage_forPassing.getPath());
startActivity(forward);
memeEditorView.setDrawingCacheEnabled(false);
return "DONE";
}
// After forwarding
# Override
protected void onPostExecute(Object result)
{
linlaHeaderProgress.setVisibility(View.GONE);
super.onPostExecute(result);
}
}
// Clear the Bitmap from memory
private void bp_release()
{
if(memeBitmap!=null&&!memeBitmap.isRecycled())
{
memeBitmap.recycle();
memeBitmap = null;
}
}
}
#AC-OpenSource E/BitmapFactory: Unable to decode stream:
java.io.FileNotFoundException:
/http:/static2.businessinsider.com/image/56e3189152bcd0320c8b5cf7-480/sammy-griner-success-kid-meme.jpg:
open failed: ENOENT (No such file or directory)
You have a slash before http
I'm trying to build an RSS reader and put the rss feed fetch as ansyctask,
that returns a feed in list view, or returns a text view saying "no internet connection"
but the app still crashes, I don't know what's wrong, can you help please.
here is the code:
package rss;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.TextView;
import com.enporan.polytechoran.R;
public class RSSActivity extends ActionBarActivity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
rssfeedget alpha = new rssfeedget();
alpha.execute();
}
private class rssfeedget extends AsyncTask<String, Void, FeedSource> {
protected void onPreExecute() {
}
#Override
protected FeedSource doInBackground(String... params) {
FeedSource f = new HttpFeedSource();
if(f!=null)
return f;
else {
return null;
}
}
#Override
protected void onPostExecute(FeedSource result){
ListView rssItemList = (ListView) findViewById(R.id.rssListview);
rssItemList.setVerticalFadingEdgeEnabled(true);
if(doInBackground()==null){
TextView tv= (TextView) findViewById(R.id.textView2);
tv.setText("No internet Connection...");
}
else{
RSSItemAdapter adapter = new RSSItemAdapter(getApplicationContext(), R.layout.rssitem, doInBackground().getFeed());
rssItemList.setAdapter(adapter);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_news, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
As #coelho pointed out, the FeedSource.getFeed() shouldn't be executed in the UI thread. You must now that the onPreExecute and onPostExecute methods are executed inside the UI thread, while the doInBackground method isn't.
Here's what you can do: in your AsyncTask class, add a private member: private List<RSSItem> result; (replace RSSItem here by the type of the collection returned by getFeed).
Then, update doInBackground:
FeedSource f = new HttpFeedSource();
if (f != null)
return f;
else {
this.result = f.getFeed(); // Execute getFeed in doInBackground
return null;
}
Then, in the onPostExecute method, you'll be able to use this private member as this:
RSSItemAdapter adapter = new RSSItemAdapter(getApplicationContext(), R.layout.rssitem, this.result);
Here is the code:
private class rssfeedget extends AsyncTask<String, Void, List<RSSItem>> {
private List<RSSItem> result;
protected void onPreExecute() {
}
#Override
protected List<RSSItem> doInBackground(String... params) {
FeedSource f = new HttpFeedSource();
if(f.getFeed()==null)
return null;
else {
this.result = f.getFeed(); // Execute getFeed in doInBackground
return result;
}
}
#Override
protected void onPostExecute(List<RSSItem> result){
if(doInBackground()==null){
TextView tv= (TextView) findViewById(R.id.textView2);
tv.setText("No internet Connection...");
}
else{
ListView rssItemList = (ListView) findViewById(R.id.rssListview);
rssItemList.setVerticalFadingEdgeEnabled(true);
RSSItemAdapter adapter = new RSSItemAdapter(getApplicationContext(), R.layout.rssitem, this.result);
rssItemList.setAdapter(adapter);
}
}
}
I have a code that only takes information from a web vía Jsoup and I want to refresh this information every second. I tried with all the code that I've found in Google and stackoverflow with no luck. Thank you very much in advance. [SOLVED]
Now I'm trying to send an array from MainActivity to another Activity called "Activity_allday" with Bundle and Intent when viewallday() function is called pressing the "btviewallday" button but with no luck. Any suggestions?
LogCat error: Could not find a method viewallday(View) in the activity class com.example.Chispa.MainActivity for onClick handler on view class android.widget.Button with id 'btviewallday'.
I've noticed that the error comes from receiving two values at viewallday(View view, Pair p). How can I receive the "Pair p" value in my viewallday function?
Here is the new app code:
[MainActivity]
public class MainActivity extends Activity {
private TextView tvmax, tvmid, tvmin, tvactualval,tvvaloractual,tvdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvdate=(TextView)findViewById(R.id.tvdate);
tvvaloractual=(TextView)findViewById(R.id.tvvaloractual);
tvmax=(TextView)findViewById(R.id.tvmaximo);
tvmid=(TextView)findViewById(R.id.tvmedio);
tvmin=(TextView)findViewById(R.id.tvminimo);
new BackGroundTask().execute();
callAsynchronousTask();
}
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
BackGroundTask performBackgroundTask = new BackGroundTask();
// PerformBackgroundTask this class is the class that extends AsynchTask
performBackgroundTask.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 1000); //execute in every 1000 ms
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class Pair
{
public String[] bar;
public String[] values;
}
public void viewallday(View view, Pair p) {
Intent intent = new Intent(this, Activity_allday.class);
Bundle bundle =new Bundle();
bundle.putStringArray("bar", p.bar);
intent.putExtras(bundle);
startActivity(intent);
}
class BackGroundTask extends AsyncTask<Void, Void, Pair> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
public String[] getValuesGraph(Document doc) {
int cont=24,var=7;
String bar[] = new String[cont];
/*
* Getting elements from the graphic in an array from 0-23. 0 it's 1:00am, 23 it's 00:00am
*/
for (cont=0; cont < 24; cont++){
String onMouseOver = doc.select("a").get(var+cont).attr("onMouseOver");
bar[cont] = onMouseOver.split("'")[9];
}
return bar;
}
public String[] getValuesFooter(Document doc) {
String values[] = new String[7];
/*
* Getting elements from the graphic footer
*/
String delimiters= "[ /]+";
Elements elements = doc.select("td.cabeceraRutaTexto");
elements.size(); // 6
/* Getting text from table */
values[0] = elements.get(0).text(); // TITLE
values[1] = elements.get(1).text(); // TEXT MAX VALUE
values[2] = elements.get(2).text(); // TEXT MIDDLE VALUE
values[3] = elements.get(3).text(); // TEXTO MIN VALUE
/* Getting numbers from table */
values[4] = elements.get(4).text().split(delimiters)[0]; // NUMBER MAX VALUE
values[5] = elements.get(5).text().split(delimiters)[0]; // NUMBER MIDDLE VALUE
values[6] = elements.get(6).text().split(delimiters)[0]; // NUMBER MIN VALUE
return values;
}
#Override
public Pair doInBackground(Void... params) {
Pair p = new Pair();
try {
URL url= new URL("http://www.myweb.com");
Document doc = Jsoup.connect(url.toString()).get();
p.bar = getValuesGraph(doc);
p.values = getValuesFooter(doc);
/*
* Getting elements from the graphic in an array from 0-23. 0 it's 1:00am, 23 it's 00:00am
*/
return p;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public String ActualHourValue() {
Format formatter = new SimpleDateFormat("H");
String onlyhour = formatter.format(new Date());
return onlyhour;
}
public void ShowDateHour(){
Calendar c = Calendar.getInstance();
SimpleDateFormat df3 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a");
String formattedDate3 = df3.format(c.getTime());
tvdate.setText("Fecha y hora actuales : "+formattedDate3);
}
#Override
protected void onPostExecute(Pair p) {
int hour = Integer.parseInt(ActualHourValue());
tvvaloractual.setText(p.bar[hour]+" €/MWh");
tvmax.setText(p.values[4]+" €/MWh");
tvmid.setText(p.values[5]+" €/MWh");
tvmin.setText(p.values[6]+" €/MWh");
ShowDateHour();
/*super.onPostExecute(p.values);*/
}
}
}
[Activity_allday]
Public class Activity_allday extends MainActivity {
private TextView tvall;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.all_day_prices);
tvall = (TextView) findViewById(R.id.tvall);
Bundle bundle = this.getIntent().getExtras();
String[] bar=bundle.getStringArray("bar");
/*tvall.setText(bar[0]);*/
}
public void back (View view) {
finish();
}
}
I'm using AsyncTask to download some files, and want to do something after all tasks finished.
Is there any easy way to do this?
Keep track of how many async tasks you have running and do something when the total is 0.
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
public int numOfTasks = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void addTask(){
numOfTasks++;
}
public void removeTask(){
numOfTasks--;
}
public void allTasksComplete(){
if(numOfTasks ==0){
//do what you want to do if all tasks are finished
}
}
class RequestTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... uri) {
String responseString = "";
return responseString;
}
#Override
protected void onPreExecute()
{
addTask(); // adds one to task count.
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
removeTask(); // subtracts one from task count.
allTasksComplete(); // checks to see if all tasks are done... task count is 0
}
}
}
AsyncTask has a callback method name onPostExecute. It will be execute when the background task finish.
You can use onPostExecute() callback when Asyn task finishes background processing, In a typical scenarion you would notify the UI (list adapter or UI Activity) that download of the File is finished and UI can refresh or populate the data.
onPreExecute(), invoked on the UI thread immediately after the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
Please have a look at this Android Ref example:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
http://developer.android.com/reference/android/os/AsyncTask.html
Example2:
https://github.com/ashutoshchauhan13/TwitterFeedApp/blob/master/TwitterFeedApp/src/com/sixthsense/twitterfeed/ui/TwitterFeedActivity.java