Record and play by clicking a buttom - javascript

I have a code that plays a sound, records audio (by clicking one button) and plays the file recorded (by clicking another button). I want to know how to modify it in order to record and play the sound when I click the first button so when I click the second button I can heard the recorded sound that I played first.
That means: I want to know how to start record and play my audio file in record folder, both of them, only by clicking a button.
This is my code just now:
public class MediaPlayerExample2Activity extends Activity {
private static final String LOG_TAG = "AudioRecordTest";
private static String mFileName = null;
private RecordButton mRecordButton = null;
private MediaRecorder mRecorder = null;
private PlayButton mPlayButton = null;
private MediaPlayer mPlayer = null;
private void onRecord(boolean start) {
if (start) {
startRecording(); }
else {
stopRecording(); } }
private void onPlay(boolean start) {
if (start) {
startPlaying(); }
else {
stopPlaying(); } }
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start(); }
catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
} } private void stopPlaying() {
mPlayer.release();
mPlayer = null; }
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
}
catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
} mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
class RecordButton extends Button {
boolean mStartRecording = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
setText("Stop recording");
}
else {
setText("Start recording");
}
mStartRecording = !mStartRecording; }
};
public RecordButton(Context ctx) {
super(ctx);
setText("Start recording");
setOnClickListener(clicker);
} }
class PlayButton extends Button {
boolean mStartPlaying = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
setText("Stop playing");
}
else {
setText("Start playing");
}
mStartPlaying = !mStartPlaying;
} };
public PlayButton(Context ctx) {
super(ctx);
setText("Start playing");
setOnClickListener(clicker);
} }
public MediaPlayerExample2Activity() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MediaPlayer mPlayer = MediaPlayer.create(this, R.raw.pru);
mPlayer.start();
LinearLayout ll = new LinearLayout(this);
mRecordButton = new RecordButton(this);
ll.addView(mRecordButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0)); setContentView(ll);
mPlayButton = new PlayButton(this);
ll.addView(mPlayButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0)); setContentView(ll); }
#Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
} }}
Thanks!! I hope you understand my question!!! ;)

Related

how to send current location to specific people in firebase database

