Unable to update textview from callback method - java

I have an interface implemented in MainActivity, and inside that callback method i want to update my TextView but i am getting nullpointer exception.
This is my MainActivity class
public class MainActivity extends AppCompatActivity implements GenericCallback
{
Context mcontext;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mcontext = this;
Button btn = findViewById(R.id.btn);
tv = findViewById(R.id.tv);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
startActivity(new Intent(MainActivity.this,SecondActivity.class));
}
});
}
#Override
public void doSomething(Context context, String... a)
{
Toast.makeText(context,"Calback"+a[0]+a[1],Toast.LENGTH_SHORT).show();
tv = findViewById(R.id.tv);//Line 43
tv.setText(a[0]+a[1]);
}
My interface looks like this
public interface GenericCallback
{
void doSomething(Context context, String... a);
}
My SecomdActivity
public class SecondActivity extends AppCompatActivity
{
Context context;
GenericCallback genericCallback = new MainActivity();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
context = this;
String a="Secomd",b = "Activity";
genericCallback.doSomething(context,a,b);
finish();
}
}
StackTrace
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'android.view.Window$Callback
android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImplBase.(AppCompatDelegateImplBase.java:117)
at android.support.v7.app.AppCompatDelegateImplV9.(AppCompatDelegateImplV9.java:149)
at android.support.v7.app.AppCompatDelegateImplV14.(AppCompatDelegateImplV14.java:56)
at android.support.v7.app.AppCompatDelegateImplV23.(AppCompatDelegateImplV23.java:31)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:200)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:183)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
at android.com.callback.MainActivity.doSomething(MainActivity.java:43)
at android.com.callback.SecondActivity.onCreate(SecondActivity.java:21)
I already know what is nullpointer, I already referred this and this

You can use EventBus Library
For installation
compile 'org.greenrobot:eventbus:3.1.1'
First, create a Java class
public class MsgEvent {
String oo;
public String getOo() {
return oo;
}
public void setOo(String oo) {
this.oo = oo;
}
}
Then in SecondActivity
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
context = this;
String a="Secomd",b = "Activity";
MsgEvent msgEvent = new MsgEvnet();
msgEvent.setOo(a);
EventBus.getDefault().post(msgEvent);
finish();
}
Then in MainActivity
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MsgEvent event) {
String value = event.getOo();
}

You can use BroadcastReceiver
check the below example
MainActivity
public class MainActivity extends AppCompatActivity {
TextView mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = findViewById(R.id.toolbar_title);
startActivity(new Intent(this, SecondActivity.class));
}
private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mTitle.setText(intent.getStringExtra("DATA"));
Toast.makeText(context, "recieved text : " + intent.getStringExtra("DATA"), Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onResume() {
IntentFilter filter = new IntentFilter();
filter.addAction("MY_ACTION");
registerReceiver(myBroadcastReceiver, filter);
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
}
XML form MainActivity
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbarIcon"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Nilesh"
android:textStyle="bold" />
</LinearLayout>
Second_activity
public class SecondActivity extends AppCompatActivity {
TextView tvText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
getSupportActionBar().setTitle("SECOND Activity");
tvText = findViewById(R.id.tvText);
tvText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendBroadcast();
}
});
}
public void sendBroadcast() {
Intent broadcast = new Intent();
broadcast.putExtra("DATA", "MY NAME IS NILESH");
broadcast.setAction("MY_ACTION");
sendBroadcast(broadcast);
}
}
LAYOUT for second activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondActivity">
<TextView
android:layout_width="match_parent"
android:id="#+id/tvText"
android:text="Click to Send Broadcas"
android:layout_height="wrap_content" />
</LinearLayout>

The reason you are getting that null exception is that your MainActivity view is not inflated because it is not instantiated by the framework.
You can create an instance getter method from your first activity.
private static GenericCallback instance;
public static GenericCallback getHandler() {
return instance;
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
...
instance = this;
...
}
And then on your 2nd activity, get that instance instead of instantiating an activity.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
context = this;
String a="Secomd",b = "Activity";
GenericCallback genericCallback = MainActivity.getHandler();
genericCallback.doSomething(context,a,b);
finish();
}

Related

Android: How can I use ringtone.stop in activity by click button

