Android Calling Method in Activity Class - java

I have java class called Second.java which has a method called toast_method().
My question is, How can i call the toast_method() from the Second.java and then display the toast message in the app?
I tried the following code but it's not working
Second.java
package com.example.callmethod;
import android.content.Context;
import android.widget.Toast;
public class Second {
Context context;
public Second(Context context) {
this.context = context;
}
public void toast_method() {
Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show();
}
}
MainActivity.java
package com.example.callmethod;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
private Second myotherclass;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Calling the method from Second Class
myotherclass.toast_method();
}
}
Thanks

You are nearly there! Only missing the vital instantiation of the second class:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Calling the method from Second Class
myotherclass = new Second(this); // <----- this
myotherclass.toast_method();
}

do it in onCreate Like this
Second second =new Second(this);
second.toast_method();

Easy one ^^
you have to extends Activity to use context in the activity
public class operation extends Activity {
// normal toast
//you can change length
public static void toast(String toastText, Context contex) {
Toast.makeText(contex, toastText, Toast.LENGTH_LONG).show();
}
// Empty Toast for Testing
public static void emptyToast(Context contex) {
Toast.makeText(contex, R.string.EmptyText, Toast.LENGTH_LONG).show();
}
}
now ... in your activity only call function
operation.toast("Your Text",currentClass.this);
Example :
public class currentClass extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
operation.toast("Hello",currentClass.this);
}
}

Related

How to add text to TextView from Loader

Now I'm studying Threads and my task is to make a counter, which will add number from 0 to 9 to TextView with the help of Loader. Of course, I know that it isn't the best variant to use Loader for such tasks, but I'd like to understand how does it work.
So, I have the following code:
package asus.example.com.exercise4;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class LoaderActivity extends AppCompatActivity {
private TextView counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_threads);
Button startButton = findViewById(R.id.start_button);
Button cancelButton = findViewById(R.id.cancel_button);
startButton.setOnClickListener(listener);
cancelButton.setOnClickListener(listener);
counter = findViewById(R.id.counter);
}
private View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.start_button:
getSupportLoaderManager().initLoader(0, null, new LoaderClass());
break;
case R.id.cancel_button:
break;
}
}
};
#SuppressLint("StaticFieldLeak")
class AsyncTaskLoaderClass extends AsyncTaskLoader<Void>{
AsyncTaskLoaderClass(#NonNull Context context) {
super(context);
}
#Nullable
#Override
public Void loadInBackground() {
for (int i = 0; i<10;i++){
counter.setText(i);
SystemClock.sleep(500);
}
return null;
}
}
private class LoaderClass implements LoaderManager.LoaderCallbacks<Void>{
#NonNull
#Override
public Loader<Void> onCreateLoader(int i, #Nullable Bundle bundle) {
return new LoaderActivity.AsyncTaskLoaderClass(LoaderActivity.this);
}
#SuppressLint("SetTextI18n")
#Override
public void onLoadFinished(#NonNull Loader<Void> loader, Void aVoid) {
counter.setText("Done!");
}
#Override
public void onLoaderReset(#NonNull Loader<Void> loader) {
}
}
}
When I run the project I have a runtime error:
java.lang.IllegalArgumentException: Object returned from onCreateLoader must not be a non-static inner member class: AsyncTaskLoaderClass{eed39bf id=0}
Yes, I understand, that it means that AsyncTaskLoaderClass should be in another file or static, but in such case I won't have an opportunity to add text to textview. So, how can I solve this problem?
UPD
I changed the code in clicking start button in such way:
case R.id.start_button:
Loader loader = getSupportLoaderManager().initLoader(0, null, LoaderActivity.this);
loader.forceLoad();
Log.i(TAG, "Button start clicked");
break;
And now each time in the loop I have the following error:
E/e.com.exercise: Invalid ID 0x00000009.
E/EventBus: Could not dispatch event: class asus.example.com.exercise4.LoaderActivity$MyAsyncTaskLoader$ProgressEvent to subscribing class class asus.example.com.exercise4.LoaderActivity
android.content.res.Resources$NotFoundException: String resource ID #0x9
UPD 2
Finally fixed the problem in the following way:
Was
counter.setText(i);
Now
counter.setText(""+i);
Probably I don't understrand why it works, but it works
Make the Activity implement LoaderCallbacks. Also a Loader retrieves one particular value in its onLoadFinished callback, and it should return the retrieved (loaded) item as a result.
To change what value is being loaded by a Loader, you're supposed to restart the loader with a new argument bundle, and pass in the parameters so that it knows what it is doing.
Then again, you are trying to create something like "publishProgress" in AsyncTask; Loaders cannot do that out of the box, and need some variant of "sending an event" (handler threads if you are adventurous, but most likely an event bus, see implementation 'org.greenrobot:eventbus:3.1.1').
TL;DR: use EventBus for this.
public class LoaderActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Void> {
private TextView counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_threads);
Button startButton = findViewById(R.id.start_button);
Button cancelButton = findViewById(R.id.cancel_button);
counter = findViewById(R.id.counter);
startButton.setOnClickListener((view) -> {
getSupportLoaderManager().initLoader(0, null, LoaderActivity.this);
});
cancelButton.setOnClickListener((view) -> {
// do nothing, apparently
});
EventBus.getDefault().register(this);
}
#Override
protected void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onLoaderProgressEvent(MyAsyncTaskLoader.ProgressEvent event) {
counter.setText("" + event.getNumber());
}
#NonNull
#Override
public Loader<Void> onCreateLoader(int i, #Nullable Bundle bundle) {
return new MyAsyncTaskLoader(LoaderActivity.this);
}
#SuppressLint("SetTextI18n")
#Override
public void onLoadFinished(#NonNull Loader<Void> loader, Void aVoid) {
counter.setText("Done!");
}
#Override
public void onLoaderReset(#NonNull Loader<Void> loader) {
}
public static class MyAsyncTaskLoader extends AsyncTaskLoader<Void> {
public static class ProgressEvent {
private final int number;
public ProgressEvent(int number) {
this.number = number;
}
public int getNumber() { return number; }
}
public MyAsyncTaskLoader(#NonNull Context context) {
super(context);
}
#Nullable
#Override
public Void loadInBackground() {
for (int i = 0; i<10;i++){
EventBus.getDefault().post(new ProgressEvent(i));
SystemClock.sleep(500);
}
return null;
}
}
}
Your are using inner AsyncTaskLoaderClass in Activity class. Inner class holds the reference of Outer class. That means your AsyncTaskLoaderClass may hold Activity reference in some cases. Make your inner class static.
You have 2 solutions. Make AsyncTaskLoaderClass a separate class file or make AsyncTaskLoaderClass a static class.
make textview public static like this public static TextView counter;