i want to send current location to specific people in my firebase database when a button is clicked. These people change from device to device depending on which people the user has selected to get notification about the sender's location. I have a clue on what's required of me to do but i can't seem to figure it out.
This is the class i used to read the user's current location:
and in my menuActivity i want to call the latitude and the longitude when sendLoc button is clicked
public class MenuActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback {
ImageButton fakeCallBtn;
Button sendLoc;
ImageButton notif;
ImageButton flash;
private GoogleMap mMap;
LocationManager locationManager;
private FirebaseAuth mAuth;
private DatabaseReference mUserRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
mAuth = FirebaseAuth.getInstance();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("RescueX ");
sendLoc=(Button)findViewById(R.id.Locationbtn);
sendLoc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Location l = gt.getLocation();
if( l == null){
Toast.makeText(getApplicationContext(),"GPS unable to get
Value",Toast.LENGTH_SHORT).show();
}else {
double lat = l.getLatitude();
double lon = l.getLongitude();
Intent lociIntent = new Intent(MenuActivity.this,
ViewLocation.class);
lociIntent.putExtra("lat", lat);
lociIntent.putExtra("lon",lon);
startActivity(lociIntent);
Toast.makeText(getApplicationContext()," Emergency Alert has
been Successfully sent ",Toast.LENGTH_SHORT).show();
}
}
});
if (mAuth.getCurrentUser() != null) {
mUserRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//get latitude
double latitude = location.getLatitude();
//get longitude
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
String str = addressList.get(0).getCountryName() + ",";
str += addressList.get(0).getLocality();
mMap.addMarker(new MarkerOptions().position(latLng).title(str)); // this is the location i want to share with the specific people in my database
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.2f));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
}
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null){
sendToStart();
} else {
mUserRef.child("online").setValue("true");
}
}
#Override
protected void onStop() {
super.onStop();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser != null) {
mUserRef.child("online").setValue(ServerValue.TIMESTAMP);
}
}
private void sendToStart() {
Intent startIntent = new Intent(MenuActivity.this, Home.class);
startActivity(startIntent);
finish();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if(item.getItemId()== R.id.log_out){
FirebaseAuth.getInstance().signOut();
sendToStart();
}
//noinspection SimplifiableIfStatement
if (item.getItemId() == R.id.action_settings) {
Intent notifIntent= new Intent(MenuActivity.this, Settings.class);
startActivity(notifIntent);
}
if(item.getItemId() == R.id.all_users){
Intent usersIntent= new Intent(MenuActivity.this, UsersActivity.class);
startActivity(usersIntent);
}
return true;
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_profile_layout) {
Intent searchIntent = new Intent(MenuActivity.this, Profile.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_users_activity) {
Intent searchIntent = new Intent(MenuActivity.this, UsersActivity.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_history_layout) {
Intent searchIntent = new Intent(MenuActivity.this, History.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_help_layout) {
Intent searchIntent = new Intent(MenuActivity.this, Help.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_feedback_layout) {
Intent searchIntent = new Intent(MenuActivity.this, Feedback.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_signout_layout) {
Intent searchIntent = new Intent(MenuActivity.this, SignOut.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_friends_layout) {
Intent searchIntent = new Intent(MenuActivity.this, FriendsActivity.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
} else if (id == R.id.nav_share) {
Intent searchIntent = new Intent(MenuActivity.this, Share.class);
startActivity(searchIntent);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}}
this is the class that creates a group that should be sent the location when a button is clicked to send the location:
public class EmergencyList extends AppCompatActivity {
private Toolbar mToolbar;
private TextView mProfileName, mProfileStatus, mProfileFriendsCount;
private Button mProfileSendReqBtn, mDeclineBtn;
private DatabaseReference mUsersDatabase;
private ProgressDialog mProgressDialog;
private DatabaseReference mFriendReqDatabase;
private DatabaseReference mFriendDatabase;
private DatabaseReference mNotificationDatabase;
private ImageView mProfileImage;
private DatabaseReference mRootRef;
private FirebaseUser mCurrent_user;
private String mCurrent_state;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emergency_list);
mToolbar = (Toolbar)findViewById(R.id.user_Appbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Who to notify in emergency");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final String user_id = getIntent().getStringExtra("user_id");
mRootRef = FirebaseDatabase.getInstance().getReference();
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
mFriendReqDatabase = FirebaseDatabase.getInstance().getReference().child("Connection_req");
mFriendDatabase = FirebaseDatabase.getInstance().getReference().child("Emergency_Contacts");
mNotificationDatabase = FirebaseDatabase.getInstance().getReference().child("Emergency_Notification");
mCurrent_user = FirebaseAuth.getInstance().getCurrentUser();
mProfileImage = (ImageView) findViewById(R.id.profile_image);
mProfileName = (TextView) findViewById(R.id.profile_displayName);
mProfileStatus = (TextView) findViewById(R.id.profile_status);
mProfileFriendsCount = (TextView) findViewById(R.id.profile_totalFriends);
mProfileSendReqBtn = (Button) findViewById(R.id.profile_send_req_btn);
mDeclineBtn = (Button) findViewById(R.id.profile_decline_btn);
mCurrent_state = "not_emergency_contact";
mDeclineBtn.setVisibility(View.INVISIBLE);
mDeclineBtn.setEnabled(false);
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setTitle("Loading User Data");
mProgressDialog.setMessage("Please wait while we load the user data.");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
mUsersDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String display_name = dataSnapshot.child("name").getValue().toString();
String status = dataSnapshot.child("status").getValue().toString();
String image = dataSnapshot.child("profile_picture").getValue().toString();
mProfileName.setText(display_name);
mProfileStatus.setText(status);
Picasso.with(EmergencyList.this).load(image).placeholder(R.drawable.my_profile).into(mProfileImage);
if(mCurrent_user.getUid().equals(user_id)){
mDeclineBtn.setEnabled(false);
mDeclineBtn.setVisibility(View.INVISIBLE);
mProfileSendReqBtn.setEnabled(false);
mProfileSendReqBtn.setVisibility(View.INVISIBLE);
}
//--------------- FRIENDS LIST / REQUEST FEATURE -----
mFriendReqDatabase.child(mCurrent_user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(user_id)){
String req_type = dataSnapshot.child(user_id).child("emergency_type").getValue().toString();
if(req_type.equals("received")){
mCurrent_state = "emergency_received";
mProfileSendReqBtn.setText("Accept As Emergency ");
mDeclineBtn.setVisibility(View.VISIBLE);
mDeclineBtn.setEnabled(true);
} else if(req_type.equals("sent")) {
mCurrent_state = "emergency_sent";
mProfileSendReqBtn.setText("Cancel Emergency Request");
mDeclineBtn.setVisibility(View.INVISIBLE);
mDeclineBtn.setEnabled(false);
}
mProgressDialog.dismiss();
} else {
mFriendDatabase.child(mCurrent_user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(user_id)){
mCurrent_state = "emergency_contact";
mProfileSendReqBtn.setText("Remove "+mProfileName.getText() + " As Emergency Contact");
mDeclineBtn.setVisibility(View.INVISIBLE);
mDeclineBtn.setEnabled(false);
}
mProgressDialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
mProgressDialog.dismiss();
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mProfileSendReqBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mProfileSendReqBtn.setEnabled(false);
// --------------- NOT FRIENDS STATE ------------
if(mCurrent_state.equals("not_emergency_contact")){
DatabaseReference newNotificationref = mRootRef.child("Emergency_Notification").child(user_id).push();
String newNotificationId = newNotificationref.getKey();
HashMap<String, String> notificationData = new HashMap<>();
notificationData.put("from", mCurrent_user.getUid());
notificationData.put("type", "request");
Map requestMap = new HashMap();
requestMap.put("Connection_req/" + mCurrent_user.getUid() + "/" + user_id + "/emergency_type", "sent");
requestMap.put("Connection_req/" + user_id + "/" + mCurrent_user.getUid() + "/emergency_type", "received");
requestMap.put("Emergency_Notifications/" + user_id + "/" + newNotificationId, notificationData);
mRootRef.updateChildren(requestMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError != null){
Toast.makeText(EmergencyList.this, "There was some error in sending request", Toast.LENGTH_SHORT).show();
} else {
mCurrent_state = "emergency_sent";
mProfileSendReqBtn.setText("Cancel Emergency Contact");
}
mProfileSendReqBtn.setEnabled(true);
}
});
}
// - -------------- CANCEL REQUEST STATE ------------
if(mCurrent_state.equals("emergency_sent")){
mFriendReqDatabase.child(mCurrent_user.getUid()).child(user_id).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mFriendReqDatabase.child(user_id).child(mCurrent_user.getUid()).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mProfileSendReqBtn.setEnabled(true);
mCurrent_state = "not_emergency_contact";
mProfileSendReqBtn.setText("Add As Emergency Contact");
mDeclineBtn.setVisibility(View.INVISIBLE);
mDeclineBtn.setEnabled(false);
}
});
}
});
}
// ------------ REQ RECEIVED STATE ----------
if(mCurrent_state.equals("emergency_received")){
final String currentDate = DateFormat.getDateTimeInstance().format(new Date());
Map friendsMap = new HashMap();
friendsMap.put("Emergency_Contact/" + mCurrent_user.getUid() + "/" + user_id + "/date", currentDate);
friendsMap.put("Emergency_Contact/" + user_id + "/" + mCurrent_user.getUid() + "/date", currentDate);
friendsMap.put("Connection_req/" + mCurrent_user.getUid() + "/" + user_id, null);
friendsMap.put("Connection_req/" + user_id + "/" + mCurrent_user.getUid(), null);
mRootRef.updateChildren(friendsMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError == null){
mProfileSendReqBtn.setEnabled(true);
mCurrent_state = "emergency_contact";
mProfileSendReqBtn.setText("Remove " + mProfileName.getText() + " As Emergency Contact");
mDeclineBtn.setVisibility(View.INVISIBLE);
mDeclineBtn.setEnabled(false);
} else {
String error = databaseError.getMessage();
Toast.makeText(EmergencyList.this, error, Toast.LENGTH_SHORT).show();
}
}
});
}
// ------------ UNFRIENDS ---------
if(mCurrent_state.equals("emergency_contact")){
Map unfriendMap = new HashMap();
unfriendMap.put("Emergency_Contact/" + mCurrent_user.getUid() + "/" + user_id, null);
unfriendMap.put("Emergency_Contact/" + user_id + "/" + mCurrent_user.getUid(), null);
mRootRef.updateChildren(unfriendMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError == null){
mCurrent_state = "not_emergency_contact";
mProfileSendReqBtn.setText("Add As Emergency Contact");
mDeclineBtn.setVisibility(View.INVISIBLE);
mDeclineBtn.setEnabled(false);
} else {
String error = databaseError.getMessage();
Toast.makeText(EmergencyList.this, error, Toast.LENGTH_SHORT).show();
}
mProfileSendReqBtn.setEnabled(true);
}
});
}
}
});
}
}
this is the class where i call the people from my Emergency_Contacts in my database:
public class EmergencyFragment extends Fragment {
private RecyclerView mFriendsList;
private DatabaseReference mFriendsDatabase;
private DatabaseReference mUsersDatabase;
private FirebaseAuth mAuth;
private String mCurrent_user_id;
private View mMainView;
public EmergencyFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mMainView = inflater.inflate(R.layout.fragment_emergency, container, false);
mFriendsList = (RecyclerView) mMainView.findViewById(R.id.emergency_contacts);
mAuth = FirebaseAuth.getInstance();
mCurrent_user_id = mAuth.getCurrentUser().getUid();
mFriendsDatabase = FirebaseDatabase.getInstance().getReference().child("Emergency_Contact").child(mCurrent_user_id);
mFriendsDatabase.keepSynced(true);
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mUsersDatabase.keepSynced(true);
mFriendsList.setHasFixedSize(true);
mFriendsList.setLayoutManager(new LinearLayoutManager(getContext()));
// Inflate the layout for this fragment
return mMainView;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Emergency, EmergencyFragment.EmergencyViewHolder> emergencyRecyclerViewAdapter = new FirebaseRecyclerAdapter<Emergency, EmergencyFragment.EmergencyViewHolder>(
Emergency.class,
R.layout.users_emergency_layout,
EmergencyFragment.EmergencyViewHolder.class,
mFriendsDatabase
) {
#Override
protected void populateViewHolder(final EmergencyFragment.EmergencyViewHolder emergencyViewHolder, Emergency emergency, int i) {
emergencyViewHolder.setDate(emergency.getDate());
final String user_id = getRef(i).getKey();
mUsersDatabase.child(user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String Username = dataSnapshot.child("name").getValue().toString();
String userThumb = dataSnapshot.child("thumb_image").getValue().toString();
emergencyViewHolder.setName(Username);
emergencyViewHolder.setUserImage(userThumb, getContext());
emergencyViewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence options[] = new CharSequence[]{" Open Details", "view history"};
final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Select Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Click Event for each item.
if(i == 0){
Intent emergencyIntent = new Intent(getContext(), EmergencyList.class);
emergencyIntent.putExtra("user_id", user_id);
startActivity(emergencyIntent);
}
if(i == 1){
Intent historyIntent = new Intent(getContext(), History.class);
historyIntent.putExtra("user_id", user_id);
historyIntent.putExtra("Username", Username);
startActivity(historyIntent);
}
}
});
builder.show();
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
mFriendsList.setAdapter(emergencyRecyclerViewAdapter);
}
public static class EmergencyViewHolder extends RecyclerView.ViewHolder {
View mView;
public EmergencyViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDate(String date){
TextView userStatusView = (TextView) mView.findViewById(R.id.contacts_status);
userStatusView.setText(date);
}
public void setName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.contacts_name);
userNameView.setText(name);
}
public void setUserImage(String thumb_image, Context ctx){
CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.image_display);
Picasso.with(ctx).load(thumb_image).placeholder(R.drawable.my_profile).into(userImageView);
}
}
}
}
i want the location to be stored or opened on the history class now i am not sure how to get the location from the menuactivity class -> Emergency_Contacts then to -> history where it's going to be displayed.

