Dynamic time display crash on orientation - nullpointerexception

I have a layout that will display a TextView which is used to display a ticking time.I followed the codes from this link
How to Display current time that changes dynamically for every second in android
but I get an error of
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
I had the same problem here but I fixed it
Intent extras null on configuration change
Here are the Java codes
void clockTicking(){
final CountDownTimer newtimer = new CountDownTimer(1000000000, 1000) {
public void onTick(long millisUntilFinished) {
timeDisplay = (TextView)findViewById(R.id.txtTime);
Calendar c = Calendar.getInstance();
timeDisplay.setText(c.get(Calendar.HOUR)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND)+" PM");
}
public void onFinish() {
}
};
newtimer.start();

In your code timeDisplay object is null.
Make sure your textview id is correct. Double check this line timeDisplay = (TextView)findViewById(R.id.txtTime);
I think your id txtTime is incorrect.
Hope it will helpful.

Okay so I finally fixed it,the only reason why it crashed was because during orientation the layout I used has no TextView which Mitesh Vanaliya stated was correct.So I fixed it by turning it off upon orientation using this code thanks to Ayyappan from
How to Display current time that changes dynamically for every second in android
Turning off the clock
void clockUnTicking(){
CountDownTimer newtimer = new CountDownTimer(1000000000, 1000) {
public void onTick(long millisUntilFinished) {
timeDisplay = (TextView)findViewById(R.id.txtTime);
Calendar c = Calendar.getInstance();
timeDisplay.setText(c.get(Calendar.HOUR)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND));
}
public void onFinish() {
}
};
newtimer.cancel();
}
to turn it on just replace newtimer.cancel(); with newtimer.start()

Related

PagerAdapter always getting called two times in ViewPager

