I want to retrieve 4 string from Edittext and save it firebase realtime database
all the permission in firebase is set to true. After clicking the button no data is saved in the firebase.
I am not able to debug it
below is my COde
activity_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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">
<EditText
android:id="#+id/SOURCE"
android:layout_width="284dp"
android:layout_height="49dp"
android:layout_marginTop="32dp"
android:hint="SOURCE"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.464"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.136" />
<EditText
android:id="#+id/DESTINATION"
android:layout_width="276dp"
android:layout_height="51dp"
android:layout_marginTop="108dp"
android:hint="DESTINATION"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.466"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.268" />
<EditText
android:id="#+id/TIME"
android:layout_width="276dp"
android:layout_height="51dp"
android:layout_marginTop="196dp"
android:hint="TIME"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.389" />
<EditText
android:id="#+id/FARE"
android:layout_width="276dp"
android:layout_height="51dp"
android:layout_marginTop="268dp"
android:hint="FARE"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.525"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/SWITCH"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="312dp"
android:layout_marginBottom="296dp"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.532"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
my MainActivity file
package com.example.rupam;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class MainActivity extends AppCompatActivity {
EditText source;
EditText destination;
EditText time;
EditText fare;
Button save;
//////////////////////////////
///////Firebase ref//////////
DatabaseReference databaseReference;
////////////////////////////
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
////////Find view by id section//////////
source = (EditText) findViewById(R.id.SOURCE);
destination = (EditText) findViewById(R.id.DESTINATION);
time = (EditText) findViewById(R.id.TIME);
fare = (EditText) findViewById(R.id.FARE);
save = (Button) findViewById(R.id.SWITCH);
/////////////////////////////////////////
databaseReference = FirebaseDatabase.getInstance().getReference().child("USERS");
////////////On button click//////////////
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public void saveData() {
String src2 = source.getText().toString().trim();
String dst2 = destination.getText().toString().trim();
String tm2 = time.getText().toString().trim();
String fr2 = fare.getText().toString().trim();
SaveData saveData = new SaveData(src2, dst2, tm2, fr2);
databaseReference.setValue(saveData);
}
}
Savedata(class)
package com.example.rupam;
public class SaveData {
///Take 4 String////////
String src;
String dst;
String tm;
String fr;
//////////////////////
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
public String getDst() {
return dst;
}
public void setDst(String dst) {
this.dst = dst;
}
public String getTm() {
return tm;
}
public void setTm(String tm) {
this.tm = tm;
}
public String getFr() {
return fr;
}
public void setFr(String fr) {
this.fr = fr;
}
public SaveData(String src, String dst, String tm, String fr) {
this.src = src;
this.dst = dst;
this.tm = tm;
this.fr = fr;
}
}
my Mainfest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.rupam">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
please help me where I am wrong
there is no error in the build
You onClick() method is empty. You should call saveData() here.
So change from:
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
in to
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Call method which storing values
saveData();
}
});
You make a small mistake but don't worry .
When you set save.setOnClickListener method thats you don't put your saveData() method in this methods.So you should be put your saveData() method on save.setOnClickListener:
Your Mistake:
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
But Correct is:
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveData();
}
});
I have try your mentions code, According to your code you are not call
saveData(); method any where . so to resolve this issue call
saveData(); method on your save button click like this .
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Call method which storing values
saveData();
}
});
If you have Any query regarding this answered ,so add your query in comment
Related
I am new to android and java programming so i try to learn from doing few projects and i am stuck with this problem.
When i try to run the app only first activity is working and second activity is not working.
Where did i missed on this app?
I am confuse and two java projects are working but the only first activity works.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.android_examples.wallpaper_android_examplescom.MainActivity">
<ImageView
android:id="#+id/imageView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/img76"
android:layout_above="#+id/btn_right"
android:layout_alignParentTop="true"
android:layout_marginBottom="30dp"
android:scaleType="fitXY" />
<Button
android:id="#+id/btn_right"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/btn_left"
android:layout_alignBottom="#+id/btn_left"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginEnd="42dp"
android:layout_marginRight="42dp"
android:text="RIGHT" />
<Button
android:id="#+id/btn_left"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="43dp"
android:layout_marginLeft="43dp"
android:layout_marginBottom="100dp"
android:text="LEFT" />
<Button
android:id="#+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="0dp"
android:text="Click here to Set this image as Wallpaper in android programmatically" />
</RelativeLayout>
MainActivity.java
package com.android_examples.wallpaper_android_examplescom;
import android.app.WallpaperManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
Button button;
ImageView imageView;
WallpaperManager wallpaperManager ;
Bitmap bitmap1, bitmap2 ;
DisplayMetrics displayMetrics ;
int width, height;
BitmapDrawable bitmapDrawable ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
imageView = (ImageView)findViewById(R.id.imageView);
wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
bitmapDrawable = (BitmapDrawable) imageView.getDrawable();
bitmap1 = bitmapDrawable.getBitmap();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GetScreenWidthHeight();
SetBitmapSize();
wallpaperManager = WallpaperManager.getInstance(MainActivity.this);
try {
wallpaperManager.setBitmap(bitmap2);
wallpaperManager.suggestDesiredDimensions(width, height);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public void GetScreenWidthHeight(){
displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
width = displayMetrics.widthPixels;
height = displayMetrics.heightPixels;
}
public void SetBitmapSize(){
bitmap2 = Bitmap.createScaledBitmap(bitmap1, width, height, false);
}
}
login.java
package com.android_examples.wallpaper_android_examplescom;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class login extends AppCompatActivity {
private ImageView imageView;
private Button btn_right, btn_left;
private int current_image_index;
private int[] images = {R.drawable.img76, R.drawable.img2};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayImage();
SwitchButton();
}
void DisplayImage(){
imageView = (ImageView)findViewById(R.id.imageView);
}
void SwitchButton(){
btn_right = (Button)findViewById(R.id.btn_right);
btn_left = (Button)findViewById(R.id.btn_left);
btn_right.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
current_image_index++;
current_image_index = current_image_index % images.length;
imageView.setImageResource(images[current_image_index]);
}
});
btn_left.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
current_image_index--;
if(current_image_index < 0){
current_image_index = images.length - 1;
}
imageView.setImageResource(images[current_image_index]);
}
}
);
}
}
Androidmanifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android_examples.wallpaper_android_examplescom">
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-permission android:name="android.permission.SET_WALLPAPER_HINTS"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".login">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity">
</activity>
</application>
</manifest>
Where ever you want to call the next activity use this:-
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
Theres no code to navigate to MainActivity
Trigger below code
private void startMainActivity(){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
You have to start your second activity
startActivity(new Intent(getApplicationContext(), MainActivity.class));
make sure that you have added second activity in manifest file
void SwitchButton() {
btn_right = (Button) findViewById(R.id.btn_right);
btn_left = (Button) findViewById(R.id.btn_left);
btn_right.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
current_image_index++;
current_image_index = current_image_index % images.length;
imageView.setImageResource(images[current_image_index]);
startMainPage();
}
});
btn_left.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
current_image_index--;
if (current_image_index < 0) {
current_image_index = images.length - 1;
}
imageView.setImageResource(images[current_image_index]);
startMainPage();
}
}
);
}
private void startMainPage() {
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
}
write this code in your click listener:
btn_right.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
current_image_index++;
current_image_index = current_image_index % images.length;
imageView.setImageResource(images[current_image_index]);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
});
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I can not understand why my application does not open a new activity on a button click.I have a button in my layout file(id is showButton),I need to open another activity when I click on that button.But it does not work and my application will crash.therefore I added a try catch block and get the android monitor result as following.
activity_place_picker.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".PlacePickerActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView2"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Launch Places API Picker"
android:id="#+id/pickerButton"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add to Place Holder"
android:id="#+id/saveButton"
android:layout_below="#+id/pickerButton"
android:layout_centerHorizontal="true"
android:visibility="gone"
android:layout_marginTop="20dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Place Holder"
android:id="#+id/showButton"
android:layout_below="#+id/saveButton"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView3"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView3"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/poweredBy"
android:src="#drawable/powered_by_google_light"/>
This is Place picker class where I have included the onClick listner to the button to open a new activity.
PlacePickerActivity
public class PlacePickerActivity extends AppCompatActivity {
private static final int PLACE_PICKER_REQUEST = 1;
private TextView mName;
private TextView mAddress;
private TextView mAttributions;
private static final LatLngBounds BOUNDS_MOUNTAIN_VIEW = new LatLngBounds(
new LatLng(37.398160, -122.180831), new LatLng(37.430610, -121.972090));
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_picker);
mName = (TextView) findViewById(R.id.textView);
mAddress = (TextView) findViewById(R.id.textView2);
mAttributions = (TextView) findViewById(R.id.textView3);
Button showButton = (Button) findViewById(R.id.showButton);
Button pickerButton = (Button) findViewById(R.id.pickerButton);
pickerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
PlacePicker.IntentBuilder intentBuilder =
new PlacePicker.IntentBuilder();
intentBuilder.setLatLngBounds(BOUNDS_MOUNTAIN_VIEW);
Intent intent = intentBuilder.build(PlacePickerActivity.this);
startActivityForResult(intent, PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException
| GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
});
showButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
try {
Intent i = new Intent(ctx, PlacesActivity.class);
ctx.startActivity(i);
}catch (Exception e){
e.printStackTrace();
}
}
});
}
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST
&& resultCode == Activity.RESULT_OK) {
//Extracting place information from the API
final Place place = PlacePicker.getPlace(this, data);
final String place_Id = place.getId().toString();
final String place_Name = place.getName().toString();
final String place_Address = place.getAddress().toString();
final String place_PhoneNumber = place.getPhoneNumber().toString();
final String place_Website = place.getWebsiteUri().toString();
//Get rating as a float value and converting to string
final float rating = place.getRating();
final String place_Rating = String.valueOf(rating);
final String place_LatLng = place.getLatLng().toString();
final String function_Save = "save_Place";
final String function_Show = "show_Place";
String attributions = (String) place.getAttributions();
if (attributions == null) {
attributions = "";
}
mName.setText(place_Name);
mAddress.setText(place_Address);
mAttributions.setText(Html.fromHtml(attributions));
//Accessing the save button and show button in the view and making it visible after selecting a place
final View save = findViewById(R.id.saveButton);
save.setVisibility(View.VISIBLE);
//Passing the Extracted place details to the background worker class
save.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
BackgroundWorker backgroundWorker = new BackgroundWorker(PlacePickerActivity.this);
backgroundWorker.execute(function_Save,place_Id,place_Name,place_Address,place_PhoneNumber,place_Website,place_Rating,place_LatLng);
}
});
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
PlacesActivity.java
package com.truiton.placepicker;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class PlacesActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_places);
}
}
activity_places.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.truiton.placepicker.PlacesActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello world"
android:id="#+id/textView" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.truiton.placepicker">
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyBpIGvJfE8eKhoEFCMqV8NrFkWRjTAnNyQ" />
<activity
android:name=".PlacePickerActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".PlacesActivity"></activity>
</application>
</manifest>
Android Monitor result when the button clicks
Android Monitor result
Edited : This is the crash log
Crash log
can anyone help me with this?
Write the class name PlacePickerActivity in the intent, your method should be
showButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
try {
Intent i = new Intent(PlacePickerActivity.this , PlacesActivity.class);
ctx.startActivity(i);
}catch (Exception e){
e.printStackTrace();
}
}
});
I found the answer for the question.
This
link helped me to find the answer for the problem. In PlacePickerActivity I have just declare Context ctx;and it does not contain any primitive value. But I have use the it as an argument to open a new activity which will give me a NullPointerException.So instead of
showButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent i = new Intent(ctx, PlacesActivity.class);
ctx.startActivity(i);
}
});
I used
showButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent i = new Intent(PlacePickerActivity.this, PlacesActivity.class);
PlacePickerActivity.this.startActivity(i);
}
});
And this fixed my problem.Thank you for every one.
enter image description hereHey guys I'm at the end of my Java 1 class working on my project. We are making a memory/concentration game. My issue is that when I click the easy button for the next activity the app crashes. I have tried using fragments and activities and just can't seem to get it right. I have also tried using the layout I need on my main activity just to see if I could get it to display. Even then it just crashes on startup of the app. Any help would be appreciated.
Startup Screen activity.
package com.bignerdranch.android.memory;
import android.app.Activity;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
public class MemoryActivity extends Activity {
private Button mEasy;
private Button mMedium;
private Button mHard;
private CheckBox mSilence;
public MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memory);
player = new MediaPlayer();
player = MediaPlayer.create(this, R.raw.mkstartmusic);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setLooping(true);
player.start();
mEasy = (Button)findViewById(R.id.easy);
mEasy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent easy = new Intent(getApplicationContext(), EasyGame.class);
startActivity(easy);
}
});
mMedium = (Button)findViewById(R.id.medium);
mMedium.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
mHard = (Button)findViewById(R.id.hard);
mHard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
mSilence = (CheckBox)findViewById(R.id.silence);
mSilence.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mSilence.isChecked()) {
player.pause();
} else if(mSilence.isChecked() == false) {
player.start();
}
}
});
}
#Override
protected void onStop() {
super.onPause();
if (player != null){
player.stop();
if (isFinishing()){
player.stop();
player.release();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.layout.activity_memory, menu);
return true;
}
}
Second Activity (Easy option)
package com.bignerdranch.android.memory;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
public class EasyGame extends Activity {
private ImageButton buttOne;
private ImageButton buttTwo;
private ImageButton buttThree;
private ImageButton buttFour;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_easy);
buttOne = (ImageButton)findViewById(R.id.ImageButton01);
buttOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
buttTwo = (ImageButton)findViewById(R.id.ImageButton02);
buttTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
buttThree = (ImageButton)findViewById(R.id.ImageButton03);
buttThree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
buttFour = (ImageButton)findViewById(R.id.ImageButton04);
buttFour.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.layout.activity_easy, menu);
return true;
}
}
This is the layout for the Easy option
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/easyback"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#drawable/easyback"
android:clickable="false"
android:duplicateParentState="false"
android:longClickable="false"
android:scaleType="centerCrop" />
<ImageButton
android:id="#+id/ImageButton04"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_below="#+id/ImageButton01"
android:layout_toRightOf="#+id/ImageButton01"
android:layout_toEndOf="#+id/ImageButton01"
android:maxHeight="25dp"
android:maxWidth="25dp"
android:scaleType="fitXY"
android:src="#drawable/dragonemb" />
<ImageButton
android:id="#+id/ImageButton02"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_above="#+id/ImageButton04"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="22dp"
android:layout_marginEnd="22dp"
android:maxHeight="25dp"
android:maxWidth="25dp"
android:scaleType="fitXY"
android:src="#drawable/dragonemb" />
<ImageButton
android:id="#+id/ImageButton03"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignTop="#+id/ImageButton04"
android:layout_toLeftOf="#+id/ImageButton04"
android:layout_toStartOf="#+id/ImageButton04"
android:maxHeight="25dp"
android:maxWidth="25dp"
android:scaleType="fitXY"
android:src="#drawable/dragonemb" />
<ImageButton
android:id="#+id/ImageButton01"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentTop="true"
android:layout_marginTop="152dp"
android:layout_toLeftOf="#+id/ImageButton02"
android:maxHeight="25dp"
android:maxWidth="25dp"
android:scaleType="fitXY"
android:src="#drawable/dragonemb" />
</RelativeLayout>
OK It's not the full crash log you posted but at the top of it I saw roidManifest.xml?. And It's sure that you didn't defined your EasyGame Activity in your androidmanifest.xml so add this line inside application tag,
<manifest package="com....." . . . >
<application . . . >
<activity
android:name=".EasyGame"
android:label="easygame">
</activity>
. . .
</application>
</manifest>
In addition you are trying to cast your ImageButton into Button consider fixing that as well.
Add code below to AndroidManfest
<activity
android:name=".EasyGame"
/>
its simple just add this line to your AndroidManifest
<activity android:name="Activity"/>
The logcat did mentioned that you need to declare your activity within the Android Manifest which you didn't. please read the logcat carefully as it really helps to find what went wrong.
OK, so I had tried all of your guys suggestions which I had were part of the issue, the final issue turned out to that I needed to add my images to the drawable-xhdpi. Thanks for all your help.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
In a class i am taking we have been learning some android app development and such, and i have managed to run into a problem that I, for the life of me, cannot figure out...
Basic background...
I get a nullpointerexception when I rotate the device... This error is located at Line 100 of QuizActivity.....
this Line is : mCheatButton.setOnClickListener(new View.OnClickListener() {//....
I suspect this has something to do with storing or retrieving information from the bundle...
Anyways here is the rest of The code....
Here is my quiz activity... Sorry for all the code blocks, I dont really know a better way to give you this information, or if you even need all of it.... But right now I just can figure out what is going on... so i have printed the error (stack trace? i think that is the right term...).. here as well...
03-02 09:49:28.858 7921-7921/com.example.ryan.ryans_quiz E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ryan.ryans_quiz, PID: 7921
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ryan.ryans_quiz/com.example.ryan.ryans_quiz.QuizActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.ryan.ryans_quiz.QuizActivity.onCreate(QuizActivity.java:100)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
QuizActivity
package com.example.ryan.ryans_quiz;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class QuizActivity extends AppCompatActivity {
private static final String TAG = "QuizActivity";
private static final String KEY_INDEX = "index";
private static final int REQUEST_CODE_CHEAT = 0;
private Button mTrueButton;
private Button mFalseButton;
private ImageButton mNextButton;
private Button mCheatButton;
private TextView mQuestionTextView;
private Question[] mQuestionBank = new Question[] {
new Question(R.string.question_oceans, true),
new Question(R.string.question_mideast, false),
new Question(R.string.question_africa, false),
new Question(R.string.question_americas, true),
new Question(R.string.question_asia, true)
};
private int mCurrentIndex = 0;
private boolean mIsCheater;
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getTextResId();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue();
int messageResId = 0;
if (mIsCheater) {
messageResId = R.string.judgment_toast;
} else {
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT)
.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
if (savedInstanceState != null) {
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
}
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
mTrueButton = (Button) findViewById(R.id.trueButton);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button) findViewById(R.id.falseButton);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
}
});
mNextButton = (ImageButton) findViewById(R.id.nextButton);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
mIsCheater = false;
updateQuestion();
}
});
mCheatButton = (Button)findViewById(R.id.cheatButton);
mCheatButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue();
Intent i = CheatActivity.newIntent(QuizActivity.this, answerIsTrue);
startActivityForResult(i, REQUEST_CODE_CHEAT);
}
});
updateQuestion();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(KEY_INDEX, mCurrentIndex);
}
#Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
#Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
#Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop() called");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() called");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
if (requestCode == REQUEST_CODE_CHEAT) {
if (data == null) {
return;
}
mIsCheater = CheatActivity.wasAnswerShown(data);
}
}
}
My CheatActivity class
package com.example.ryan.ryans_quiz;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
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.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.widget.Button;
import android.widget.TextView;
public class
CheatActivity extends AppCompatActivity {
private static final String EXTRA_ANSWER_IS_TRUE =
"com.bignerdranch.android.geoquiz.answer_is_true";
private static final String EXTRA_ANSWER_SHOWN =
"com.bignerdranch.android.geoquiz.answer_shown";
private boolean mAnswerIsTrue;
private TextView mAnswerTextView;
private Button mShowAnswer;
public static Intent newIntent(Context packageContext, boolean answerIsTrue) {
Intent i = new Intent(packageContext, CheatActivity.class);
i.putExtra(EXTRA_ANSWER_IS_TRUE, answerIsTrue);
return i;
}
public static boolean wasAnswerShown(Intent result) {
return result.getBooleanExtra(EXTRA_ANSWER_SHOWN, false);
}
private void setAnswerShownResult(boolean isAnswerShown) {
Intent data = new Intent();
data.putExtra(EXTRA_ANSWER_SHOWN, isAnswerShown);
setResult(RESULT_OK, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
mAnswerTextView = (TextView)findViewById(R.id.answer_text_view);
mShowAnswer = (Button)findViewById(R.id.show_answer_button);
mShowAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.trueButton);
} else {
mAnswerTextView.setText(R.string.falseButton);
}
setAnswerShownResult(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
int cx = mShowAnswer.getWidth() / 2;
int cy = mShowAnswer.getHeight() / 2;
float radius = mShowAnswer.getWidth();
Animator anim = ViewAnimationUtils
.createCircularReveal(mShowAnswer, cx, cy, radius, 0);
anim.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
mAnswerTextView.setVisibility(View.VISIBLE);
mShowAnswer.setVisibility(View.INVISIBLE);
}
});
anim.start();
} else {
mAnswerTextView.setVisibility(View.VISIBLE);
mShowAnswer.setVisibility(View.INVISIBLE);
}
}
});
}
my Question Class
package com.example.ryan.ryans_quiz;
/**
* Created by Ryan on 1/20/2016.
*/
public class Question {
private int mTextResId;
private boolean mAnswerTrue;
public Question(int _textResId, boolean _answerTrue) {
mTextResId = _textResId;
mAnswerTrue = _answerTrue;
}
public int getTextResId() {
return mTextResId;
}
public void setTextResId(int textResId) {
mTextResId = textResId;
}
public boolean isAnswerTrue() {
return mAnswerTrue;
}
public void setAnswerTrue(boolean answerTrue) {
mAnswerTrue = answerTrue;
}
}
And finally my xml Files....
activity_cheat
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical"
tools:context="com.example.ryan.ryans_quiz.CheatActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="24dp"
android:text="#string/warning_text"/>
<TextView
android:id="#+id/answer_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="24dp"
tools:text="Answer"/>
<Button
android:id="#+id/show_answer_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/show_answer_button"/>
</LinearLayout>
LandLayout - activity_quiz
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/question_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="24dp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:orientation="horizontal">
<Button
android:id="#+id/trueButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/trueButton"/>
<Button
android:id="#+id/falseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/falseButton"/>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:text="#string/cheat_button"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:orientation="horizontal">
<ImageButton
android:id="#+id/previousButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#string/previousButton"
android:src="#drawable/arrow_left"/>
<ImageButton
android:id="#+id/nextButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal|center_vertical"
android:contentDescription="#string/nextButton"
android:src="#drawable/arrow_right"/>
</LinearLayout>
</LinearLayout>
</FrameLayout>
vertical layout- activity_quiz
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/question_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="24dp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/trueButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/trueButton"/>
<Button
android:id="#+id/falseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/falseButton"/>
</LinearLayout>
<Button
android:id="#+id/cheatButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/cheat_button"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageButton
android:id="#+id/previousButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/previousButton"
android:src="#drawable/arrow_left"/>
<ImageButton
android:id="#+id/nextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/nextButton"
android:src="#drawable/arrow_right"/>
</LinearLayout>
</LinearLayout>
Strings..
<resources>
<string name="app_name">RyanHull_Quiz</string>
<string name="action_settings">Settings</string>
<string name="trueButton">True</string>
<string name="falseButton">False</string>
<string name="nextButton">Next</string>
<string name="previousButton">Previous</string>
<string name="cheat_button">Cheat!</string>
<string name="correct_toast">Correct! :)</string>
<string name="incorrect_toast">Incorrect! :(</string>"
<string name="question_oceans">The Pacific Ocean is larger than the Atlantic Ocean.</string>
<string name="question_mideast">The Suez Canal connects the Red Sea and the Indian Ocean.</string>
<string name="question_africa">The source of the Nile River is in Egypt.</string>
<string name="question_americas">The Amazon River is the longest river in the Americas.</string>
<string name="question_asia">Lake Baikal is the world\'s oldest and deepest freshwater lake.</string>
<string name="warning_text">Are you sure you want to do this??</string>
<string name="show_answer_button">Show Answer</string>
<string name="judgment_toast">Cheating is Wrong 8/</string>
<string name="title_activity_cheat">Cheat</string>
and finally manifest....
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.example.ryan.ryans_quiz"
xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".QuizActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!--
ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information.
-->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<activity
android:name=".CheatActivity"
android:label="#string/title_activity_cheat"
android:theme="#style/AppTheme.NoActionBar">
</activity>
</application>
EDIT: its not a matter of me know what the exception is.. More of the matter of find where and why...
The lookup is failing for mCheatButton because you forgot to assign it an id in the landscape version of the activity_quiz.xml layout file.
When you then try to set a ClickListener on a null object that is where the NullPointerException is coming from.
when you rotate the device,the QuizActivity will destroy and then call onCreate,but your LandLayout file has no Button called 'cheatButton',so findViewById(R.id.cheatButton) will return null to mCheatButton, it can not call any method.
You haven't assigned any id to cheat button in LandLayout - activity_quiz
Change
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:text="#string/cheat_button"/>
to
<Button
android:id="#+id/cheatButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:text="#string/cheat_button"/>
In my Android app I have three classes, one is the MainActivity another one is called CustomerTransaction, which is just a Java class. There is also another activity called DataActivity which starts when the button Enter Data on the MainActivity screen is clicked. The activity DataActivity allows the user to enter a number in an EditText and then click the Send button to trigger a method in CustomerTransaction. I shall add the complete code below. But first let me explain my problem. In CustomerTransaction I have a method that provides values for two variables: totalAmount and transactionType (both are int). This values are needed in the MainActivity to be displayed on the main screen, when they are available. The MainActivity implements an interface called CustomListeners containing the header of the function that displays the two values (in TextViews). The values are communicated from CustomerTransaction to the method in MainActivity by notifying the listener when the values are available. The problem is that when I have the values, the set of listeners is empty. I would like to understand why this happens and then to correct the code.
Here's the code:
package com.example.customlistenertest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements CustomListeners {
TextView tv_amount;
TextView tv_transactionType;
Button btn_enterData;
CustomerTransaction control= new CustomerTransaction();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
control.registerListener(this);
tv_amount = (TextView) findViewById(R.id.textView_amount);
tv_transactionType = (TextView) findViewById(R.id.textView_transactionType);
btn_enterData = (Button) findViewById(R.id.button_enterData);
addListenerOnButtonEnterData();
}
public void addListenerOnButtonEnterData() {
btn_enterData.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent =
new Intent(MainActivity.this,com.example.customlistenertest.DataActivity.class);
startActivity(intent);
}
});
}
public void updateTotal(final int transactionType, final int totalAmount) {
runOnUiThread(new Runnable() {
public void run() {
tv_amount.setText(Integer.toString(totalAmount));
tv_transactionType.setText(Integer.toString(transactionType));
}});
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume(){
super.onResume();
control.registerListener(this);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
control.unregisterListener(this);
}
} // End MainActivity
Following is the code for the DataActivity class:
package com.example.customlistenertest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class DataActivity extends Activity {
TextView tv_enterNumber;
EditText et_number;
Button btn_send;
CustomerTransaction transaction;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.enter_data);
btn_send = (Button) findViewById(R.id.button_send);
et_number = (EditText) findViewById(R.id.editText_number);
}
public void send(View view) {
transaction = new CustomerTransaction();
transComplete();
}
private void transComplete() {
new Thread("TransComplete") {
public void run() {
String s_number = et_number.getText().toString();
int value = Integer.parseInt(s_number);
transaction.setState(5, value);
finish();
}
}.start();
}
} // end DataActivity
Following is the code for the CustomerTransaction class:
package com.example.customlistenertest;
import java.util.HashSet;
import java.util.Set;
public class CustomerTransaction {
public static final int DATA_ENTERED = 1;
public static final int TRANSACTION_COMPLETE = 5;
private int state;
private int totalAmount;
private int transactionType;
public Set<CustomListeners> listeners = new HashSet<CustomListeners>();
public synchronized void registerListener(CustomListeners listener) {
listeners.add(listener);
}
public synchronized void unregisterListener(CustomListeners listener) {
listeners.remove(listener);
}
public synchronized void notifyListeners() {
for(CustomListeners listener : listeners) {
if (totalAmount != 0)
listener.updateTotal(transactionType,totalAmount);
else
listener.updateTotal(transactionType,0);
}
}
public void performOperation() {
new Thread("MyThread") {
public void run() {
notifyListeners();
}
}.start();
}
public void setState(final int state, final int value) {
this.state = state;
this.totalAmount = value;
this.transactionType = 999;
if (state == DATA_ENTERED) {
}
if (state == TRANSACTION_COMPLETE) {
performOperation();
}
}
} // end CustomerTransactionjava
I shall add the two layout files as well. The first is activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView_amount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/textView_transactionType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<Button
android:id="#+id/button_enterData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Data" />
</LinearLayout>
The next one is the file enter_data.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView_enterNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter a number:" />
<EditText
android:id="#+id/editText_number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="send"
android:text="Send" />
</LinearLayout>
Finally, here's the Manifest file.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.customlistenertest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:theme="#style/AppTheme"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name">
<activity android:label="#string/app_name" android:name="MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.customlistenertest.DataActivity" >
</activity>
</application>
</manifest>
The "CustomerTransaction transaction" used in the MainActivity is not the same instance of the "CustomerTransaction transaction" of the one defined in the DataActivity. That explains why the DataActivity one is empty, because you did subscribe only with the one from the MainActivity. Two possible solutions for the problem:
Make the 'control' a singleton, so that you will be sure that there is only one instance of it at a time.
Make the 'listeners' variables and the 'register/unregister/notitifylisteners' methods static.
I prefer the option 1, but you can choose what you think it's best.
Good luck!