How can I Create a class AsynkTask in which the class DataContainer is filled. Continue to fill the class DataContainer with synthetic data. After each new one Record should pause the AsynkTask class for a short time (200ms).?
public class DataContainer {
public ArrayList<String> mGlobalDataStore1 = initializeData();
static ArrayList<String> initializeData(){
ArrayList<String> data = new ArrayList<String>();
for (Integer i=0; i<100; i++){
data.add("Item " + i.toString());
}
return data;
}
}
public class TestTask extends AsyncTask<Character, String, ArrayList<String>> {
#Override
protected ArrayList<String> doInBackground(Character... integers) {
return null;
}
#Override
protected void onProgressUpdate(String... values) {
}
#Override
protected void onPostExecute(ArrayList<String> s) {
}
}
how can I implement the class DataContainer in class AsyncTask?
public class MainActivity extends AppCompatActivity {
private ProgressBar progressBar;
private AsyncTask asyncTask;
private RecyclerView recyclerView;
private DataContainer fragment;
private TextView textView;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater= getMenuInflater();
inflater.inflate(R.menu.refresh, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.item1:
Toast.makeText(this,"erfolgreich",Toast.LENGTH_SHORT).show();
return true;
default:
Toast.makeText(this," nicht erfolgreich",Toast.LENGTH_SHORT).show();
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar=findViewById(R.id.progressBar);
textView=findViewById(R.id.textView);
}
I understand that this is not the answer you are looking for. But the AsyncTask api is deprecated from Android 11. Read this link for more info
Related
i have all my async calls in their own classes and so i dont want to have global vars being set aync'ly. To do this i want to return objects eg a string from my asunc postProcess methods.
can this be done?
Below is my general structure to my classes, i want to return a String for example from onPostExecute(). I see delegates are mentioned in other places but this seems very messy, sure there is a way to have a return type to the class or methods?
class GetStuffAsyncly extends AsyncTask<String, String, String>
{
// my vars....
public myconstructor(String dialogMessage, Context con)
{
this.qDialog = new ProgressDialog(con);
this.dialogString = dialogMessage;
this.context = con;
}
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute()
{
super.onPreExecute();
do stuff like fire dialog
}
#Override
protected String doInBackground(String... args)
{
// do stuff in background...
return data;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String jsonString)
{
// dismiss the dialog after getting all data
dialog.dismiss();
}
}
Some thing like below
class GetStuffAsyncly extends AsyncTask<String, String, String> {
String dialogString;
ProgressDialog dialog;
Context context;
AsyncListener listener;
// my vars....
public GetStuffAsyncly(String dialogMessage, Context con, AsyncListener listener) {
this.dialog = new ProgressDialog(con);
this.dialogString = dialogMessage;
this.context = con;
this.listener = listener;
}
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
listener.onTaskStarted();
}
#Override
protected String doInBackground(String... args) {
// do stuff in background...
return data;
}
/**
* After completing background task Dismiss the progress dialog
**/
protected void onPostExecute(String jsonString) {
// dismiss the dialog after getting all data
dialog.dismiss();
listener.onTaskFinished(jsonString);
}
}
And the listener class
public interface AsyncListener {
void onTaskStarted();
void onTaskFinished(String data);
}
and you can call like this
new GetStuffAsyncly(message, this, new AsyncListener() {
#Override
public void onTaskStarted() {
//do your stuff
}
#Override
public void onTaskFinished(String data) {
//Do your stuff;
}
}).execute(parameter);
Another option is to use AsyncTaskLoader. You derive your class not from AsyncTask, but from AsyncTaskLoader. In your Activity you need to implement LoaderCallbacks interface. The args you want to use in Loader, you put in Bundle. All information you want to get from Loader will be passed in method onLoadFinished(). Here's an example
public class BaseInitLoader extends AsyncTaskLoader<Employee[]> {
Context mContext;
boolean firstrun;
public BaseInitLoader(Context context, Bundle args) {
super(context);
mContext = context;
firstrun = args.getBoolean("firstrun");
}
#Override
protected void onStartLoading() {
super.onStartLoading();
forceLoad();
}
#Override
public Employee[] loadInBackground() {
MainActivity activity =(MainActivity) mContext;
Cursor cursor = new DatabaseFiller(activity.getDb(), mContext, firstrun).fillTable();
ArrayList<Employee> list = new ArrayList<>();
QueryResultIterable<Employee> itr = null;
try {
itr = cupboard().withCursor(cursor).iterate(Employee.class);
for(Employee employee: itr){
list.add(employee);
}
} finally {
// close the cursor
if (itr != null) {
itr.close();
}
}
Employee[] employees = new Employee[list.size()];
employees = list.toArray(employees);
return employees;
}
}
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks, View.OnClickListener {
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
TextView priority, name, innerPhone, mobilePhone, position;
Button cityBtn;
CharSequence[] cities;
SQLiteDatabase db;
Context mContext;
private Cursor cursor;
private SQLiteDatabase database;
private ListView listView;
private TextView nameTxt;
private EmployeeAdapter adapter;
public static final String LOG_TAG = "Database";
SharedPreferences prefs;
private boolean firstrun;
private ViewPager viewPager;
private TabLayout tabLayout;
private final int INITIAL = 1;
private final int SORT_NAME = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
Bundle args = new Bundle();
prefs = getSharedPreferences("ua.lanet.PipBoy", MODE_PRIVATE);
if(prefs.getBoolean("firstrun", true)){
args.putBoolean("firstrun", true);
prefs.edit().putBoolean("firstrun", false).apply();
}
else{
args.putBoolean("firstrun", false);
}
getLoaderManager().initLoader(INITIAL, args, this);
PipBoyDataHelper helper = new PipBoyDataHelper(this);
db = helper.getWritableDatabase();
}
public SQLiteDatabase getDb() {
return db;
}
#Override
public Loader onCreateLoader(int id, Bundle args) {
return new BaseInitLoader(mContext, args);
}
#Override
public void onLoadFinished(Loader loader, Object data) {
//do something with the data. Cast Object to your return type of loader
}
#Override
public void onLoaderReset(Loader loader) {
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.text:
getLoaderManager().initLoader(SORT_NAME, null, this);
break;
}
}
private class ViewPagerAdapter extends FragmentPagerAdapter{
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
}
}
I have a problem with code. I have two classes: MainActivity where i checking if sensor (in this case light sensor) is available and if yes - i try to get date from sensor from another class LightSensor, but result is always null. I think that i'm doing something wrong with listener but i don't know what.. and i'm sitting on this couple of hours and still nothing.. If you have any idea, please write and help me.
MainActivity class:
`public class MainActivity extends Activity implements EventListener {
SensorManager mSensorManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView wyswietl = (TextView)findViewById(R.id.res);
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
LightSensor mLightSensor = new LightSensor(getBaseContext());
if (mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT) != null){
//mLightSensor.register();
String newLux = mLightSensor.getLux();
wyswietl.setText("Light level: " + newLux);
}
else{
}
}
#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;
}`
and in MainActivioty class i don't know it argument in constructor :
LightSensor mLightSensor = new LightSensor(getBaseContext()); is good...
LightSensor class:
`public class LightSensor implements SensorEventListener {
public SensorManager mSensorManagerx;
public Sensor lightManager;
public String lux;
Context context;
public LightSensor(Context context){
//public void onCreateLight(Context context){
this.context = context;
mSensorManagerx = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
lightManager = mSensorManagerx.getDefaultSensor(Sensor.TYPE_LIGHT);
}
public void register(){
mSensorManagerx.registerListener(this, lightManager, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
lux = Float.toString(event.values[0]);
}
public String getLux(){
return lux;
}
public void unregister(){
mSensorManagerx.unregisterListener(this);
}
}`
You should not use a getter for this purpose, because the value your getting will be initialized after a unknown time. So it could still be null when you're calling the getLux method.
What you should do is use a listener pattern. I have changed your code a bit to give you an example implementation.
LightSensor:
public class LightSensor implements SensorEventListener {
public static interface LightSensorListener {
abstract void onLightSensorChanged(String lux);
}
private LightSensorListener listener;
private SensorManager mSensorManagerx;
private Sensor lightManager;
public LightSensor(Context context) {
mSensorManagerx = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
lightManager = mSensorManagerx.getDefaultSensor(Sensor.TYPE_LIGHT);
}
public void setListener(LightSensorListener listener) {
this.listener = listener;
}
public boolean register() {
return mSensorManagerx.registerListener(this, lightManager, SensorManager.SENSOR_DELAY_UI);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
if (listener != null) {
listener.onLightSensorChanged(Float.toString(event.values[0]));
}
}
public void unregister() {
mSensorManagerx.unregisterListener(this);
}
}
Activity:
public class ActivityLightSensor extends Activity implements LightSensorListener {
private TextView text;
private LightSensor mLightSensor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView)findViewById(R.id.test);
mLightSensor = new LightSensor(getBaseContext());
mLightSensor.setListener(this);
}
#Override
public void onLightSensorChanged(String lux){
text.setText("Light level: " + lux);
}
#Override
protected void onResume() {
super.onStart();
if(!mLightSensor.register()){
Toast.makeText(this, "Light sensor not supported!", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onPause() {
super.onStop();
mLightSensor.unregister();
}
}
onSensorChanged event is not called just after you created listener. It is called after something will change sensot value, then it will be called. So you should implement some callback, or, as for me, better would be to implement SensorEventListener in your activity, then just in onSensorChanged event method call
wyswietl.setText("Light level: " + newLux);
I have a Drawscreen.class file which the main activity and Drawthegraph.class which extends view. I have a method in Drawthegraph.class which I need to call from Drawscreen.class.How can I do that?
Drawscreen.class-
public class Drawscreen extends ActionBarActivity
{
//LinearLayout linear=(LinearLayout)findViewById(R.id.main_layout);
//draw=(Drawthegraph)findViewById(R.id.main_layout);
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
ActionBar actionbar=getSupportActionBar();
actionbar.show();
View drawthegraph=new Drawthegraph(this);
setContentView(drawthegraph);
drawthegraph.setBackgroundColor(color.Ivory);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.drawscreen, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
case R.id.undo:/*Call method of view here*/
break;
}
return super.onOptionsItemSelected(item);
}
}
Drawthegraph.class
public class Drawthegraph extends View
{
private int lines;
----
----
public void decrease_lines() /*Call this function from Drawscreen*/
{
if(lines>0)
{
lines--;
}
}
Use your drawthegraph variable as an instance field:
public class Drawscreen extends ActionBarActivity
{
//LinearLayout linear=(LinearLayout)findViewById(R.id.main_layout);
//draw=(Drawthegraph)findViewById(R.id.main_layout);
private Drawthegraph drawthegraph;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
ActionBar actionbar=getSupportActionBar();
actionbar.show();
this.drawthegraph=new Drawthegraph(this);
setContentView(drawthegraph);
drawthegraph.setBackgroundColor(color.Ivory);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.drawscreen, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
case R.id.undo:/*Call method of view here*/
drawthegraph.decrease_lines();
break;
}
return super.onOptionsItemSelected(item);
}
}
Your Drawthegraph object must be a field of your Activity:
public class Drawscreen extends ActionBarActivity {
Drawthegraph drawthegraph;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
...
drawthegraph = new Drawthegraph(this);
setContentView(drawthegraph);
drawthegraph.setBackgroundColor(color.Ivory);
}
...
then you can call wherever you want in your Drawscreen:
drawthegraph.decrease_lines();
I am trying to make listener interface between two activities Act1 and Act2. Act1 will start Act2. If there is some event occurred in Act2, it will inform it to Act1. Problem is that I am starting new activity using Intent, so how Act1 will assign itself as listener to Act2's interface?
Act1.java
public class Act1 extends ActionBarActivity implements
ActionBar.OnNavigationListener {
ActionBar actionbar;
Intent pizzaIntent;
boolean visibleFirstTime = true;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menutab);
//set actionbar here
}
#Override
public boolean onNavigationItemSelected(int arg0, long arg1)// item pos,
// itemid
{
switch (arg0) {
case 0:
if(this.visibleFirstTime == false)
{
if(pizzaIntent == null)
{
pizzaIntent = new Intent(this,Act2.class);
//how to call setChangeListener?
}
startActivity(pizzaIntent);
}
else
this.visibleFirstTime = false;
break;
case 1:
System.out.println("selected: " + arg0);
break;
case 2:
System.out.println("selected: " + arg0);
break;
case 3:
System.out.println("selected: " + arg0);
break;
default:
break;
}
return true;
}
}
Act2.java
public class Act2 extends Activity {
selectionChangeListener listener;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pizza_slice_selection);
}
public void setChangeListener(selectionChangeListener listener)
{
this.listener = listener;
}
private interface selectionChangeListener
{
public void selectionMadeAtIndex(int index);
}
}
Note: Please don't suggest me to use fragments. I want to use activities currently.
I would suggest to create a model class. Let me give you an example:
Model class:
public class CustomModel {
public interface OnCustomStateListener {
void stateChanged();
}
private static CustomModel mInstance;
private OnCustomStateListener mListener;
private boolean mState;
private CustomModel() {}
public static CustomModel getInstance() {
if(mInstance == null) {
mInstance = new CustomModel();
}
return mInstance;
}
public void setListener(OnCustomStateListener listener) {
mListener = listener;
}
public void changeState(boolean state) {
if(mListener != null) {
mState = state;
notifyStateChange();
}
}
public boolean getState() {
return mState;
}
private void notifyStateChange() {
mListener.stateChanged();
}
}
And here's how you would use this:
// Imports
public class MainActivity extends Activity implements OnCustomStateListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomModel.getInstance().setListener(this);
boolean modelState = CustomModel.getInstance().getState();
Log.d(TAG, "Current state: " + String.valueOf(modelState));
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
#Override
public void stateChanged() {
boolean modelState = CustomModel.getInstance().getState();
Log.d(TAG, "MainActivity says: Model state changed: " +
String.valueOf(modelState));
}
}
Changing the member state in second activity:
// Imports
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CustomModel.getInstance().changeState(true);
}
}
LogCat output:
Current state: false
MainActivity says: Model state changed: true
Have you considered using LocalBroadcastManager?
In Act1's onCreate:
act2InitReceiver= new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
// do your listener event stuff
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(act2InitReceiver, new IntentFilter("activity-2-initialized"));
In Act1's onDestroy:
LocalBroadcastManager.getInstance(this).unregisterReceiver(act2InitReceiver);
In Act2's onCreate:
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("activity-2-initialized"));
Give me a comment if the code doesn't compile, I'm writing it by hand.
The best, shortest and the easiest way to do this is to use static variables, like this:
class Main extends Activity {
static String message = "Hi";
}
class Another extends Activity {
public onCreate() {
Log.i(Main.message); // implementation of the message, 'Hi'
}
}
I made 2 activities and an Intent extended class named SomeSpecialIntent, when you press on the first activity's textview you go to the second using new SomeSpecialIntent class instnace, but something strange goes with it on the way, because the phrase getIntent() instnaceof SomeSpecialIntent returns false on the second activity!
whats up with that?
the code for the check i made:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView)findViewById(R.id.textView1);
textView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new SomeSpecialIntent(MainActivity.this,SomeActivity.class));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
public class SomeActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Check",""+(getIntent() instanceof SomeSpecialIntent));//returns false!!!!
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
public class SomeSpecialIntent extends Intent {
public SomeSpecialIntent(Context context,
Class<?> class1) {
super(context,class1);
}
}