Multithread management in view? - android

I have 3 button and 3 textview.When i press first button i want to see 10 sec later which is writing in the first textview.i press second button i want to see someting 5 sec later which is writing in the second textview .i press third button,i want to see textview which is writing immediately.
My question how can i work all multithread in the view without lock other view? I tried ASCYNTask but it doestn work.
Can anybody give me any suggestion?
My Activity:
package com.example;
import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MyActivity extends Activity
{
Button a,b,c;
TextView ta,tb,tc;
Ascyn ascyn,ascyn2,ascyn3;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
a=(Button)findViewById(R.id.ba);
b=(Button)findViewById(R.id.bb);
c=(Button)findViewById(R.id.bc);
ta=(TextView)findViewById(R.id.ta);
tb=(TextView)findViewById(R.id.tb);
tc=(TextView)findViewById(R.id.tc);
ascyn=new Ascyn(this);
ascyn2=new Ascyn(this);
ascyn3=new Ascyn(this);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ascyn.execute();
SystemClock.sleep(5000);
ta.setText("ok");
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ascyn2.execute();
SystemClock.sleep(1000);
tb.setText("ozaman");
}
});
c.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ascyn3.execute();
tc.setText("byby");}
});
}
}
Ascyn:
package com.example;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
/**
* Created by IntelliJ IDEA.
* User: duygukahraman
* Date: 20.02.2012
* Time: 15:44
* To change this template use File | Settings | File Templates.
*/
public class Ascyn extends AsyncTask<Void,String,Void> {
private Context ctx;
ProgressDialog dialog;
public Ascyn(Context context){
ctx=context;
dialog=new ProgressDialog(ctx);
}
#Override
protected void onPreExecute() {
// dialog.setTitle("Please wait");
// dialog.show();
}
#Override
protected Void doInBackground(Void... unused) {
// SystemClock.sleep(20000);
return (null);
}
#Override
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
}

You have to create separate Async class for each thread like.
public class AscynThread1 extends AsyncTask<Void,String,Void> { // }
public class AscynThread2 extends AsyncTask<Void,String,Void> { // }
public class AscynThread3 extends AsyncTask<Void,String,Void> { // }

You don't need threads, if you simply want to write some text in a textview. Use a handler instead.
Handler handler = new Handler();
public void method() {
handler.postDelayed(new Runnable() {
public void run() {
textView.setText("Your text");
}
}, 5000);
}

Related

Method loadVideoFromAsset must be called from UI thread

I am trying to implement 360 Video Viewer in my project but I am getting an error for the line:
mVrVideoView.loadVideoFromAsset("sea.mp4", options);
This is the error
Method loadVideoFromAsset must be called from the UI thread, currently inferred
thread is worker
Following is my code:
package com.example.jal.jp;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import com.google.vr.sdk.widgets.video.VrVideoEventListener;
import com.google.vr.sdk.widgets.video.VrVideoView;
import java.io.IOException;
public abstract class VR_Video extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {
private VrVideoView mVrVideoView;
private SeekBar mSeekBar;
private Button mVolumeButton;
private boolean mIsPaused;
private boolean mIsMuted;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vr__video);
initViews();
}
public void onPlayPausePressed() {
}
public void onVolumeToggleClicked() {
}
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
private void initViews() {
mVrVideoView = (VrVideoView) findViewById(R.id.video_view);
mSeekBar = (SeekBar) findViewById(R.id.seek_bar);
mVolumeButton = (Button) findViewById(R.id.btn_volume);
mVrVideoView.setEventListener(new ActivityEventListener());
mSeekBar.setOnSeekBarChangeListener(this);
mVolumeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onVolumeToggleClicked();
}
});
}
class VideoLoaderTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... voids) {
try {
VrVideoView.Options options = new VrVideoView.Options();
options.inputType = VrVideoView.Options.TYPE_MONO;
mVrVideoView.loadVideoFromAsset("sea.mp4", options);
} catch( IOException e ) {
//Handle exception
}
return true;
}
}
public void playPause() {
}
#Override
protected void onPause() {
super.onPause();
mVrVideoView.pauseRendering();
mIsPaused = true;
}
#Override
protected void onResume() {
super.onResume();
mVrVideoView.resumeRendering();
mIsPaused = false;
}
#Override
protected void onDestroy() {
mVrVideoView.shutdown();
super.onDestroy();
}
private class ActivityEventListener extends VrVideoEventListener {
#Override
public void onLoadSuccess() {
super.onLoadSuccess();
}
#Override
public void onLoadError(String errorMessage) {
super.onLoadError(errorMessage);
}
#Override
public void onClick() {
super.onClick();
}
#Override
public void onNewFrame() {
super.onNewFrame();
}
#Override
public void onCompletion() {
super.onCompletion();
}
}
}
Please help. I tried my best but couldn't fix.
Remove AsyncTask Implementation And Call Required Methods From UI Thread
Use Below Code :
private void initViews() {
mVrVideoView = (VrVideoView) findViewById(R.id.video_view);
mSeekBar = (SeekBar) findViewById(R.id.seek_bar);
mVolumeButton = (Button) findViewById(R.id.btn_volume);
mVrVideoView.setEventListener(new ActivityEventListener());
try {
VrVideoView.Options options = new VrVideoView.Options();
options.inputType = VrVideoView.Options.TYPE_MONO;
mVrVideoView.loadVideoFromAsset("sea.mp4", options);
} catch( IOException e ) {
//Handle exception
}
mSeekBar.setOnSeekBarChangeListener(this);
mVolumeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onVolumeToggleClicked();
}
});
}
I dont know much about videoview but I show in your code that you are trying to access some the features in doInbackground method. The doINbackground method runs on a separate thread from the UI thread so that complex ant time consuming tasks do not block the UI thread. You can implement the features you are implementing in doINbackground method in the onCreate method or if you still need to use doInbackground you can access the UI thread inside doInbackground using runOnUiThread as follows
runOnUiThread(new Runnable() {
#Override
public void run() {
//your code here
}
});

