I am trying to create a preferences activity but for some reason, my Switch control is not behaving the way that it is supposed to. It prevents the desired itms from collapsing + my app crashes whenever I navigate to the SettingsActivity. I really don't understand why this is happening when the component has clearly been declared. Below is my code (the code for pages 2 and 3 have been omitted to reduce clutter within my question):
activity_page1.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:id="#+id/activity_page1"
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.apptacularapps.settingsapp.Page1Activity">
<View
android:id="#+id/blue_square"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:background="#drawable/shape_blue_square" />
<View
android:id="#+id/blue_circle"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:background="#drawable/shape_blue_circle"
android:layout_marginBottom="20dp"
android:layout_below="#id/blue_square"/>
<View
android:id="#+id/blue_rectangle"
android:layout_width="300dp"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:background="#drawable/shape_blue_rectangle"
android:layout_below="#id/blue_circle"/>
</RelativeLayout>
Page1Activity.java
public class Page1Activity extends AppCompatActivity {
boolean squareState;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
}
#Override
public void onResume(){
super.onResume();
loadPreferences();
displaySettings();
}
public void loadPreferences(){
SharedPreferences pref = getSharedPreferences("settings", AppCompatActivity.MODE_PRIVATE);
squareState = pref.getBoolean("square_state", true);
}
public void displaySettings() {
if (squareState) {
findViewById(R.id.blue_square).setVisibility(View.VISIBLE);
} else {
findViewById(R.id.blue_square).setVisibility(View.GONE);
}
}
}
activity_settings.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.packagename.settingsapp.SettingsActivity">
<android.support.v7.widget.SwitchCompat
android:id="#+id/square_switch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="true"
android:layout_margin="20dp"
android:text="Show squares"
style="#android:style/TextAppearance.Large" />
<android.support.v7.widget.SwitchCompat
android:id="#+id/circle_switch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="true"
android:layout_margin="20dp"
android:text="Show circles"
style="#android:style/TextAppearance.Large"
android:layout_below="#id/square_switch"/>
<android.support.v7.widget.SwitchCompat
android:id="#+id/rectangle_switch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="true"
android:layout_margin="20dp"
android:text="Show rectangles"
style="#android:style/TextAppearance.Large"
android:layout_below="#id/circle_switch"/>
</RelativeLayout>
SettingsActivity.java
public class SettingsActivity extends AppCompatActivity {
boolean squareState;
SwitchCompat squareSwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
#Override
public void onResume(){
super.onResume();
loadPreferences();
displaySettings();
}
public void loadPreferences(){
SharedPreferences pref = getSharedPreferences("settings", AppCompatActivity.MODE_PRIVATE);
squareState = pref.getBoolean("square_state", true);
}
public void displaySettings(){
squareSwitch.setChecked(squareState);
}
#Override
public void onPause(){
super.onPause();
savePreferences();
}
private void savePreferences(){
SharedPreferences pref = getSharedPreferences("settings", AppCompatActivity.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("square_state", squareState);
editor.apply();
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int id = buttonView.getId();
switch(id){
case R.id.square_switch:
squareState = isChecked;
break;
}
}
}
Current result
Expected result
You're not attaching squareSwitch to any UI component. Update your SettingsActivity.java to the following:
public class SettingsActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
boolean squareState;
SwitchCompat squareSwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
squareSwitch = (SwitchCompat)findViewById(R.id.square_switch); //add this line
squareSwitch.setOnCheckedChangeListener(this); //Also add this
}
#Override
public void onResume(){
super.onResume();
loadPreferences();
displaySettings();
}
public void loadPreferences(){
SharedPreferences pref = getSharedPreferences("settings", AppCompatActivity.MODE_PRIVATE);
squareState = pref.getBoolean("square_state", true);
}
public void displaySettings(){
squareSwitch.setChecked(squareState);
}
#Override
public void onPause(){
super.onPause();
savePreferences();
}
private void savePreferences(){
SharedPreferences pref = getSharedPreferences("settings", AppCompatActivity.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("square_state", squareState);
editor.apply();
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int id = buttonView.getId();
switch(id){
case R.id.square_switch:
squareState = isChecked;
break;
}
}
Also, you don't need to implement CompoundButton.OnCheckedChangeListener and override onCheckedChanged in Page1Activity you might want to remove those from there.
Related
I am building a simple video player Ui and I have a : seekbar and two buttons to controle the video view, when I click on any point of seekbar every thing is ok and video view progress will be the same with seekbar and the buttons is working too ! but,when I handle the seekbar thumb and move it ,then leave it, every thing messing up and the seekbar and the buttons will never work again, so I am not getting an Exception error it's just will not work again. why that happening?
Activity
public class Player extends AppCompatActivity {
View controller;
Handler handler;
SeekBar seekBar;
VideoView videoView;
ImageButton play_btn, pause_btn;
ImageButton forward_btn, replay_btn;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
handler = new Handler();
videoView = (VideoView) findViewById(R.id.videoView);
controller = findViewById(R.id.player_controller); // the controller View
hideController(controller);
forward_btn = (ImageButton) findViewById(R.id.playerController_forward_10_Button);
replay_btn = (ImageButton) findViewById(R.id.playerController_replay_10_Button);
forward_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
forward_10_sec();
}
});
replay_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
reply_10_sec();
}
});
play_btn = (ImageButton) findViewById(R.id.playerController_playButton);
pause_btn = (ImageButton) findViewById(R.id.playerController_pauseButton);
play_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play();
}
});
pause_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pause();
}
});
seekBar = findViewById(R.id.playerController_seekBar); // video seekBar
seekBar.setOnSeekBarChangeListener(onSeekBarChangeListener);
videoView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (controller.getVisibility() == View.INVISIBLE)
showController(controller);
else
hideController(controller);
}
});
Intent intent = getIntent();
if (intent != null)
setVideoSource(intent);
}
private void play() {
if(!videoView.isPlaying()) {
videoView.start();
play_btn.setVisibility(View.INVISIBLE);
pause_btn.setVisibility(View.VISIBLE);
}
}
private void pause() {
if(videoView.isPlaying()) {
videoView.pause();
pause_btn.setVisibility(View.INVISIBLE);
play_btn.setVisibility(View.VISIBLE);
}
}
private void forward_10_sec() {
if (videoView.canSeekForward())
videoView.seekTo(videoView.getCurrentPosition() + 1000);
}
private void reply_10_sec() {
if (videoView.canSeekBackward())
videoView.seekTo(videoView.getCurrentPosition() - 1000);
}
// to show the controllers
private void showController(View controller) {
controller.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
hideController(controller);
}
}, 6000);
}
// to hide the controllers
private void hideController(View controller) {
controller.setVisibility(View.INVISIBLE);
}
// to set video source from the main app or file manager
private void setVideoSource(Intent intent) {
... some codes to set path ...
play();
showController(controller);
updateSeekBarProgress();
}
// to move seekBar to real video progress
private void updateSeekBarProgress() {
Player.this.runOnUiThread(updateSeekBar);
}
private Runnable updateSeekBar = new Runnable() {
#Override
public void run() {
seekBar.setMax(videoView.getDuration() / 1000);
seekBar.setProgress(videoView.getCurrentPosition() / 1000);
seekBar.postDelayed(this,500);
}
};
SeekBar.OnSeekBarChangeListener onSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if (b) {
videoView.seekTo(i*1000);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
}
activity_player
<?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"
android:background="#color/black"
tools:context=".Player">
<VideoView
android:id="#+id/videoView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<include
android:id="#+id/player_controller"
layout="#layout/player_controller" />
</androidx.constraintlayout.widget.ConstraintLayout>
player_controller
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/transparent_black">
<ImageButton
android:id="#+id/playerController_playButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null"
android:src="#drawable/play_icon_48"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="#+id/playerController_pauseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null"
android:src="#drawable/pause_icon_48"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="#+id/playerController_replay_10_Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null"
android:src="#drawable/replay_10_icon_48"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#id/playerController_playButton"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="#+id/playerController_forward_10_Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null"
android:src="#drawable/forward_10_icon_48"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#id/playerController_playButton"
app:layout_constraintTop_toTopOf="parent" />
<SeekBar
android:id="#+id/playerController_seekBar"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginStart="5dp"
android:layout_marginEnd="5dp"
android:progressBackgroundTint="#color/white"
android:progressTint="#color/white"
android:secondaryProgressTint="#color/light_purple"
android:thumbTint="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/playerController_playButton" />
</androidx.constraintlayout.widget.ConstraintLayout>
so, in a simple way : I want to set video view progress like seekbar progress with any way that I move the seek bar with.
(now it's just works when click on it and when handle and move it , nothing works again).
thanks...
It's finally has been done with that :
SeekBar.OnSeekBarChangeListener onSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if (b) {
videoView.seekTo(i * 1000);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
handler.removeCallbacks(updateSeekBar);
pause();
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
videoView.seekTo(seekBar.getProgress()*1000);
play();
updateSeekBarProgress();
}
};
I have a problem ,I create recyclerview and its work fine at the first search data from api , it display fine but when I try to search with new data ( second time ) it is not display anything i try to test and debug every every thing work fine and new data enter to adapter and get the result fine and set adapter to recyclerview but it is not showing any thing
I try several method like use only one adapter and change it's list of Date and use notifyDataSetChange but not work still only show at the first time
Below activity is use to search get date ( use in searching data )
fromDate to toDate
DeliveryReportActivity.java
public class DeliveryReportActivity extends AppCompatActivity
implements DateDialogFromFragment.SelectDateFromInterface,
DateDialogToFragment.SelectDateToInterface {
Button btn_from;
Button btn_to;
EditText et_fromDate;
EditText et_toDate;
Button search_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delivery_report);
btn_from=(Button)findViewById(R.id.btn_fromDate);
btn_to=(Button)findViewById(R.id.btn_toDate);
et_fromDate = (EditText) findViewById(R.id.from_date);
et_toDate = (EditText) findViewById(R.id.to_date);
search_btn=(Button)findViewById(R.id.search_delivery_report_btn);
et_fromDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(new
Date()));
et_toDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(new
Date()));
btn_from.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DateDialogFromFragment dateDialogFragment = new
DateDialogFromFragment();
android.app.FragmentTransaction ft =
getFragmentManager().beginTransaction();
dateDialogFragment.show(ft, "DatePicker");
}
});
btn_to.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DateDialogToFragment dateDialogFragment = new
DateDialogToFragment();
android.app.FragmentTransaction ft =
getFragmentManager().beginTransaction();
dateDialogFragment.show(ft, "DatePicker");
}
});
search_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle bundle=new Bundle();
bundle.putString("from",et_fromDate.getText().toString()+ "
00:00:00");
bundle.putString("to",et_toDate.getText().toString()+" 23:59:59");
Intent intent =new
Intent(DeliveryReportActivity.this,DeliveryReportListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
#Override
public void onGetSelectFromDate(String fromDate) {
et_fromDate.setText(fromDate);
}
#Override
public void onGetSelectToDate(String toDate) {
et_toDate.setText(toDate);
}
}
and it's view activity_delivery_report.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:orientation="vertical"
tools:context="com.exatech.groupsmsandroid.activity.
deliveryReport.DeliveryReportActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/btn_fromDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/From"
android:textSize="18dp" />
<EditText
android:id="#+id/from_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="2017-12-26" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:orientation="horizontal">
<Button
android:id="#+id/btn_toDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/to" />
<EditText
android:id="#+id/to_date"
android:text="2017-12-26"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_centerInParent="true"
android:gravity="center"
android:layout_marginTop="20dp"
android:id="#+id/search_delivery_report_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:text="#android:string/search_go" />
</RelativeLayout>
</LinearLayout>
after I press the search button it's start new activity that show my recylerview the new activity is
DeliveryReportListActivity .java
public class DeliveryReportListActivity extends AppCompatActivity implements
DeliveryReportService.DeliveryReportServiceInterface {
private static final String TAG = "GSMS";
private Bundle bundle;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delivery_report_list);
recyclerView = (RecyclerView) findViewById(R.id.delivery_report_rv);
}
#Override
protected void onResume() {
super.onResume();
bundle = getIntent().getExtras();
String from = bundle.getString("from");
String to = bundle.getString("to");
DeliveryReportService.getInstance(this).
getDeliveryReportFromDateToDate(from, to);// Call api get deliver
}
#Override
public void onGetDeliveryReport(Response<List<DeliveryReportResource>>
listResponse) {// response
Log.i(TAG, "onGetDeliveryReport: listResponse.body():" +
listResponse.body());
DeliveryReportAdapter deliveryReportAdapter = new
DeliveryReportAdapter(DeliveryReportListActivity.this, listResponse.body());
recyclerView.setAdapter(deliveryReportAdapter);
deliveryReportAdapter.notifyDataSetChanged();
Toast.makeText(DeliveryReportListActivity.this, "Delivery Report Success
", Toast.LENGTH_SHORT).show();
}
#Override
public void onDeliveryConnectionFailed() {
Toast.makeText(DeliveryReportListActivity.this, "Connect Error ",
Toast.LENGTH_SHORT).show();
}
}
and it's view activity_delivery_report_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.exatech.groupsmsandroid.activity.deliveryReport.
DeliveryReportListActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:text="#string/text"
android:layout_weight="3"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_weight="4"
android:text="#string/phone_no"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_weight="4"
android:text="#string/status"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/delivery_report_rv"
android:layout_width="match_parent"
app:layoutManager="LinearLayoutManager"
android:layout_height="match_parent"
tools:listitem="#layout/delivery_report_list_content"/>
</LinearLayout>
Below is Myadapter Class
**DeliveryReportAdapter.java**
public class DeliveryReportAdapter extends
RecyclerView.Adapter<DeliveryReportAdapter.ViewHolder> {
List<DeliveryReportResource> listDeliveryReport;
Context context;
public DeliveryReportAdapter(Context context, List<DeliveryReportResource>
listDeliveryReport) {
this.listDeliveryReport = listDeliveryReport;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view =
LayoutInflater.from(parent.getContext()).
inflate(R.layout.delivery_report_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.item = listDeliveryReport.get(position);
holder.text.setText(holder.item.getText());
CustomAdapterFroDeliveryReport adapterFroDeliveryReport = new
CustomAdapterFroDeliveryReport(context, R.layout.two_text_contect,
listDeliveryReport.get(position).getSmsSubscribedRecipientsResourceList());
holder.phoneNoAndStatus.setAdapter(adapterFroDeliveryReport);
holder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "click message no=" +
holder.item.getText(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return listDeliveryReport.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
View view;
TextView text;
ListView phoneNoAndStatus;
DeliveryReportResource item;
public ViewHolder(View itemView) {
super(itemView);
view = itemView;
text = (TextView) itemView.findViewById(R.id.message_tv);
phoneNoAndStatus = (ListView)
itemView.findViewById(R.id.phoneNo_and_status_lv);
}
}
}
Try to create an adapter once and then update items
Add next code to your adapter class
ArrayList<DeliveryReportResource> listDeliveryReport = new ArrayList<DeliveryReportResource>();
public DeliveryReportAdapter(Context context) {
this.context = context;
}
public void updateItems(List<DeliveryReportResource> list) {
listDeliveryReport.clear();
listDeliveryReport.addAll(list);
notifyDataSetChanged();
}
Then create adapter once in onCreate() and place it as global variable
And now you should call adapter.updateItems(...) every time you want to change data
I am creating an app which have a setting PreferenceActivity with actionbar and that's working fine. I want to use another custom PreferenceActivity with actionbar which is using a layout (activity_about.xml) and preference layout (about_preferences.xml). But when i run the app it's causing my app to crash on calling that activity. Probably the actionbar is returning the Null, i can't figure it out where is the problem. Please help.
My ActivityAbout.java
public class ActivityAbout extends PreferenceActivity {
private AppCompatDelegate mDelegate;
private ActionBar actionBar;
private SharedPref sharedPref;
private View parent_view;
private TextView ver;
Context context=this;
#Override
protected void onCreate(Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.about_preferences);
setContentView(R.layout.activity_about);
View lv = findViewById(android.R.id.list);
if (lv != null) lv.setPadding(0, 0, 0, 0);
final Preference prefPrivacy = (Preference) findPreference(getString(R.string.pref_title_privacy));
final Preference prefTerm = (Preference) findPreference(getString(R.string.pref_title_term));
final Preference prefBuild = (Preference) findPreference(getString(R.string.pref_title_build));
final Preference prefCopyright = (Preference) findPreference(getString(R.string.pref_title_copyright));
String versionName = BuildConfig.VERSION_NAME;
ver = (TextView) findViewById(R.id.version);
ver.setText("Version "+versionName);
prefBuild.setSummary("Version "+versionName);
int y = Calendar.getInstance().get(Calendar.YEAR);
prefCopyright.setSummary("Copyright © "+y+" Get Rid Remedy.\nAll Right Reserved.");
prefPrivacy.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
dialogPrivacy(ActivityAbout.this);
return false;
}
});
prefTerm.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
dialogTerm(ActivityAbout.this);
return false;
}
});
initToolbar();
}
public void dialogPrivacy(Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(activity.getString(R.string.pref_title_privacy));
builder.setMessage(activity.getString(R.string.content_privacy));
builder.setPositiveButton("OK", null);
builder.show();
}
public void dialogTerm(Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(activity.getString(R.string.pref_title_term));
builder.setMessage(activity.getString(R.string.content_term));
builder.setPositiveButton("OK", null);
builder.show();
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
getDelegate().onPostCreate(savedInstanceState);
}
private void initToolbar() {
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setTitle(R.string.activity_title_settings);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
public ActionBar getSupportActionBar() {
return getDelegate().getSupportActionBar();
}
public void setSupportActionBar(#Nullable Toolbar toolbar) {
getDelegate().setSupportActionBar(toolbar);
}
#Override
public MenuInflater getMenuInflater() {
return getDelegate().getMenuInflater();
}
#Override
public void setContentView(#LayoutRes int layoutResID) {
getDelegate().setContentView(layoutResID);
}
#Override
public void setContentView(View view) {
getDelegate().setContentView(view);
}
#Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().setContentView(view, params);
}
#Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().addContentView(view, params);
}
#Override
protected void onPostResume() {
super.onPostResume();
getDelegate().onPostResume();
}
#Override
protected void onTitleChanged(CharSequence title, int color) {
super.onTitleChanged(title, color);
getDelegate().setTitle(title);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getDelegate().onConfigurationChanged(newConfig);
}
#Override
protected void onStop() {
super.onStop();
getDelegate().onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
getDelegate().onDestroy();
}
public void invalidateOptionsMenu() {
getDelegate().invalidateOptionsMenu();
}
private AppCompatDelegate getDelegate() {
if (mDelegate == null) {
mDelegate = AppCompatDelegate.create(this, null);
}
return mDelegate;
}
}
Here is the about_preferences layout.
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<Preference
android:key="#string/pref_title_dev_email"
android:summary="#string/developer_email"
android:title="#string/pref_title_dev_email"/>
<Preference
android:key="#string/pref_title_copyright"
android:summary="#string/copyright"
android:title="#string/pref_title_copyright"/>
<Preference
android:key="#string/pref_title_build"
android:summary="#string/app_version"
android:title="#string/pref_title_build"/>
<Preference
android:key="#string/pref_title_privacy"
android:title="#string/pref_title_privacy"
android:widgetLayout="#layout/ic_about"/>
<Preference
android:key="#string/pref_title_term"
android:title="#string/pref_title_term"
android:widgetLayout="#layout/ic_about"/>
Here is activity_about.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="#+id/activity_about"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.overridecode.getridremedy.ActivityAbout">
<android.support.design.widget.AppBarLayout
android:id="#+id/tool"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<include layout="#layout/toolbar" />
</android.support.design.widget.AppBarLayout>
<LinearLayout
android:layout_below="#+id/tool"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/activity_vertical_margin">
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_gravity="center"
app:srcCompat="#mipmap/ic_launcher"
android:id="#+id/imageView" />
<TextView
android:text="#string/app_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_marginTop="10dp"
android:textSize="30dp"
android:textStyle="bold"
android:textColor="#73000000"
android:id="#+id/app_title" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:id="#+id/version" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignParentBottom="true">
<ListView android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
The error i am getting:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.overridecode.getridremedy/
com.overridecode.getridremedy.ActivityAbout}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
Add an ID to your Toolbar:
<include
android:id="#+id/toolbar_prefs"
layout="#layout/toolbar" />
And call setSupportActionBar() (passing your Toolbar instance) before calling getSupportActionBar():
private void initToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_prefs);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setTitle(R.string.activity_title_settings);
}
Otherwise getSupportActionBar() will return null.
As per my experience, I found there is no ActionBar in preference activity. So,
There are following steps to add toolbar in your activity
Add in xml
<include layout="#layout/toolbar" />
Set Toolbar in java class using following code.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarId);
setSupportActionBar(toolbar);
NOTE: here you need to use this code in starting of intitToolbar() method.
Import proper class/package for your toolbar. From your comments seems you need to import
import android.support.v7.widget.Toolbar;
Hope this may help you. If helps, please approve it as right answer.
I have made a progress bar in Android but it is not at all working. What am I doing wrong? I have just started to learn android. Below is my code.
MainActivity.java-
public class MainActivity extends AppCompatActivity {
ProgressBar progressBar;
int mporgress=0;
EditText time;
private Handler mHandler = new Handler();
private static final int PROGRESS = 0x1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void Startbuttononclick(View view){
Button startbutton=(Button) findViewById(R.id.button);
startbutton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
mporgress = Integer.parseInt(time.getText().toString());
progressBar.setProgress(mporgress);
new Thread(new Runnable() {
public void run() {
while (mporgress < 100) {
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(mporgress);
mporgress = doWork();
try{
Thread.sleep(1000);
}catch (InterruptedException e){}
}
});
}
}
}).start();
}
});
}
public void doprogress(View view) {
}
public int doWork(){
mporgress++;
return mporgress;
}
}
Activity_main.xml-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.android.progressbar.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the time:"
android:inputType="number"
android:id="#+id/editText" />
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="500dp"
android:layout_height="200dp"
android:id="#+id/progressBar4"
android:layout_gravity="center"
android:scrollbarSize="500dp" />
<Button
android:text="START"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_gravity="center"
android:onClick="Startbuttononclick" />
</LinearLayout>
Check out this image below-
- https://i.stack.imgur.com/2TBIb.png
Note- Enter the time in this image is an EditText with a hint and not a TextView.
It is appearing but not working.
I have done these changes so far.-
https://i.stack.imgur.com/UujpB.png
But still the progress bar is still continuously rotating.
Seems you forgot to initialize EditText -time and ProgressBar. Init it inside onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar =(ProgressBar) findViewById(R.id.progressBar4);
time = (EditText) findViewById(R.id.editText); //here
}
Also inside button click the bar:
progressBar = new ProgressBar(this);
mporgress = Integer.parseInt(time.getText().toString());
................
.............
Hi I am new to Android and Java and have run into a problem. My problem is that i am trying to add a PreferenceScreen to my linear layout so I am able to set an setOnSeekBarChangeListener() on the seekbar in res/layout/activity_main.xml. At the moment the PreferenceScreen and the LinearLayout get added to the view but they are on top of each other which is not what I want. Instead I want the PreferenceScreen to go in place of the ListView inside my layout file.
res/xml/settings.xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Category"
android:key="category_preference">
<SwitchPreference
android:key="switch_preference"
android:title="Title"
android:summary="Summary"
android:defaultValue="true" />
<CheckBoxPreference
android:key="checkbox_preference"
android:title="Title"
android:summary="Summary"
android:defaultValue="true" />
</PreferenceCategory>
</PreferenceScreen>
res/layout/activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_height="fill_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=".MainActivity" >
<SeekBar
android:id="#+id/main_seek_bar"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ListView android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
setContentView(R.layout.activity_main);
SeekBar seekBar = (SeekBar) findViewById(R.id.main_seek_bar);
seekBar.setOnTouchListener(new SeekBar.OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
return false;
}
});
}
public static class SettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener {
public static final String KEY_PREF_SYNC_CONN = "pref_syncConnectionType";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
onSharedPreferenceChanged(null, "");
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("switch_preference")) {
Toast.makeText(getActivity(), "Switch", Toast.LENGTH_LONG).show();
}
}
}
}
in your res/layout/activity_main.xml file change
<ListView android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
to
<fragment android:id="#+id/fragment_settings"
android:layout_width="fill_parent"
android:name="yourpackagename.MainActivity$SettingsFragment"
android:layout_height="fill_parent" />
and then in your MainActivity.java file remove the following line
getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();