It is stated in d.android.com for onPreExecute() that it runs on the UI thread before doInBackground(Params...) so it should easily access the TextView and perform setText() method from the Activity from which it was executed().
But here in the below codes the loading TextView is privately declared inside the class SplashScreen that extends Activity. Inside the onCreate() it is linked with the TextView widget of the UI. But when AsyncTask extended class Atom the function onPreExecute() is executed which throws a NullPointerExcepction for the statement loading.setText("Loading..."); executed inside it.
Here the code
public class SplashScreen extends Activity implements AnimationListener{
...
TextView loading=null;
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
try {
a = (Atom) new Atom().execute(null,null,null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
finish();
}
...
loading = (TextView) findViewById(R.id.textView2);
....
}
public class Atom extends AsyncTask<RSSFeed, Void, RSSFeed>{
private RSSReader reader;
private RSSFeed feed = null;
private String uri = "http://website.com/feed/";
#Override
protected void onPreExecute() {
super.onPreExecute();
//------------problem----area-------------------
loading.setText("Loading...");
//------------problem----area-------------------
}
#Override
protected RSSFeed doInBackground(RSSFeed... arg0) {
reader = new RSSReader();
try {
feed = reader.load(uri);
Log.d("rss", feed.getTitle());
} catch (RSSReaderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return feed;
}
#Override
protected void onPostExecute(RSSFeed result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
prg.cancel();
t(result.getTitle().toString());
}
}
}
The stack:
03-09 10:50:12.793: W/System.err(14214): java.lang.NullPointerException
03-09 10:50:12.813: W/System.err(14214): at in.edu.ss.er.splash.SplashScreen$Atom.onPreExecute(SplashScreen.java:158)
03-09 10:50:12.827: W/System.err(14214): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
03-09 10:50:12.833: W/System.err(14214): at android.os.AsyncTask.execute(AsyncTask.java:534)
03-09 10:50:12.833: W/System.err(14214): at in.edu.ss.er.splash.SplashScreen.onCreate(SplashScreen.java:45)
Try to initialize TextView before executing asyntask. Like following.
try {
loading = (TextView) findViewById(R.id.textView2);
a = (Atom) new Atom().execute(null,null,null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
finish();
}
I don't know this is correct or not, This my guessing, So, Please let me know what happened.
Thanks
just initialize your text view before calling AsyncTask. do something like this
loading = (TextView) findViewById(R.id.textView2);
try {
a = (Atom) new Atom().execute(null,null,null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
finish();
}
You have to initialize your textview before then call asynctask. Change your code into following-
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
loading = (TextView) findViewById(R.id.textView2);
try {
a = (Atom) new Atom().execute(null,null,null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
finish();
}
}
Related
I am working on an android app development and I am stuck in an issue. I have used ANSYNC TASK method but now it has stopped working.
It was working fine from last many years but now it is creating problem.
Also, doinbackground() and postExecute() methods are not working (they are not called) only preExecute() method is working for me.
I am attaching code here for the reference:
class MyAsyncTask extends AsyncTask<Void, ConversationModel, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
heading.setText("myheading");
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (ConversationModel model : dataList) {
if (flagStop)
break;
publishProgress(model);
long_time = Long.parseLong(model.sound_time) * 1000 + 500;
try {
Thread.sleep(long_time);
Thread.sleep(long_extraTime);
long_extraTime = 0;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i++;
Log.d("i", i + " -----------------");
}
return null;
}
protected void onProgressUpdate(ConversationModel... model) {
if (i % 2 == 0) {
View v = View.inflate(Conversation1.this, arrInt_resource[0], null);
v.setAnimation(null);
TextView txtV_spn = (TextView) v.findViewById(R.id.textView_spn);
TextView txtV_eng = (TextView) v.findViewById(R.id.textView_eng);
ImageView img_sound = (ImageView) v.findViewById(R.id.imgsound_conv_spn2eng);
RelativeLayout speak_layout = (RelativeLayout) v.findViewById(R.id.speaking_layout);
heading.setText(dataList.get(0).heading);
if (flag != 1) {
txtV_spn.setText(model[0].eng_txt);
txtV_eng.setText(model[0].spn_txt);
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (i >= dataList.size()) {
Log.d("i", i + " ------------------");
makingcontinueImageView();
}
}
}
i think you are using .execute() method of asynctask to start execute of asynctask, change that line of code with this one
asynctask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
E/MediaPlayer: EventHandler handleMessage thread id is 1
E/MediaPlayer: EventHandler handleMessage thread id is 1
E/MediaPlayer: currentThread is 1, handleMessage mTimeProvider hashcode is 1112571032, mTimeProvider is android.media.MediaPlayer$TimeProvider#42507c98, msg is { when=-19ms what=7 target=android.media.MediaPlayer$EventHandler }
I get the above error when trying to play audio, any ideas why I get this error, the same code works in some places, I'm calling the static function from a fragment?
Global.playAudio("sounds/add_comment.mp3",context);
public static void playAudio(String aud, Context context) {
final MediaPlayer mp;
try {
AssetFileDescriptor fileDescriptor =
context.getAssets().openFd(aud);
mp = new MediaPlayer();
mp.setDataSource(fileDescriptor.getFileDescriptor(),
fileDescriptor.getStartOffset(),
fileDescriptor.getLength());
fileDescriptor.close();
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Let me know if this helped -
public class MainActivity extends AppCompatActivity implements MediaPlayer.OnPreparedListener,AudioManager.OnAudioFocusChangeListener{
MediaPlayer mp;
AudioManager mAudioManager ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int result = mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
//got audio focus
playAudio("bell.mp3",this);
}
}
private void playAudio(String aud, Context context) {
try {
AssetFileDescriptor fileDescriptor =
context.getAssets().openFd(aud);
mp = new MediaPlayer();
mp.setDataSource(fileDescriptor.getFileDescriptor(),
fileDescriptor.getStartOffset(),
fileDescriptor.getLength());
fileDescriptor.close();
mp.prepareAsync();
mp.setOnPreparedListener(this);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mp.start();
}
#Override
public void onAudioFocusChange(int i) {
}
}
Here, I am first trying to get the audio focus and then letting the mediaplayer do the task asynchronously.
Im using ListView and Jsoup to create simple app that shows photos from a website, anyone can tell me why does the emulator crushes everytime? what's the problem with the code?
public class MainActivity extends Activity{
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
listView = (ListView) findViewById( R.id.listview);
final ArrayList list = new ArrayList();
Document doc = null;
try {
doc = (Document) Jsoup.connect("http://mongol.co.il/").get();
Elements divs = ((Elements) doc).select("img[src$=.jpg]");
for (org.jsoup.nodes.Element div : divs)
{
list.add(div);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);
}
}
Hello I had this also in my application.
The solution is fairly simple:
All Networking actions have to be done in an Asyntask or Thread
I personally use an Asynctask like this:
private class LoadImages extends AsyncTask<Void, Void, Void> {
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// Here you can do any UI operations like textview.setText("test");
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
Document doc = null;
try {
doc = (Document) Jsoup.connect("http://mongol.co.il/").get();
Elements divs = ((Elements) doc).select("img[src$=.jpg]");
for (org.jsoup.nodes.Element div : divs)
{
list.add(div);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return null;
}
Don't make http requests in your onCreate, this will throw an exception in ICS and above, I think, because you are blocking the UI thread.
I was just testing mediaplayer in android, i started a stream in the onCreate method and I have a button that calls the finish() method. After clicking the button I can still hear the stream playing even though the activity is close, I am wondering if this is a leak of sorts and i will have to stop the player first before calling the finish() method, or if finish() method actually does not full kill the app to free up resources. Thank you for reading
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button add_function,exit_btn;
add_function = (Button) findViewById(R.id.view_chat);
exit_btn = (Button) findViewById(R.id.exit_btn);
MediaPlayer mp = new MediaPlayer();
String URL_OF_FILE = "http://stream.radiosai.net:8002/";
try {
mp.setDataSource(URL_OF_FILE);
mp.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
exit_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}// EOF ONCREATE
Calling finish() does not kill the application, it just destroys the current Activity that you're finishing. Although I would think finishing the Activity would stop the MediaPlayer, what you should probably do in this case is override onDestroy(), and release your MediaPlayer object there. For instance:
#Override
public void onDestroy() {
if(mediaPlayer != null) mediaPlayer.release();
super.onDestroy();
}
As I can refresh the content of an activity?, for example, I have a menu and a button send me an application content that displays information online, but to go back and return again, the information is not updated.
This is my Activity.
public class Bovalpo extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bovalpo);
Button buttonExit = (Button)this.findViewById(R.id.cerrar);
buttonExit.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
System.exit(0);
}
}
);
TextView myListView = (TextView) findViewById(R.id.tv);
try {
myListView.setText(getPage());
if(getPage().contains("Abierto")){
myListView.setTextColor(Color.parseColor("#008000"));
}else{
myListView.setTextColor(Color.parseColor("#FF0000"));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String getPage() throws MalformedURLException, IOException {
HttpURLConnection con = (HttpURLConnection) new URL("http://www.bovalpo.com/cgi-local/xml_bcv.pl?URL=1").openConnection();
con.connect();
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
return inputStreamToString(con.getInputStream());
} else {
return null;
}
}
private String inputStreamToString(InputStream in) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append("Mercado: " + line + "\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
public void lanzar(View view){
Intent i = new Intent(this, xml7009.class);
startActivity(i);
}
public void lanzar3(View view){
Intent i = new Intent(this, tabla7009.class);
startActivity(i);
}
public void lanzar4(View view){
Intent i = new Intent(this, xml6503.class);
startActivity(i);
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
}
put your code here
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// make your work to data bind
}
The code that fetches your data and sets list view color should be put in onResume() instead of onCreate if you want it to run each time your Activity is shown.
Simply you can put your update code in the onResume() method of the activity. OnResume() method will be called when ever you return from the other activity.
But onResume() method is often called when your activity is resume for example. If you open and dismiss the dialog then your activity will be Resume. SO if you are calling some network call in onResume then it will consume the process and Network speed.
The alternate solution is use startActivityForResult() method to receive the result from the next activity and bases of the activity result you can call your web API or any work. You can get the result of the next activity in onActivityResult() method.
But before using the startActivityForResult method ensure that the next activity will set the result by calling setResult() method.
If you want to update your data every time you came to activity, you need to set your updated values in onResume
like below
#Override
protected void onResume() {
super.onResume();
try {
myListView.setText(getPage());
if(getPage().contains("Abierto")){
myListView.setTextColor(Color.parseColor("#008000"));
}else{
myListView.setTextColor(Color.parseColor("#FF0000"));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}