Start AsyncTask in Application class; use listener to inform activity

I start in Application class, in onCreate, a background thread (AsyncTask) which does some time consuming job (between 15 - 70 seconds).
In an activity I need to make some operations only if that task started in Application onCreate() method is completed.
My solution for this is:
Application class
create an interface with a single method
in AsyncTask onPostExecute method I update the listener
I have also a boolean variable to know from poutside if asyncTask is in progress or is terminated
MyActivity class
I implement the listener
when pressing the button:
if asyncTask is in progress I set the listener and I will be informed in onCommandEnded when AsyncTask is done and do there the operations
if asyncTask job is done I do here the following operations.
I'm not sure if this is the correct way to do it...
import android.app.Application;
import android.content.Context;
import android.os.AsyncTask;
public class MyApplicationClass extends Application {
protected static MyApplicationClass instance;
public static MyApplicationClass getInstance() {
return instance;
}
private ApplicationListener listener;
public void setListener(ApplicationListener listener) {
this.listener = listener;
}
public static interface ApplicationListener {
void onCommandEnded();
}
private boolean isInProgress;
#Override
public void onCreate() {
super.onCreate();
instance = this;
CommandAsyncTask copyFfmpeg = new CommandAsyncTask();
copyFfmpeg.execute();
}
private class CommandAsyncTask extends AsyncTask<Void, Void, Double> {
#Override
protected void onPreExecute() {
super.onPreExecute();
isInProgress = true;
}
#Override
protected Double doInBackground(Void... params) {
//do some time consuming operations here
return null;
}
#Override
protected void onPostExecute(Double aDouble) {
if (listener != null) {
listener.onCommandEnded();
}
isInProgress = false;
super.onPostExecute(aDouble);
}
}
public boolean isInProgress() {
return isInProgress;
}
}
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MyActivity extends Activity implements MyApplicationClass.ApplicationListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (MyApplicationClass.getInstance().isInProgress()) {
MyApplicationClass.getInstance().setListener(MyActivity.this);
} else {
//start new asynctask
}
}
});
}
#Override
public void onCommandEnded() {
//start here new asynctask
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="#+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, MyActivity"
/>
</LinearLayout>

when don't keep activities selected on Setting , progress dialog is not dismissing

when "don't keep activities" is selected on Setting's Developer Options progress dialog is not dismissing.
Actually, I am displaying the Progerss bar,for initialize the Application, When I am going to Activity A to Activity B and then came to Activity A, the Progress bar is not dismissing after initialize completed.
Below is my Code,
First Activity
package com.example.donotkeepactivitiesalive;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
public static final int MESSAGE_PROGRESS_BAR_INITIALIZING = 1;
private Dialog m_cObjDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println(getClass().getName() + "before InitializeEnvironment >>>>>>");
new InitializeEnvironment().execute();
System.out.println(getClass().getName() + "after InitializeEnvironment >>>>>>");
Button lb = (Button) findViewById(R.id.button1);
lb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent lIntent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(lIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected Dialog onCreateDialog(int id) {
m_cObjDialog = new ProgressDialog(this);
m_cObjDialog.setTitle("Initializing");
((ProgressDialog) m_cObjDialog).setMessage("Initializing the Application");
m_cObjDialog.setCancelable(false);
return m_cObjDialog;
}
class InitializeEnvironment extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
System.out.println(getClass().getName() + "onPreExecute >>>>>>");
super.onPreExecute();
showDialog(MESSAGE_PROGRESS_BAR_INITIALIZING);
}
#Override
protected String doInBackground(String... aurl) {
System.out.println(getClass().getName() + " doInBackground >>>>>>");
return null;
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(MESSAGE_PROGRESS_BAR_INITIALIZING);
System.out.println(getClass().getName() + " onPostExecute >>>>>>");
}
}
}
Second Activity
package com.example.donotkeepactivitiesalive;
import android.app.Activity;
import android.os.Bundle;
public class SecondActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Is there any way to track this problem and work even if "don't keep activities" is enabled
I solved this, by checking the Bundle object is null or not.If the Bundle object is null then call the AsynTask class, else don't call,
if(null == savedInstanceState) {
new InitializeEnvironment().execute();
}
But make sure that your previous Activity is not overriding onActivityResult()