when change mSwitch1 or mSwitch2 or mSwitch3, change All Switchs?

Why if change mSwitch1 or mSwitch2 or mSwitch3, change All Switchs? If you leave one Switch in Activity, everything works.
AndroidStudio / javascript .
Why if change mSwitch1 or mSwitch2 or mSwitch3, change All Switchs? If you leave one Switch in Activity, everything works.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
...
String sw1 = pref.getString(APP_PREFERENCES_SWITCH1, "");
String sw2 = pref.getString(APP_PREFERENCES_SWITCH2, "");
String sw3 = pref.getString(APP_PREFERENCES_SWITCH3, "");
if (sw1.length() == 2) {
mSwitch1.setChecked(true);
}
if (sw1.length() == 1) {
mSwitch1.setChecked(false);
}
if (sw2.length() == 2) {
mSwitch2.setChecked(true);
}
if (sw2.length() == 1) {
mSwitch2.setChecked(false);
}
if (sw3.length() == 2) {
mSwitch3.setChecked(true);
}
if (sw3.length() == 1) {
mSwitch3.setChecked(false);
}
...
mSwitch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences pref3 = getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE);
if (mSwitch1.isChecked()) {
String Swe1 = "12";
Editor editSwe1 = pref3.edit();
editSwe1.putString(APP_PREFERENCES_SWITCH1, Swe1);
editSwe1.apply();
Toast.makeText(getApplicationContext(), "SET ON1", Toast.LENGTH_SHORT).show();
} else {
String Swe2 = "1";
Editor editSwe2 = pref3.edit();
editSwe2.putString(APP_PREFERENCES_SWITCH1, Swe2);
editSwe2.apply();
Toast.makeText(getApplicationContext(), "SET OFF1", Toast.LENGTH_SHORT).show();
}
}
});
mSwitch2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences pref4 = getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE);
if (mSwitch2.isChecked()) {
String Swe3 = "12";
Editor editSwe3 = pref4.edit();
editSwe3.putString(APP_PREFERENCES_SWITCH2, Swe3);
editSwe3.apply();
Toast.makeText(getApplicationContext(), "SET ON2", Toast.LENGTH_SHORT).show();
} else {
String Swe4 = "1";
Editor editSwe4 = pref4.edit();
editSwe4.putString(APP_PREFERENCES_SWITCH2, Swe4);
editSwe4.apply();
Toast.makeText(getApplicationContext(), "SET OFF2", Toast.LENGTH_SHORT).show();
}
}
});
...
}