I have Mybroadcastreceiver and when rintone is play stopAlarm.java page is shown If button is pressed i want to use stop ringtone. How can I use r.stop() in my stopAlarm.java
public class MyBroadcastReceiver extends BroadcastReceiver {
public static final String NOTIFICATION_CHANNEL_ID = "10001" ;
private final static String default_notification_channel_id = "default" ;
#Override
public void onReceive(Context context, Intent intent) {
Uri notificationsound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
Ringtone r = RingtoneManager.getRingtone(context,notificationsound);
r.play();
Intent i = new Intent(context,stopAlarm.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
public class stopAlarm extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stop_alarm);
Button stop = (Button)findViewById(R.id.stopAlarm);
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//////////How can I get r
}
});
}
}
public class stopAlarm extends AppCompatActivity {
Ringtone r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stop_alarm);
Button stop = (Button)findViewById(R.id.stopAlarm);
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
r.stop();
}
});
}

Display words in a recyclerview from a second activity

I am trying to display a word from a second activity to my main activity which is inform of a recycler view with a textview item.
I have created my adapter and I am assuming it works fine the only problem is once I launch my floating button to access my display word activities it does not display on the main activity, what am I doing wrong, I am new to Android.
My Adapter :
public class RoomAdapter extends RecyclerView.Adapter<RoomAdapter.RoomViewHolder> {
private List <RoomPojo> word;
public RoomAdapter(List <RoomPojo> word1){
this.word = word1;
}
#NonNull
#Override
public RoomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View layoutInflater = LayoutInflater.from(parent.getContext()).inflate(R.layout.word_item,parent,false);
return new RoomViewHolder(layoutInflater);
}
#Override
public void onBindViewHolder(#NonNull RoomViewHolder holder, int position) {
holder.wordTextView.setText(word.get(position).getWord());
}
#Override
public int getItemCount() {
return word.size();
}
public class RoomViewHolder extends RecyclerView.ViewHolder{
private TextView wordTextView;
public RoomViewHolder(View itemView) {
super(itemView);
wordTextView = itemView.findViewById(R.id.display_word);
}
}
}
Here is my Main activity:
public class MainActivity extends AppCompatActivity {
private RoomAdapter roomAdapter;
public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.rv_word);
recyclerView.setAdapter(roomAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
FloatingActionButton floatingActionButton = findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), DisplayWord.class);
String word = getIntent().getStringExtra(DisplayWord.EXTRA_KEY);
startActivityForResult(intent,NEW_WORD_ACTIVITY_REQUEST_CODE);
}
});
}
}
Here is my display word which has a button and a edit text which should take just one string.
public class DisplayWord extends AppCompatActivity {
public static final String EXTRA_KEY = "key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_word);
final EditText editText = findViewById(R.id.word_edit_text);
Button button = findViewById(R.id.word_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent replyIntent = new Intent();
if(TextUtils.isEmpty(editText.getText())){
setResult(RESULT_CANCELED, replyIntent);
}else {
String word = editText.getText().toString();
replyIntent.putExtra(EXTRA_KEY,word);
}
finish();
}
});
}
}
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_word"
android:layout_width="368dp"
android:layout_height="433dp"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginLeft="328dp"
android:layout_marginStart="328dp"
android:layout_marginTop="12dp"
android:src="#drawable/ic_add_black_24dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/rv_word" />
</android.support.constraint.ConstraintLayout>
Your code should be like this :
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent replyIntent = new Intent();
if(TextUtils.isEmpty(editText.getText())){
setResult(RESULT_CANCELED, replyIntent);
}else {
String word = editText.getText().toString();
replyIntent.putExtra(EXTRA_KEY,word);
setResult(RESULT_OK, replyIntent); //missing
}
finish();
}
});
Then After handle it in MainActivity.java
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
String requiredValue = data.getStringExtra(DisplayWord.EXTRA_KEY);
}
} catch (Exception ex) {
Toast.makeText(Activity.this, ex.toString(),
Toast.LENGTH_SHORT).show();
}
}

Android QR reader with Zxing