I can't setText() in another class in android

I have a TextView with the id android:id="#+id/yazi", and I have a button that has build in android:OnClick="gonderB"
and I can complie this code:
package com.seri.bir;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
Bilmez b;
TextView t;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = new Bilmez();
t = (TextView) findViewById(R.id.yazi);
}
public void gonderB (View v,TextView t,Bilmez b){
String s = " ..."+this;
b.yaziYaz(v,s,t);
}
}
class Bilmez {
public void yaziYaz(View v,String s,TextView t){
t.setText(s);
}
}
However I have an error.
Can I setText in another class?
You can overwrite onClick of the activity. Avoid the using of the android:OnClick="gonderB" line in the xml file. I think it is better to implement the onClickListener and attach it to View Objects within your code.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
Bilmez b;
TextView t;
Button bt;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = new Bilmez();
t = (TextView) findViewById(R.id.yazi);
Button bt = (Button) findViewById(R.id.btn);
bt.setOnClickListener(this);
}
#Override
public void onClick(View clickedView) {
switch (clickedView.getId()) {
case R.id.btn:
String s = "...." + this;
b.changeText(t,s);
break;
}} //end of main class }
In the changeText method you change the text of the TextView. This method can if be placed in another class if you like that.
class Bilmez {
public void changeText(TextView t, String s){
t.setText(s);
}
}
Perhaps what you are experiencing is a need to run the function on the UI thread?
public void yaziYaz(View v,final String s,final TextView t) {
runOnUiThread(new Runnable() {
public void run() {
t.setText(s);
}
});
}
i think you should do that:
public void gonderB (new View v,TextView t,Bilmez b){
String s = " ..."+this;
b.yaziYaz(v,s,t);
}

Display progress bar while loading

I have one button in the main.xml which will link to another xml which include information from server. I include progress bar to avoid the blank screen while the system is loading the information. i already done the code as below but it's still not the things i wanted. the code below will "WAIT" for 1000 ms then only will execute the next code. how can i modify it so that the loading "WAIT TIME" will depends on the internet speed, if internet connection is slow, then the progress-bar-screen will show longer.
package com.android.myApps;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
public class MainScr extends Activity {
private final int WAIT_TIME = 1000;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.MainScr);
}
public void onClickCategory(View view)
{
findViewById(R.id.mainSpinner1).setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
Intent mainIntent = new Intent(MainScr.this, Category.class);
MainScr.this.startActivity(mainIntent);
MainScr.this.finish();
}
}, WAIT_TIME);
}
}
The mistake you are doing here is you are dumping specific time into your code
You never know how much it will take to get response.
You should follow following approach
Step 1 Show progress dialog on screen
Step 2 Let download take its own time.But it should be done in new thread
Step 3 Once download is complete it will raise message that task is done,now remove that
progress dialog and proceed.
I am pasting sample code here.Hope it will help you.
package com.android.myApps;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
public class MainScr extends Activity
{
private Handler handler;
private ProgressDialog progress;
private Context context;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = AncActivity.this;
progress = new ProgressDialog(this);
progress.setTitle("Please Wait!!");
progress.setMessage("Wait!!");
progress.setCancelable(false);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
progress.dismiss();
Intent mainIntent = new Intent(context, Category.class);
startActivity(mainIntent);
super.handleMessage(msg);
}
};
progress.show();
new Thread()
{
public void run()
{
// Write Your Downloading logic here
// at the end write this.
handler.sendEmptyMessage(0);
}
}.start();
}
}
Did you try Asyntask? Your doing process will be update in UI.
public final class HttpTask
extends
AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {
private HttpClient mHc = new DefaultHttpClient();
#Override
protected String doInBackground(String... params) {
publishProgress(true);
// Do the usual httpclient thing to get the result
return result;
}
#Override
protected void onProgressUpdate(Boolean... progress) {
// line below coupled with
// getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS)
// before setContentView
// will show the wait animation on the top-right corner
MyActivity.this.setProgressBarIndeterminateVisibility(progress[0]);
}
#Override
protected void onPostExecute(String result) {
publishProgress(false);
// Do something with result in your activity
}
}

Categories

Resources