SharedPreferences listener not working when called from class

I'm trying to clean up my code and make a class which will be only used for SharedPreference changes.
This is what I currently have:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
prefs.registerOnSharedPreferenceChangeListener(listener);
}
SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// listener implementation
if (key.equals("listEventType") || key.equals("listEventAge")) {
recreate();
}
}
};
}
This one is working great. However, as soon as I move this code to my support class:
package com.example.rok.terroristinfo;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class SharedPreferencesInit {
private Context context;
private Activity activity;
private SharedPreferences prefs;
public SharedPreferencesInit(Context context, Activity activity) {
this.context = context;
this.activity = activity;
prefs = PreferenceManager.getDefaultSharedPreferences(context);
}
protected void recreateOnChange() {
prefs.registerOnSharedPreferenceChangeListener( new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// listener implementation
if (key.equals("listEventType") || key.equals("listEventAge")) {
activity.recreate();
}
}
};
}
}
And call it from MainActivity class as:
new SharedPreferencesInit(getBaseContex(), this).recreateOnChange();
it is not working. Any suggestions?

Incompatible Java method

I'm trying to learn Java through a tutorial on Aide and have entered what I believed was the correct code:
package com.aide.trainer.myapp;
import android.app.*;
import android.os.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set main.xml as user interface layout
setContentView(R.layout.main);
final TextView textView = (TextView) findViewById(R.id.mainTextView1);
Button button = (Button) findViewById(R.id.mainButton1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View p1)
{
// TODO: Implement this method
TextView textView = (TextView) findViewById(R.id.mainTextView1);
textView.setText("Clicked");
}
});
button.setOnLongClickListener(new OnLongClickListener()
{
#Override
public void onLongClick(View p1)
{
}
});
}
}
But at public void onLongClick(View p1), there is an error around void that says:
The type of this method is incompatible with the type of the overridden method 'android.view.View.OnLongClickListener.onLongClick(android.view.View)'
I can't figure out what I did wrong. Does anyone know?
In an OnLongClickListener, onLongClick(…) must return boolean, not void.

An error occured while executing doInBackground?