imageview visibility by onclick button

I'm currently working on an app where I want to add a button to toggle visibility on a certain ImageView. Beforehand, there are 3 GraphViews on my UI, and when visibility is toggled, ImageView will overlap the two graphs below. However, when I run the app, the 'app has stopped'
The btndiag button causes the error
public class MainActivity extends Activity {
private static final String TAG = "TUP-MainActivity";
private int mMaxChars = 50000;//Default
private UUID mDeviceUUID;
private BluetoothSocket mBTSocket;
private ReadInput mReadThread = null;
private ConnectedThread mConnectedThread;
private boolean mIsUserInitiatedDisconnect = false;
// All controls here
private TextView mTxtReceive;
private Button mBtnDisconnect;
private Button mBtnStart;
private GraphView1 graphView1;
private GraphView2 graphView2;
private GraphView3 graphView3;
private StringBuilder recDataString = new StringBuilder();
private boolean mIsBluetoothConnected = false;
private BluetoothDevice mDevice;
private ProgressDialog progressDialog;
private Button btnDiag;
private ImageView imgDiag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
graphView1 = (GraphView1) findViewById(R.id.graph_view1);
graphView2 = (GraphView2) findViewById(R.id.graph_view2);
graphView3 = (GraphView3) findViewById(R.id.graph_view3);
ActivityHelper.initialize(this);
Intent intent = getIntent();
Bundle b = intent.getExtras();
mDevice = b.getParcelable(Homescreen.DEVICE_EXTRA);
mDeviceUUID = UUID.fromString(b.getString(Homescreen.DEVICE_UUID));
mMaxChars = b.getInt(Homescreen.BUFFER_SIZE);
Log.d(TAG, "Ready");
mBtnDisconnect = (Button) findViewById(R.id.btnDisconnect);
mBtnStart = (Button) findViewById(R.id.btnStart);
btnDiag = (Button)findViewById(R.id.btDiag);
mTxtReceive = (TextView)findViewById(R.id.textView);
mTxtReceive.setMovementMethod(new ScrollingMovementMethod());
mBtnDisconnect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mIsUserInitiatedDisconnect = true;
new DisConnectBT().execute();
mConnectedThread = new ConnectedThread(mBTSocket);
mConnectedThread.start();
mConnectedThread.write("B");
}
});
mBtnStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mConnectedThread = new ConnectedThread(mBTSocket);
mConnectedThread.start();
mConnectedThread.write("A");
}
});
btnDiag.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
btnDiag.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
imgDiag.setVisibility(View.VISIBLE);
}
});
}
});
}
private class ReadInput implements Runnable {
private boolean bStop = false;
private Thread t;
public ReadInput() {
t = new Thread(this, "Input Thread");
t.start();
}
public boolean isRunning() {
return t.isAlive();
}
#Override
public void run() {
InputStream inputStream;
try {
inputStream = mBTSocket.getInputStream();
while (!bStop) {
byte[] buffer = new byte[512];
if (inputStream.available() > 0) {
inputStream.read(buffer);
int i = 0;
/*
* This is needed because new String(buffer) is taking the entire buffer i.e. 256 chars on Android 2.3.4 http://stackoverflow.com/a/8843462/1287554
*/
for (i = 0; i < buffer.length && buffer[i] != 0; i++) {
}
final String strInput = new String(buffer, 0, i);
mTxtReceive.post(new Runnable() {
#Override
public void run() {
String[] items = strInput.split("\\*");
for (String item : items )
{
if(item.length() == 12){
try{
//get sensor value from string between indices 1-5;
final int value = Integer.parseInt(item.substring(1, 3));
ImageView imageView = (ImageView) findViewById(R.id.edg_image);
if ( value <= 77) {
imageView.setImageResource(R.drawable.left);
}
else if ( value <= 80 && value >=78) {
imageView.setImageResource(R.drawable.center);
}
else if ( value >= 81 ){
imageView.setImageResource(R.drawable.right);
}
System.out.println("acc = " + value);
}catch(NumberFormatException ex){ // handle your exception
System.out.println("Not an integer");
}
try{
//get sensor value from string between indices 1-5;
final int value = Integer.parseInt(item.substring(3, 6));
System.out.println("ecg = "+ value);
graphView1.plotProcedure1(value);
}catch(NumberFormatException ex){ // handle your exception
System.out.println("Not an integer");
}
try{
final int value = Integer.parseInt(item.substring(6, 9));
System.out.println("eda = "+ value);
graphView2.plotProcedure2(value);
}catch(NumberFormatException ex){ // handle your exception
System.out.println("Not an integer");
}
try{
final int value = Integer.parseInt(item.substring(9, 12));
System.out.println("emg = "+ value);
graphView3.plotProcedure3(value);
}catch(NumberFormatException ex){ // handle your exception
System.out.println("Not an integer");
}
}
}
}
});
}
Thread.sleep(500);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stop() {
bStop = true;
}
}
private class DisConnectBT extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
if (mReadThread != null) {
mReadThread.stop();
while (mReadThread.isRunning())
; // Wait until it stops
mReadThread = null;
}
try {
mBTSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mIsBluetoothConnected = false;
if (mIsUserInitiatedDisconnect) {
finish();
}
}
}
private void msg(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
if (mBTSocket != null && mIsBluetoothConnected) {
new DisConnectBT().execute();
}
Log.d(TAG, "Paused");
super.onPause();
}
#Override
protected void onResume() {
if (mBTSocket == null || !mIsBluetoothConnected) {
new ConnectBT().execute();
}
Log.d(TAG, "Resumed");
super.onResume();
};
#Override
protected void onStop() {
Log.d(TAG, "Stopped");
super.onStop();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> {
private boolean mConnectSuccessful = true;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this, "Hold on", "Connecting");// http://stackoverflow.com/a/11130220/1287554
}
#Override
protected Void doInBackground(Void... devices) {
try {
if (mBTSocket == null || !mIsBluetoothConnected) {
mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
mBTSocket.connect();
}
} catch (IOException e) {
// Unable to connect to device
e.printStackTrace();
mConnectSuccessful = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!mConnectSuccessful) {
Toast.makeText(getApplicationContext(), "Could not connect to device. Is it a Serial device? Also check if the UUID is correct in the settings", Toast.LENGTH_LONG).show();
finish();
} else {
msg("Connected to device");
mIsBluetoothConnected = true;
mReadThread = new ReadInput(); // Kick off input reader
}
progressDialog.dismiss();
}
}
//create new class for connect thread
private class ConnectedThread extends Thread {
private final OutputStream mmOutStream;
//creation of the connect thread
public ConnectedThread(BluetoothSocket mBTSocket) {
OutputStream tmpOut = null;
try {
//Create I/O streams for connection
tmpOut = mBTSocket.getOutputStream();
} catch (IOException e) { }
mmOutStream = tmpOut;
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
finish();
}
}
}
}
logcat error
01-04 07:04:08.467 22700-22700/com.tup.tup E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.tup.tup, PID: 22700
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tup.tup/com.tup.tup.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2224)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2273)
at android.app.ActivityThread.access$800(ActivityThread.java:138)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1236)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5045)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:610)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.tup.tup.MainActivity.onCreate(MainActivity.java:82)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2188)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2273) 
at android.app.ActivityThread.access$800(ActivityThread.java:138) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1236) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:149) 
at android.app.ActivityThread.main(ActivityThread.java:5045) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515)