I am trying to make a slider between TouchImageView and PlayerView (Exoplayer) but I am unable to catch up with certain issues that are persisting even after several changes. All the suggestions and answers are welcome. Pardon my questioning skills and please let me know if more inputs are needed for your analysis. Kindly also let me know if there is any other alternative to successfully meet my expectations of properly implementing views smoothly in ViewPager.
Problem description:-
Issues related to click on view :-
When the image is clicked, the audio of next video (if any) starts playing in background.
The same issue is with PlayerView. When the video thumbnail is clicked, the audio of clicked video as well as next video plays together.
Issues related to slider :-
When an we slide and reach to an image preceding to a video, the audio starts playing in background. However, after sliding once toward video and sliding again in forward or backward direction from video for once, the audio stops. But this issue persists after viewing more than one images in forward or backward direction of video.
Attempts made by me to solve this issue :-
I tried to use playerView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {...}) method in PagerAdapter to handle player states while sliding between views. Unfortunately, I was unable to grasp to use different player states.
I also tried to use viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {...} method in StatusViewer class.
StatusViewer Java class (Setting PagerAdapter class object inViewPager) :-
modelFeedArrayList = (ArrayList<File>) getIntent().getSerializableExtra("modelFeedArrayList");
position = intent.getIntExtra("position", 0);
ImageSlideAdapter imageSlideAdapter = new ImageSlideAdapter(this,modelFeedArrayList,position);
viewPager.setAdapter(imageSlideAdapter);
viewPager.setCurrentItem(position);
viewPager.setOffscreenPageLimit(0);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
File currentFile = modelFeedArrayList.get(position);
String filePath = currentFile.toString();
if (filePath.endsWith(".jpg") || currentPage == position){
currentPage = position;
ImageSlideAdapter.player.pause();
}
else {
currentPage = position;
ImageSlideAdapter.player.play();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
ImageSliderAdapter (PagerAdapter) (code mentioned below is inside instantiateItem):-
File currentFile = modelFeedArrayList.get(position);
String filePath = currentFile.toString();
if (currentFile.getAbsolutePath().endsWith(".mp4")) {
statusImageView.setVisibility(View.GONE);
playerView.setVisibility(View.VISIBLE);
player = new ExoPlayer.Builder(context).build();
MediaItem mediaItem = MediaItem.fromUri(filePath);
player.addMediaItem(mediaItem);
playerView.setPlayer(player);
player.prepare();
playerView.setBackgroundColor(context.getResources().getColor(android.R.color.black));
playerView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
#Override
public void onViewAttachedToWindow(View v) {
Log.d("Filepath", filePath);
Log.d("Position", "" + position);
}
#Override
public void onViewDetachedFromWindow(View v) {
if (filePath.endsWith(".jpg") || currentPage == position || modelFeedArrayList.get(currentPage).getAbsolutePath().endsWith(".jpg")){
currentPage = position;
player.pause();
Objects.requireNonNull(playerView.getPlayer()).pause();
}
else {
player.release();
Objects.requireNonNull(playerView.getPlayer()).release();
}
}
});
} else {
playerView.setVisibility(View.GONE);
statusImageView.setVisibility(View.VISIBLE);
Glide.with(context).load(modelFeedArrayList.get(position)).into(statusImageView);
statusImageView.setBackgroundColor(context.getResources().getColor(android.R.color.black));
}
Objects.requireNonNull(container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(#NonNull #NotNull ViewGroup container, int position, #NonNull #NotNull Object object) {
container.removeView((ConstraintLayout) object);
}
Thank you StackOverflow community for viewing this question. I resolved the above issue by below mentioned modifications :-
Changes in ImageSliderAdapter (PagerAdapter) :-
-> Below mentioned code was added in onViewAttachedToWindow(View v) :-
if (filePath.endsWith(".jpg") || currentPage == position || modelFeedArrayList.get(currentPage).getAbsolutePath().endsWith(".jpg")){
currentPage = position;
player.pause();
Objects.requireNonNull(playerView.getPlayer()).pause();
}
else {
player.pause();
Objects.requireNonNull(playerView.getPlayer()).pause();
if (filePath.endsWith(".mp4")){
player.pause();
Objects.requireNonNull(playerView.getPlayer()).pause();
}
else {
player.play();
Objects.requireNonNull(playerView.getPlayer()).play();
}
}
-> Below mentioned code was added in onViewDetachedFromWindow(View v) :-
if (filePath.endsWith(".mp4")){
player.release();
Objects.requireNonNull(playerView.getPlayer()).release();
}
-> player.play() was added after player.prepare().
Changes in StatusViewer Java class :-
-> The below changes cured the issue of player malfunctioning and player's play state and release state. I used the smoothScroll: false in setCurrentItem.
viewPager.setCurrentItem(position,false);

Xamarin.Android how to remember the position of items in a recyclerview

I have a recyclerview set up in xamarin.android as per the code in this link
https://www.appliedcodelog.com/2019/08/reorder-list-items-by-drag-and-drop-in.html
My question is, how can I remember the position of these items when the app is restarted etc. When the user adds items they are inserted at adapter position 0,1,2,3 etc but when they close the app and come back in, it is not always in the same order.
The user can also rearrange by drag and drop so this seems to add even more confusion!
Currently I have the items in the recyclerview being saved by converting the list to Json and loading when the app opens again but as I said, the items aren't always in the same order as before the app was closed.
Can anyone advise the best way to do this? I have tried to add the item name and position number to a list converting to json then trying to insert the item at the saved position index but can't get it to work..
Thanks
Do you want to achieve the result like following GIF?
You can use PreferenceManager to store position of items(Before store data, I will Serialize data) in a recyclerview.
You can override OnPause() method, this method will be executed when application is background or app is killed. So we can store the position and data in this method.Here is code about ReOrderActivity
[Activity(Label = "ReOrderList")]
public class ReOrderActivity : Activity, IOnStartDragListener
{
private ItemTouchHelper _mItemTouchHelper;
public static ObservableCollection<string> ResourceList;
private RecyclerView _resourceReorderRecyclerView;
ReOrderAdapters resourceAdapter;
ISharedPreferences prefs;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.ReOrderLayout);
prefs = PreferenceManager.GetDefaultSharedPreferences(this);
GetCollection();
resourceAdapter = new ReOrderAdapters(ResourceList, this);
// Initialize the recycler view.
_resourceReorderRecyclerView = FindViewById<RecyclerView>(Resource.Id.ResourceReorderRecyclerView);
Button mDone = FindViewById<Button>(Resource.Id.mDone);
mDone.Click += MDone_Click;
_resourceReorderRecyclerView.SetLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.Vertical, false));
_resourceReorderRecyclerView.SetAdapter(resourceAdapter);
_resourceReorderRecyclerView.HasFixedSize = true;
ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(resourceAdapter);
_mItemTouchHelper = new ItemTouchHelper(callback);
_mItemTouchHelper.AttachToRecyclerView(_resourceReorderRecyclerView);
}
protected override void OnPause()
{
base.OnPause();
string ConvertData = JsonConvert.SerializeObject(ResourceList);
ISharedPreferencesEditor editor = prefs.Edit();
editor.PutString("ObservableCollection_ConvertData", ConvertData);
// editor.Commit(); // applies changes synchronously on older APIs
editor.Apply(); // applies changes asynchronously on newer APIs
}
private void MDone_Click(object sender, System.EventArgs e)
{
resourceAdapter.AddItem("Add item");
}
public void OnStartDrag(RecyclerView.ViewHolder viewHolder)
{
_mItemTouchHelper.StartDrag(viewHolder);
}
//Added sample data record here
public void GetCollection()
{
//ISharedPreferencesEditor editor = prefs.Edit();
//editor.PutString("ObservableCollection_ConvertData", "");
//editor.Apply();
string ConvertData = prefs.GetString("ObservableCollection_ConvertData","");
if(string.IsNullOrEmpty(ConvertData))
{
ResourceList = new ObservableCollection<string>();
ResourceList.Add("OnPause()");
ResourceList.Add("OnStart()");
ResourceList.Add("OnCreate()");
}
else
{
ResourceList= JsonConvert.DeserializeObject<ObservableCollection<string>>(ConvertData);
}
//var or= ResourceList.ToString();
}
}
}
You can download my demo
https://drive.google.com/file/d/1mQTKf3rlcIVnf2N97amrqtnrSCRk-8ZW/view?usp=sharing