Here is my code
package com.example.rollsystems;
import java.util.ArrayList;
import org.dto.Student;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;
import android.app.Activity;
import android.content.Context;
import com.example.listview.*;
import com.example.Utils.AllBO;
import com.example.rollsystems.R;
public class RollCallActivity extends Activity {
ArrayList<Student> array;
ListStudentAdapter arrayAdapter;
ListView list;
TextView txtClassAt;
TextView txtSubjectAt;
TextView txtInstructorAt;
TextView txtTimeAt;
TextView txtDateAt;
Context context;
public class RollCallTask extends AsyncTask<Void, Void, Void> {
public RollCallActivity activity;
public RollCallTask(RollCallActivity a)
{
activity = a;
}
#Override
protected Void doInBackground(Void... params) {
//SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("rs", Context.MODE_PRIVATE);
//String RollCallID = sharedPref.getString("RollCallID", "14");
String RollCallID = "14";
list = (ListView)findViewById(R.id.listAtStudent);
ArrayList<Student> rollCalls = new AllBO().getRollCallInfo(RollCallID);
array = rollCalls;
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
arrayAdapter = new ListStudentAdapter(activity, R.layout.list_atstudent, array);
list.setAdapter(arrayAdapter);
txtClassAt = (TextView) findViewById(R.id.txtClassAt);
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_rollcall);
new RollCallTask(this).execute();
txtClassAt = (TextView) findViewById(R.id.txtClassAt);
}
}
And then, when i run:
E/AndroidRuntime(883): FATAL EXCEPTION: AsyncTask #1
E/AndroidRuntime(883): java.lang.RuntimeException: An error occured while executing
doInBackground()
E/AndroidRuntime(883): at android.os.AsyncTask$3.done(AsyncTask.java:278)
every help is precious
The async task is accessing the UI. Don't do findViewById in it, use onCreate from the Activity/Fragment.
Here are also several convention issues:
String RollCallID = "14";
list = (ListView)findViewById(R.id.listAtStudent);
ArrayList<Student> rollCalls = new AllBO().getRollCallInfo(RollCallID);
array = rollCalls;
variables should never start with an uppercase rollCallID
xml id's should not be camel cased R.id.list_as_student
array is not used outside the adapter, why use a variable outside of it?
Use the Handler object from your MainActivity and post a runnable. To use it from the backgrund you need to make the object a static that you can call outside of your MainActivity or you can create a static instance of the Activity to access it.
Inside the Activity
private static Handler handler;
handler = new Handler();
handler().post(new Runnable() {
public void run() {
//ui stuff here :)
}
});
public static Handler getHandler() {
return handler;
}
Outside the Activity
MainActivity.getHandler().post(new Runnable() {
public void run() {
//ui stuff here :)
}
});
You're trying to access the UI from a background thread. You'll need to do that outside of doInBackground.
You also must call AsyncTask from the UI Thread. Failing to do so is the cause of your runtime error.
public class RollCallTask extends AsyncTask<Void, Void, Void> {
public RollCallActivity activity;
public RollCallTask(RollCallActivity a)
{
activity = a;
}
#Override
protected Void doInBackground(Void... params) {
//SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("rs", Context.MODE_PRIVATE);
//String RollCallID = sharedPref.getString("RollCallID", "14");
String RollCallID = "14";
ArrayList<Student> rollCalls = new AllBO().getRollCallInfo(RollCallID);
array = rollCalls;
return null;
}
}
And then your onCreate would be
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_rollcall);
list = (ListView)findViewById(R.id.listAtStudent);
txtClassAt = (TextView) findViewById(R.id.txtClassAt);
new RollCallTask(this).execute();
}

Call layout from another class

Here I've called layout from another class and snippet as follows
class example extends Activity{
class2 btn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn.color();
}
}
//Another class(class2)
public class class2 extends Activity{
protected void color(){
View inflatedView = getLayoutInflater().inflate(R.layout.main, null);
LinearLayout layoutcolor=(LinearLayout) inflatedView.findViewById(R.id.linearcolor);
//some code
}
}
How can I call layout id in class2 by that I can display it from class example above code floods error.
class example extends Activity {
class2 btn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = new Class2();
btn.color(this);
}
}
// Another class(class2)
public class class2 {
protected void color(Activity mActivity) {
LinearLayout layoutcolor = (LinearLayout) mActivity.findViewById(R.id.linearcolor);
// some code
}
}
UPDATE: I created a sample and it works for me, just check your implementation. OR post full code.
package com.example.test;
import android.app.Activity;
import android.app.ListActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class sampleMediaPlayer extends ListActivity {
// Toast mToast;
private TextView selection;
class2 btn;
private static final String[] items = { "Computer Hardware", "Featured", "Information Technology",
"Software", "Technical"
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
items);
setListAdapter(adapter);
btn = new class2();
btn.color(this);
}
public void onListItemClick(ListView parent, View v, int position, long id) {
selection.setText(items[position]);
}
// Another class(class2)
public class class2 {
protected void color(Activity mActivity) {
ListView layoutcolor = (ListView) mActivity.findViewById(android.R.id.list);
layoutcolor.setBackgroundColor(Color.GREEN);
Log.i("NIMISH", "HEy ");
}
}
}

Categories

Resources