how to manage webview accordingly?

Actually, I have converted WordPress site into an android app. In WordPress site there is some add available on the site which is created in javascript, and when data is fetched into the android app as a webview, there is some space is shown in place of that ads. I want to remove it or want to add AdMob ads there. How could it be possible? Please help me regarding this.
Thanks in advance.
My Code is
public class PostViewActivity extends AppCompatActivity {
private static final String TAG = PostViewActivity.class.getSimpleName();
public static final String TAG_SEL_POST_ID = "post_id";
public static final String TAG_SEL_POST_TITLE = "post_title";
public static final String TAG_SEL_POST_IMAGE = "post_image";
private String commentsNumber;
private String selectedPostID, selectedPostTitle;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private ImageButton fab;
private TextView post_name;
private TextView post_content;
private TextView post_author;
private ImageView postImageView;
private String post_image, objURL, objTitle;
private Integer commentsCount;
private TextView timestamp;
private NetworkImageView profilePic;
private ShareActionProvider mShareActionProvider;
private WebView post_contentHTML;
private Boolean user_can_comment = true;
private Spanned spannedContent;
private ProgressBar pbLoader;
private LinearLayout llayout;
private Integer OC = 0;
//----------Exit and Banner Ad----------------------------------
private InterstitialAd interstitial;
private AdView mAdView;
private Toolbar toolbar;
public static void navigate(AppCompatActivity activity, View transitionImage, Post post) {
Intent intent = new Intent(activity, PostViewActivity.class);
intent.putExtra(TAG_SEL_POST_IMAGE, post.getImge());
intent.putExtra(TAG_SEL_POST_TITLE, post.getName());
ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(activity, transitionImage, TAG_SEL_POST_IMAGE);
ActivityCompat.startActivity(activity, intent, options.toBundle());
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putString(TAG_SEL_POST_ID, selectedPostID);
savedInstanceState.putString(TAG_SEL_POST_TITLE, selectedPostTitle);
Log.d(TAG, savedInstanceState.toString());
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.d(TAG, "Restored: " + savedInstanceState.toString());
selectedPostID = (String) savedInstanceState.getString(TAG_SEL_POST_ID);
selectedPostTitle = (String) savedInstanceState.getString(TAG_SEL_POST_TITLE);
super.onRestoreInstanceState(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
//Get a Tracker (should auto-report)
if (Const.Analytics_ACTIVE) {
AnalyticsUtil.sendScreenName(this, TAG);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initActivityTransitions();
setContentView(R.layout.activity_post_view);
//Forcing RTL Layout, If Supports and Enabled from Const file
Utils.forceRTLIfSupported(this);
ActivityCompat.postponeEnterTransition(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
//Get and Set the Post Title
String itemTitle = getIntent().getStringExtra(TAG_SEL_POST_TITLE);
setTitle(Html.fromHtml(itemTitle));
if (savedInstanceState == null) {
if (getIntent().getExtras() == null) {
selectedPostID = null;
selectedPostTitle = "Unknown Error";
} else {
selectedPostID = getIntent().getExtras().getString(TAG_SEL_POST_ID);
selectedPostTitle = getIntent().getExtras().getString(TAG_SEL_POST_TITLE);
}
} else {
Log.d(TAG, "Resume: " + savedInstanceState.toString());
selectedPostID = (String) savedInstanceState.getString(TAG_SEL_POST_ID);
selectedPostTitle = (String) savedInstanceState.getString(TAG_SEL_POST_TITLE);
/*selectedPostID = (String) savedInstanceState.getSerializable(TAG_SEL_POST_ID);
selectedPostTitle = (String) savedInstanceState.getSerializable(TAG_SEL_POST_TITLE);*/
}
//Setting up Fields Display
fab = (ImageButton) findViewById(R.id.fab);
post_name = (TextView) findViewById(R.id.title);
timestamp = (TextView) findViewById(R.id.timestamp);
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/GenR102.ttf");
post_name.setTypeface(font);
float density = getResources().getDisplayMetrics().density;
int leftPadding = (int) (20 * density);
Configuration config = getResources().getConfiguration();
if (ViewCompat.getLayoutDirection(post_name) == ViewCompat.LAYOUT_DIRECTION_RTL) {
//post_name.setPadding(leftPadding,R.dimen.spacing_large,0,0);
post_name.setPadding(leftPadding, 0, 0, 0);
} else {
post_name.setPadding(0, 0, leftPadding, 0);
}
post_content = (TextView) findViewById(R.id.description);
post_contentHTML = (WebView) findViewById(R.id.descriptionHTML);
if (!Const.ShowPostAsWebView) {
post_content.setMovementMethod(LinkMovementMethod.getInstance());
Typeface font_postcontent = Typeface.createFromAsset(getAssets(), "fonts/OSRegular.ttf");
post_content.setTypeface(font_postcontent);
} else {
post_contentHTML.setVisibility(View.VISIBLE);
WebSettings webSettings = post_contentHTML.getSettings();
post_contentHTML.getSettings().setJavaScriptEnabled(true);
post_contentHTML.getSettings().getJavaScriptEnabled();
post_contentHTML.addJavascriptInterface(this, "asiannews");
post_contentHTML.getSettings().setAllowContentAccess(true);
post_contentHTML.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
post_contentHTML.getSettings().setLoadsImagesAutomatically(true);
post_contentHTML.getSettings().setDefaultTextEncodingName("utf-8");
post_contentHTML.getSettings().setUseWideViewPort(true);
post_contentHTML.getSettings().setLoadWithOverviewMode(true);
post_contentHTML.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
post_contentHTML.setWebChromeClient(new WebChromeClient());
post_contentHTML.addJavascriptInterface(this, "AsianNews");
post_contentHTML.loadUrl("javascript:Android.getIds(Ids);");
post_contentHTML.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
//post_contentHTML.loadDataWithBaseURL("http://www.asiannews.co.in/bp4a-api/v1/post/_STORY_ID_/", myString, "text/html", "UTF-8", null);
}
post_author = (TextView) findViewById(R.id.post_author);
postImageView = (ImageView) findViewById(R.id.image);
profilePic = (NetworkImageView) findViewById(R.id.profilePic);
//Setting up Post Image and Toolbar Activity
//final ImageView image = (ImageView) findViewById(R.id.image);
/*ViewCompat.setTransitionName(postImageView, TAG_SEL_POST_IMAGE);
Bitmap bitmap = ((BitmapDrawable) postImageView.getDrawable()).getBitmap();
Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
public void onGenerated(Palette palette) {
applyPalette(palette, postImageView);
}
});*/
//Setting Up Post Admob Banner
////Standard Banner
mAdView = (AdView) findViewById(R.id.adView);
if (Const.ADMOBService_ACTIVE) {
//----------Exit Ad----------------------------------
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId(getString(R.string.unit_id_interstitial));
AdRequest adRequestInterstitial = new AdRequest.Builder().addTestDevice(Const.ADMOB_DEVICE_ID).build();
interstitial.loadAd(adRequestInterstitial);
//----------Exit Ad----------------------------------
AdRequest adRequest = new AdRequest.Builder().addTestDevice(Const.ADMOB_DEVICE_ID).build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
mAdView.setVisibility(View.VISIBLE);
}
});
} else {
mAdView.setVisibility(View.GONE);
}
getPost();
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void initActivityTransitions() {
if (Utils.isLollipop()) {
Slide transition = new Slide();
transition.excludeTarget(android.R.id.statusBarBackground, true);
getWindow().setEnterTransition(transition);
getWindow().setReturnTransition(transition);
}
}
private void applyPalette(Palette palette, ImageView image) {
int primaryDark = getResources().getColor(R.color.primary_dark);
int primary = getResources().getColor(R.color.primary);
toolbar.setBackgroundColor(primary);
Utils.setStatusBarcolor(getWindow(), primaryDark);
initScrollFade(image);
ActivityCompat.startPostponedEnterTransition(this);
}
private void initScrollFade(final ImageView image) {
final View scrollView = findViewById(R.id.scroll);
setComponentsStatus(scrollView, image);
scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
#Override
public void onScrollChanged() {
setComponentsStatus(scrollView, image);
}
});
}
private void setComponentsStatus(View scrollView, ImageView image) {
int scrollY = scrollView.getScrollY();
image.setTranslationY(-scrollY / 2);
ColorDrawable background = (ColorDrawable) toolbar.getBackground();
int padding = scrollView.getPaddingTop();
double alpha = (1 - (((double) padding - (double) scrollY) / (double) padding)) * 255.0;
alpha = alpha < 0 ? 0 : alpha;
alpha = alpha > 255 ? 255 : alpha;
background.setAlpha((int) alpha);
float scrollRatio = (float) (alpha / 255f);
int titleColor = getAlphaColor(Color.WHITE, scrollRatio);
toolbar.setTitleTextColor(titleColor);
toolbar.setSubtitleTextColor(titleColor);
}
private int getAlphaColor(int color, float scrollRatio) {
return Color.argb((int) (scrollRatio * 255f), Color.red(color), Color.green(color), Color.blue(color));
}
/**
* It seems that the ActionBar view is reused between activities. Changes need to be reverted,
* or the ActionBar will be transparent when we go back to Main Activity
*/
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void restablishActionBar() {
if (Utils.isLollipop()) {
getWindow().getReturnTransition().addListener(new TransitionAdapter() {
#Override
public void onTransitionEnd(Transition transition) {
toolbar.setTitleTextColor(Color.WHITE);
toolbar.setSubtitleTextColor(Color.WHITE);
toolbar.getBackground().setAlpha(255);
}
});
}
}
#Override
public void onBackPressed() {
restablishActionBar();
if (Const.ADMOBService_ACTIVE) {
displayInterstitial();
}
super.onBackPressed();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
restablishActionBar();
}
return super.onOptionsItemSelected(item);
}
private void getPost() {
//Requesting The Story
String url = null;
url = Const.URL_STORY_PAGE.replace("_STORY_ID_", selectedPostID.replace("P", ""));
//Log.i(TAG, "Taging: " + url);
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log.i(TAG, "Taging: " + response.toString());
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
try {
if (response.has("error")) {
String error = response.getString("error");
Toast.makeText(getApplicationContext(), error, Toast.LENGTH_LONG).show();
} else {
parseJsonFeed(response);
}
} catch (JSONException es) {
es.printStackTrace();
Toast.makeText(getApplicationContext(), es.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
/** Passing some request headers **/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("ApiKey", Const.AuthenticationKey);
return headers;
}
};
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
private void parseJsonFeed(JSONObject feedObj) {
try {
objTitle = feedObj.getString("name");
post_name.setText(Html.fromHtml(objTitle));
commentsCount = feedObj.getInt("comments");
if (feedObj.getString("can_comment") == "no") {
user_can_comment = false;
}
if (!Const.ShowPostAsWebView) {
post_contentHTML.setVisibility(View.GONE);
URLImageParser p = new URLImageParser(this, post_content);
spannedContent = Html.fromHtml(feedObj.getString("story_content"), p, null);
post_content.setText(trimTrailingWhitespace(spannedContent));
} else {
post_content.setVisibility(View.GONE);
post_contentHTML.setVisibility(View.VISIBLE);
String post_con = "<!DOCTYPE html>" +
"<html lang=\"en\">" +
" <head>" +
" <meta charset=\"utf-8\">" +
" </head>" +
" <body>" +
" #content# " +
" </body>" +
"</html>";
try {
InputStream in_s = getResources().openRawResource(R.raw.post_format);
byte[] b = new byte[in_s.available()];
in_s.read(b);
post_con = new String(b);
} catch (Exception e) {
e.printStackTrace();
}
post_con = post_con.replace("#title#", feedObj.getString("name"));
post_con = post_con.replace("#content#", feedObj.getString("story_content"));
//post_contentHTML.loadData(post_con, "text/html; charset=utf-8", "utf-8");
post_contentHTML.loadDataWithBaseURL(null,
post_con,
"text/html",
"UTF-8",
null);
}
if (feedObj.getString("story_content").length() <= 0) {
post_content.setVisibility(View.GONE);
post_contentHTML.setVisibility(View.GONE);
}
post_author.setText(feedObj.getString("author"));
getSupportActionBar().setSubtitle("By " + feedObj.getString("author"));
post_image = feedObj.getString("image");
objURL = feedObj.getString("url");
if (Const.Analytics_ACTIVE) {
AnalyticsUtil.sendEvent(this, "Post View", objTitle, objURL);
}
//Setting Up a Share Intent
fab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, objTitle + " - " + objURL);
startActivityForResult(Intent.createChooser(shareIntent, "Share via"), 300);
}
});
//setShareIntent(shareIntent);
//Comment Button Click
Button viewComments = (Button) findViewById(R.id.btnViewComments);
commentsNumber = Utils.formatNumber(commentsCount);
viewComments.setText(String.format(getString(R.string.comments_button), commentsNumber));
viewComments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setClass(PostViewActivity.this, PostComments.class);
i.putExtra("post_id", selectedPostID.replace("P", ""));
i.putExtra("post_title", getIntent().getStringExtra(TAG_SEL_POST_TITLE));
i.putExtra("commentsCount", commentsCount);
i.putExtra("user_can_comment", user_can_comment);
startActivityForResult(i, 1000);
}
});
//Button Click
Button viewWeb = (Button) findViewById(R.id.btnViewWeb);
if (Const.ShowPostOnExternalBrowser) {
viewWeb.setVisibility(View.VISIBLE);
viewWeb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToUrl(objURL);
}
});
}
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(feedObj.getString("timeStamp")),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
profilePic.setImageUrl(feedObj.getString("profilePic"), imageLoader);
loadConfig();
//pbLoader.setVisibility(View.GONE);
//llayout.setVisibility(View.VISIBLE);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void goToUrl(String url) {
Uri uriUrl = Uri.parse(url);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}
private void loadConfig() {
if (post_image != null) {
ViewCompat.setTransitionName(postImageView, TAG_SEL_POST_IMAGE);
Picasso.with(this).load(post_image).into(postImageView, new Callback() {
#Override
public void onSuccess() {
Bitmap bitmap = ((BitmapDrawable) postImageView.getDrawable()).getBitmap();
new Palette.Builder(bitmap).generate(new Palette.PaletteAsyncListener() {
public void onGenerated(Palette palette) {
applyPalette(palette, postImageView);
}
});
/*Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
public void onGenerated(Palette palette) {
applyPalette(palette, postImageView);
}
});*/
}
#Override
public void onError() {
}
});
} else {
postImageView.setVisibility(View.GONE);
}
}
#JavascriptInterface
public void resize(final float height) {
PostViewActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Trigger: " + height + " // " + (int) (height * getResources().getDisplayMetrics().density), Toast.LENGTH_LONG).show();
//post_contentHTML.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, (int) (height * getResources().getDisplayMetrics().density)));
}
});
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
post_contentHTML.loadUrl("javascript:asiannews.resize(document.body.getBoundingClientRect().height)");
}
public static CharSequence trimTrailingWhitespace(CharSequence source) {
if (source == null)
return "";
int i = source.length();
// loop back to the first non-whitespace character
while (--i >= 0 && Character.isWhitespace(source.charAt(i))) {
}
return source.subSequence(0, i + 1);
}
// Invoke displayInterstitial() when you are ready to display an interstitial.
public void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
public class URLImageParser implements Html.ImageGetter {
#SuppressWarnings("deprecation")
class URLDrawable extends BitmapDrawable {
// the drawable that you need to set, you could set the initial drawing
// with the loading image if you need to
protected Drawable drawable;
#Override
public void draw(Canvas canvas) {
// override the draw to facilitate refresh function later
if (drawable != null) {
drawable.draw(canvas);
}
}
}
class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
URLDrawable urlDrawable;
public ImageGetterAsyncTask(URLDrawable d) {
this.urlDrawable = d;
}
#Override
protected Drawable doInBackground(String... params) {
String source = params[0];
Uri uri = Uri.parse(source);
Bitmap bitmap = null;
try {
Picasso pic = new Picasso.Builder(mContext).build();
bitmap = pic.load(uri).get();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
return new BitmapDrawable(mContext.getResources(), bitmap);
}
#Override
protected void onPostExecute(Drawable result) {
// set the correct bound according to the result from HTTP call
urlDrawable.setBounds(0, 0, 0 + result.getIntrinsicWidth(), 0
+ result.getIntrinsicHeight());
// change the reference of the current drawable to the result
// from the HTTP call
urlDrawable.drawable = result;
// redraw the image by invalidating the container
URLImageParser.this.mView.invalidate();
}
}
private final Context mContext;
private final View mView;
public URLImageParser(Context context, View view) {
mContext = context;
mView = view;
}
#Override
public Drawable getDrawable(String source) {
Uri uri = Uri.parse(source);
URLDrawable urlDrawable = new URLDrawable();
ImageGetterAsyncTask task = new ImageGetterAsyncTask(urlDrawable);
task.execute(source);
return urlDrawable;
}
}
#Override
protected void onStart() {
super.onStart();
GoogleAnalytics.getInstance(PostViewActivity.this).reportActivityStart(this);
}
#Override
protected void onStop() {
super.onStop();
GoogleAnalytics.getInstance(PostViewActivity.this).reportActivityStop(this);
}
}