Oscilloscope app using mpandroidchart

I'm trying to create an app that can display linegraphs at a sample rate of 15 kHz frequency and have run into two main problems:
I cant seem to set the sample rate to anywhere below 1 ms(I'm using thread.sleep(1) to set the time duration between each value.
Also the graph shows too little onscreen at any given time. I've set xAxis.setSpaceBetweenLabels to 1 and still am only getting about 6 entries on screen at any given time. Is it at all possible to get a higher sample rate(at the order of nanoseconds) and get the chart to display much higher number of entries on screen?
Currently the app displays random values as the entries. This is the code snippet:
#Override
protected void onResume() {
super.onResume();
//real time addition
new Thread(new Runnable() {
#Override
public void run() {
//adding 100 entries
for ( int i = 0;i<3000; i++) {
runOnUiThread(new Runnable() {
#Override
public void run() {
addEntry();
}
});
//pausing between each addition
//pausing between each addition
try{
Thread.sleep(600);
} catch (InterruptedException e) {
// to manage error....
}
}
}
}).start();
}
EDIT: Figured out how to show more entries onscreen (setVisibleXRange) but still have the problem of increasing samplerate.
In order to increase sampling rate just use TimeUnit.NANOSECONDS.sleep instead of Thread.sleep.
Also don't forget to import TimeUnit library(alt enter doesnt work) ;)
Thanks for all the help.

Struggling with passing messages through MVVM Light

I have two view and their corresponding ViewModels and i want to send text from one view to another using MVVM Light as follows
in first viewmodel i am calling the following method
public void NavigatePage()
{
string temp = "temp value";
Messenger.Default.Send("temp");
Frame frame = Window.Current.Content as Frame;
if (frame != null) frame.Navigate(typeof(MyPage), temp);
}
while in page 2 view model i am having the following code
public MyViewModel()
{
Messenger.Default.Register<string>(this, MessageReceived);
}
private string test;
public string Test
{
get { return test; }
set { test = value; RaisePropertyChanged("Test");}
}
private void MessageReceived(string message)
{
Test = message;
}
when i debug my code the ctor of this viewmodel is getting called but the MessageReceived is not getting called hence property Test is never getting set, I am missing something, please help
Is the SecondViewModel actually created before you send the message? You can specify this in the ViewModelLocator class.
In the locator you have to register your viewmodel and CREATE it when the applications starts.
Like this:
SimpleIoc.Default.Register<SecondViewModel>(true);
With the true parameter the SecondViewModel will be created when the application is started! :)