When I read Qr code, textView doesn't change.(Question 1) What is the problem ?
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{
private Button buton;
private TextView textView;
private ZXingScannerView myview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buton = (Button)findViewById(R.id.button);
textView = (TextView)findViewById(R.id.textView);
buton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myview = new ZXingScannerView(MainActivity.this);
myview.setResultHandler(MainActivity.this);
setContentView(myview);
myview.startCamera();
}
});
}
#Override
protected void onPause() {
super.onPause();
myview.stopCamera();
}
#Override
public void handleResult(Result result) {
setContentView(R.layout.activity_main);
textView.setText(result.getText().toString());
myview.stopCamera();
}
}
And when I finished reading Qr code,I want to start new activty with result.
(Question 2) How I do it ? Will this code work ?
#Override
public void handleResult(Result result) {
myview.stopCamera();
Intent intent = new Intent(getApplicationContext(),SecondActivty.class);
intent.putExtra("Result",result);
startActivity(intent);
}
If it doesn't, how should I fix it ?
Remove setContentView(R.layout.activity_main); from handleResult. You're replacing the view that you have references to with a new view.
As for communicating the Result over intent, as is, what you have will not work. Result does not inherit from Parcelable, and you can't just stick it in an intent and expect it to work. Better would be to get all relevant info from the Result and put it in the Intent as a String.

Use animation on button click?

I am trying to use this cool animation called SmallBang
on my Image button. Here is how my code looks for now:
import xyz.hanks.library.SmallBang;
public class MainActivity extends AppCompatActivity {
private SmallBang smallBang;
private ImageButton imageButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
smallBang = SmallBang.attach2Window(this);
smallBang.bang((ImageButton) findViewById(R.id.imageButton));
}
public void onSettingsButtonClick(View view) {
Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(intent);
finish();
}
}
I want to use that animation and then change to another activity. When i run this code I get this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTypeface(android.graphics.Typeface)' on a null object reference
If i remove the smallbang animation, the button and activity change works just fine. What could I do to get the animation working? I've added the library to the Gradle file.
Working Code
public class MainActivity extends Activity {
private SmallBang mSmallBang;
private ImageView ImageButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSmallBang = SmallBang.attach2Window(this);
ImageButton = (ImageView) findViewById(R.id.imageButton);
ImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
}
});
}
});
}
}
activity_main:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/image_1">
<ImageButton
android:id="#+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#mipmap/ic_launcher" />
</RelativeLayout>
Update your code modification:
public class MainActivity extends Activity {
private SmallBang mSmallBang;
private ImageView ImageButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSmallBang = SmallBang.attach2Window(this);
ImageButton = (ImageView) findViewById(R.id.imageButton);
}
public void onSettingsButtonClick(View view) {
mSmallBang.bang(view);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(intent);
finish();
}
});
}
}
Try in this way
import xyz.hanks.library.SmallBang;
public class MainActivity extends AppCompatActivity {
private SmallBang smallBang;
private ImageButton imageButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
smallBang = SmallBang.attach2Window(this);
imageButton = (ImageButton) findViewById(R.id.imageButton);
smallBang.bang(view,new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
onSettingsButtonClick(imageButton);
}
});
}
public void onSettingsButtonClick(View view) {
Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(intent);
finish();
}
}

Error : onCreate(Bundle) is already defined in this activity

Being new to Android Application development i was trying to learn connecting two activities using Intent. I tried a code from a book. It keeps throwing an error saying - 'onCreate(Bundle)' is already defined in MainActivity class as well as the NewActivity class. Would be of great help if i could get a solution.
MainActivity.class
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_new);
View view = getWindow().getDecorView().findViewById(android.R.id.content);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent startIntent = new Intent(MainActivity.this, NewActivity.class);
startActivity(startIntent);
}
});
}
NewActivity.class
public class NewActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_new);
}
}
If you want to connect those activities you have to do this :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View view = getWindow().getDecorView().findViewById(android.R.id.content);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent startIntent = new Intent(MainActivity.this, NewActivity.class);
startActivity(startIntent);
}
});
}
And then in yout second activity just delete the:
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_new);
}
And copy this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
}
And it will work.
Just change your NewActivity to:
public class NewActivity extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_new);
}
}
A class can contain only one onCreate() method.First learn about Activity Life Cycle http://developer.android.com/training/basics/activity-lifecycle/starting.html
Just remove the first onCreate event on your main activity and new activity. you don't need twice
public class MainActivity extends Activity {
#Override
/*protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}*/
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_new);
View view = getWindow().getDecorView().findViewById(android.R.id.content);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent startIntent = new Intent(MainActivity.this, NewActivity.class);
startActivity(startIntent);
}
});
}

Categories