Primefaces 6 And materialprime - widget not available: selectOne

I'm trying to port materialprime to primefaces 6. I already updated the widgets to use core.js and components.js but I have a problem rendering the materialprime. selectOne is not rendering also the jsf selectOneMenu is not rendering only the priemfaces SelectOneMenu works, the console says:
widget not available: selectOne
Any ideas?
This is the code of the 4 files related to selectOne:
MaterialWidgetBuilder.java:
public class MaterialWidgetBuilder extends WidgetBuilder {
private static final String KEY = MaterialWidgetBuilder.class.getName();
public static MaterialWidgetBuilder getInstance(final FacesContext context) {
MaterialWidgetBuilder wb = (MaterialWidgetBuilder) context.getExternalContext().getRequestMap().get(KEY);
if (wb == null) {
wb = new MaterialWidgetBuilder(context);
context.getExternalContext().getRequestMap().put(KEY, wb);
}
return wb;
}
public MaterialWidgetBuilder(FacesContext context) {
super(context);
}
protected WidgetBuilder init(String widgetClass, String widgetVar, String id, String resourcePath, boolean endFunction) throws IOException {
this.endFunction = endFunction;
context.getResponseWriter().write("MaterialPrime.cw(\"");
context.getResponseWriter().write(widgetClass);
context.getResponseWriter().write("\",\"");
context.getResponseWriter().write(widgetVar);
context.getResponseWriter().write("\",{");
context.getResponseWriter().write("id:\"");
context.getResponseWriter().write(id);
if (widgetVar == null) {
context.getResponseWriter().write("\"");
} else {
context.getResponseWriter().write("\",widgetVar:\"");
context.getResponseWriter().write(widgetVar);
context.getResponseWriter().write("\"");
}
return this;
}
}
SelectOne.java:
#ResourceDependencies({
#ResourceDependency(library = "primefaces", name = "jquery/jquery.js"),
#ResourceDependency(library = "primefaces", name="core.js"),
#ResourceDependency(library = "primefaces", name="components.js"),
#ResourceDependency(library = "material-prime", name = "libs/materialize.css"),
#ResourceDependency(library = "material-prime", name = "libs/materialize.js"),
#ResourceDependency(library = "material-prime", name = "core/material-prime.js"),
#ResourceDependency(library = "material-prime", name = "core/material-prime.css"),
#ResourceDependency(library = "material-prime", name = "selectone/selectOne.js")
})
public class SelectOne extends SelectOneMenu{
public static final String COMPONENT_TYPE = "org.primefaces.material.component.SelectOne";
protected enum PropertyKeys {
nativeMode
}
public SelectOne() {
setRendererType(SelectOneRenderer.RENDERER_TYPE);
}
#Override
public String getFamily() {
return MaterialPrime.COMPONENT_FAMILY;
}
public boolean isNativeMode(){
return (Boolean) getStateHelper().eval(PropertyKeys.nativeMode,false);
}
public void setNativeMode(boolean nativeMode){
getStateHelper().put(PropertyKeys.nativeMode, nativeMode);
}
}
SelectOneRenderer.java:
public class SelectOneRenderer extends InputRenderer {
public static final String RENDERER_TYPE = "org.primefaces.material.component.SelectOneRenderer";
#Override
public void decode(FacesContext context, UIComponent component) {
SelectOne selectOne = (SelectOne) component;
if(selectOne.isDisabled()) {
return;
}
decodeBehaviors(context, selectOne);
String clientId = selectOne.getClientId(context);
String submittedValue = (String) context.getExternalContext().getRequestParameterMap().get(clientId + "_input");
if(submittedValue!=null){
selectOne.setSubmittedValue(submittedValue);
}
}
#Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
SelectOne selectOne = (SelectOne) component;
encodeMarkup(context, selectOne);
encodeScript(context, selectOne);
}
private void encodeMarkup(FacesContext context, SelectOne selectOne) throws IOException {
ResponseWriter writer = context.getResponseWriter();
String inputId = selectOne.getClientId() + "_input";
List<SelectItem> selectItems = getSelectItems(context, selectOne);
writer.startElement("div", selectOne);
writer.writeAttribute("class", "input-field", null);
writer.startElement("select", selectOne);
writer.writeAttribute("class", getSelectClass(selectOne), null);
writer.writeAttribute("id", inputId, null);
writer.writeAttribute("name", inputId, null);
for (SelectItem selectItem : selectItems) {
writer.startElement("option", null);
if(selectItem.getValue().equals(selectOne.getValue())){
writer.writeAttribute("selected", "selected", null);
}
writer.writeAttribute("value", selectItem.getValue(),null);
writer.write(selectItem.getLabel());
writer.endElement("option");
}
writer.endElement("select");
writer.endElement("div");
}
private String getSelectClass(SelectOne selectOne) {
String toReturn = "";
if(selectOne.isNativeMode()){
toReturn += " browser-default ";
}
return toReturn;
}
private void encodeScript(FacesContext context, SelectOne selectOne) throws IOException {
String clientId = selectOne.getClientId();
String widgetVar = selectOne.resolveWidgetVar();
WidgetBuilder wb = MaterialWidgetBuilder.getInstance(context);
wb.initWithDomReady("SelectOne", widgetVar, clientId);
wb.attr("widgetName", widgetVar);
encodeClientBehaviors(context, selectOne);
wb.finish();
}
}
SelectOne.js
MaterialPrime.widget.SelectOne = PrimeFaces.widget.BaseWidget.extend({
init : function(cfg) {
this._super(cfg);
this.input = jQuery(this.jqId+"_input");
var that = this;
this.input.material_select();
this.input.on("change",function(){
if(that.cfg.behaviors && that.cfg.behaviors.valueChange) {
that.cfg.behaviors.valueChange.call(that.input);
}
});
}
});

Categories