AutoCompleteTextView OnItemClickListener null param (landscape mode on HTC Desire S)

My Problem : I have an AutoCompleteTextView with an OnItemClickListener. This has been working fine for 18 months, but I have now noticed it throws a NullPointerException when I select an item in landscape mode on my HTC Desire S. (There is no error in portrait mode or on any other phone or emulator I've tested it on).
The AdapterView<?> av parameter is coming through as null. Why would this be, and how can I get around it?
Code :
myAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.myAutoCompleteTextView);
myAutoCompleteTextView.setSingleLine();
myAutoCompleteTextView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int index, long arg) {
String selectedItem = (String)av.getItemAtPosition(index);
//Do stuff with selected item ...
}
}
Error :
java.lang.NullPointerException
at uk.co.myCompany.mobile.android.myCompanymobile.pages.groups.AbstractGroupSelectionPage$3.onItemClick(AbstractGroupSelectionPage.java:228)
at android.widget.AutoCompleteTextView.onCommitCompletion(AutoCompleteTextView.java:993)
at com.android.internal.widget.EditableInputConnection.commitCompletion(EditableInputConnection.java:76)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:368)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:86)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:4385)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:849)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
at dalvik.system.NativeStart.main(Native Method)
Extra Code - my custom adapter inner class :
/**
* An inner class to simply make a custom adapter in which we can alter the on-screen look of selected groups.
*/
private class SelectedGroupAdapter extends ArrayAdapter<Group> {
private ArrayList<Group> items;
private int layout;
public SelectedGroupAdapter(Context context, int layout, ArrayList<Group> items) {
super(context, layout, items);
this.items = items;
this.layout = layout;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(layout, null);
}
Group o = items.get(position);
//Display the group name and number of contacts
if (o != null) {
TextView groupName = (TextView) v.findViewById(R.id.groupName);
TextView noOfContacts = (TextView) v.findViewById(R.id.noOfContacts);
if (groupName != null) {
groupName.setText(o.getGroupName());
}
if(noOfContacts != null) {
if (o.isDynamic())
noOfContacts.setText(getString(R.string.dynamic));
else {
int contactsCount = o.getGroupSize();
if(contactsCount == 1) noOfContacts.setText(contactsCount + " " + getString(R.string.contact));
else noOfContacts.setText(contactsCount + " " + getString(R.string.contacts));
}
}
}
return v;
}
}
My hunch is that since you are declaring android:configChanges="orientation" in your manifest, then when you rotate the old OnItemClickListener is still sticking around, and since you technically have a new layout, the AdapterView that was being used prior to orientation change doesn't exist anymore, thus is null when you click on an item.
There's 2 things I think that would solve this if this is the case:
Remove the orientation option in your manifest. Any events you place in configChanges tells Android "I'm taking care of this configuration change, so let me handle it" as opposed to letting Android handle it. The normal operation for Android in the event of an orientation change is to destroy and recreate your Activity (it will take care of repopulating some Views with data automatically).
If you decide you need to handle orientation changes, then override onConfigurationChanged() and set the OnItemClickListener to the new AdapterView object (ListView, GridView, whichever you are using) that should have been recreated in the onCreate method.