Android update view data

Update View at runtime in Android

The example is pretty straightforward: i want to let the user know about what the app is doing by just showing a text (canvas.drawText()). Then, my first message appears, but not the other ones. I mean, i have a «setText» method but it doesn’t updates.

The view’s text drawing works by doing just a drawText in onDraw();, so setText changes the text but doesn’t show it.

Someone recommended me replacing the view with a SurfaceView, but it would be alot of trouble for just a couple of updates, SO. how the heck can i update the view dinamically at runtime?

It should be quite simple, just showing a text for say 2 seconds and then the main thread doing his stuff and then updating the text.

I tried implementing handler.onPost(), but is the same story all over again. Let me put you the code:

Although splash is in other thread, i put a sleep on the main thread, i use the handler to manage UI and everything, it doesn’t changes a thing, it only shows the last update.

3 Answers 3

I haven’t hit this yet, but I think the usual pattern is to do lengthy initialization in a background thread, and use Handler.post() to update the UI. See http://developer.android.com/reference/android/widget/ProgressBar.html for a different, but possibly related, example.

Also see this answer, especially the first paragraph:

The problem is most likely that you are running the splash screen (some sort of Dialog such as ProgressDialog I assume) in the same thread as all the work being done. This will keep the view of the splash screen from being updated, which can keep it from even getting displayed to the screen. You need to display the splash screen, kick off an instance of AsyncTask to go download all your data, then hide the splash screen once the task is complete.

Update (based on your update and your comment): You are not supposed to update the UI in any thread except the one where your Activity is created. Why is it impossible for you to load your resources in a background thread?

Источник

Updating UI using ViewModel and DataBinding

I am trying to learn ViewModel in android, in my first phase of learning I am trying to update UI (TextView) by using ViewModel and DataBinding. In ViewModel, I have an AsyncTask callback and it will invoke REST API call. I am getting the response from API call but the value in textview is not getting updated.

my ViewModel class:

and my MainActivity class:

and my data class:

and layout file

3 Answers 3

I suggest to follow next basic principles:

  • don’t overload data objects by business or presentation logic
  • only view model required to obtain data in presentation layer
  • view model should expose only ready to use data to presentation layer
  • (optional) background task should expose LiveData to deliver data
  • firstName is read only on view
  • lastName is editable on view
  • loadUser() is not threadsafe
  • we have error message when call save() method until data is not loaded

Don’t overload data objects by business or presentation logic

Suppose, we have UserData object with first and last name. So, getters it’s (usually) all what we need:

Читайте также:  Лучшие порты для андроид

Only view model required to obtain data in presentation

To follow this suggestion we should to use only view model in data binding layout:

Note: you can use a few view models in one layout, but not raw data

View model should expose only ready to use data to presentation

This mean, you shouldn’t to expose complex data objects ( UserData in our case) directly from view model. Preferable to expose privative types which view can use as-is. In example below we don’t need to hold UserData object because it used only to loading grouped data. We, probably, need to create UserData to save it but it depends on your repository implementation.

Background task should expose LiveData to deliver data

MainActivity.java

PS: try to use RxJava library instead of AsyncTask to perform background work.

Источник

Updating the list view when the adapter data changes

When the data associated with array adapter is changed, invalidating the listview is sufficient to show the updated values? Following piece of code is not working, did i misunderstood something here.?

4 Answers 4

If that doesnt work, refer to this thread: Android List view refresh

Change this line:

and after updating the value of a list item, call:

invalidate(); calls the list view to invalidate itself (ie. background color)
invalidateViews(); calls all of its children to be invalidated. allowing you to update the children views

I assume its some type of efficiency thing preventing all of the items to constantly have to be redraw if not necessary.

I found a solution that is more efficient than currently accepted answer, because current answer forces all list elements to be refreshed. My solution will refresh only one element (that was touched) by calling adapters getView and recycling current view which adds even more efficiency.

Not the answer you’re looking for? Browse other questions tagged android or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.12.3.40888

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Update ViewPager dynamically?

I can’t update the content in ViewPager.

What is the correct usage of methods instantiateItem() and getItem() in FragmentPagerAdapter class?

I was using only getItem() to instantiate and return my fragments:

This worked well. Except I can’t change the content.

«My approach is to use the setTag() method for any instantiated view in the instantiateItem() method»

Now I want to implement instantiateItem() to do that. But I don’t know what I have to return (the type is Object) and what is the relation with getItem(int position)?

public abstract Fragment getItem (int position)

Return the Fragment associated with a specified position.

public Object instantiateItem (ViewGroup container, int position)

Create the page for the given position. The adapter is responsible for adding the view to the container given here, although it only must ensure this is done by the time it returns from finishUpdate(ViewGroup). Parameters

container The containing View in which the page will be shown. position The page position to be instantiated.

Returns an Object representing the new page. This does not need to be a View, but can be some other container of the page.

but I still don’t get it.

Here’s my code. I’m using support package v4.

21 Answers 21

When using FragmentPagerAdapter or FragmentStatePagerAdapter, it is best to deal solely with getItem() and not touch instantiateItem() at all. The instantiateItem() — destroyItem() — isViewFromObject() interface on PagerAdapter is a lower-level interface that FragmentPagerAdapter uses to implement the much simpler getItem() interface.

Читайте также:  Как настроить vlc media player для андроид

Before getting into this, I should clarify that

if you want to switch out the actual fragments that are being displayed, you need to avoid FragmentPagerAdapter and use FragmentStatePagerAdapter.

An earlier version of this answer made the mistake of using FragmentPagerAdapter for its example — that won’t work because FragmentPagerAdapter never destroys a fragment after it’s been displayed the first time.

I don’t recommend the setTag() and findViewWithTag() workaround provided in the post you linked. As you’ve discovered, using setTag() and findViewWithTag() doesn’t work with fragments, so it’s not a good match.

The right solution is to override getItemPosition() . When notifyDataSetChanged() is called, ViewPager calls getItemPosition() on all the items in its adapter to see whether they need to be moved to a different position or removed.

By default, getItemPosition() returns POSITION_UNCHANGED , which means, «This object is fine where it is, don’t destroy or remove it.» Returning POSITION_NONE fixes the problem by instead saying, «This object is no longer an item I’m displaying, remove it.» So it has the effect of removing and recreating every single item in your adapter.

This is a completely legitimate fix! This fix makes notifyDataSetChanged behave like a regular Adapter without view recycling. If you implement this fix and performance is satisfactory, you’re off to the races. Job done.

If you need better performance, you can use a fancier getItemPosition() implementation. Here’s an example for a pager creating fragments off of a list of strings:

With this implementation, only fragments displaying new titles will get displayed. Any fragments displaying titles that are still in the list will instead be moved around to their new position in the list, and fragments with titles that are no longer in the list at all will be destroyed.

What if the fragment has not been recreated, but needs to be updated anyway? Updates to a living fragment are best handled by the fragment itself. That’s the advantage of having a fragment, after all — it is its own controller. A fragment can add a listener or an observer to another object in onCreate() , and then remove it in onDestroy() , thus managing the updates itself. You don’t have to put all the update code inside getItem() like you do in an adapter for a ListView or other AdapterView types.

One last thing — just because FragmentPagerAdapter doesn’t destroy a fragment doesn’t mean that getItemPosition is completely useless in a FragmentPagerAdapter. You can still use this callback to reorder your fragments in the ViewPager. It will never remove them completely from the FragmentManager, though.

Источник

SQLite Database Update in Android

Please follow the below steps in order to update data in SQLite database using our Android app:

Step 1) First add one more button and this button we are going to use to update the data, so I’m going to change the name of the button as an update.

Step 2) And one more thing we want to do is, if you remember our database table contains four columns. First one was id, the second one was name, surname and the marks scored by the students. And to update the data we need a unique reference of the row so that we can tell SQLite that we want to delete the data from this row.

Because names can be same so if you want to change the name of one partner which shares the name with the other person then the data can be changed for both the names if you don’t know what is the unique you know row or unique column in this, So id we have defined as a unique column for this database table.

Читайте также:  Как разблокировать клавиатуры андроид

Step 3) Now we need to create a function in our database helper .javaclass which we have created in the last tutorial so go to the database helper .javafile and in here till now we have created insert data and get all data function right. Now we will create one more function here and we will call it as updateData.

So it will be public and it’ll return boolean and It’s going to take four arguments. The First argument we are going to pass here will be string id, second is string name, third is string surname and fourth is string marks.

basically, we want to pass all the four column data to it. Because our table will contain four columns, id, name, surname and marks right.

Step 4) Now in here what we’re going to do is, as we have done inserting data function. First of all, we will create SQLite database instance and then we are going to create an instance of content value.

Step 5) And then as we have done in this insert data function that we’re putting whatever data is passed from the argument to this content value using put. So let’s do it and one more column we need to add here and this will be for column 1 and its id in our case right. Because this contains extra id here. The only difference in update data functions and insert data function is, the method we are going to use now.

Step 6) So just take your database instance now and then call update here. And this update will update whatever argument you pass here. The first argument it takes is the name of your table okay. So give the name if you remember. we have declared table name here right so first argument is the table name right. Second is the content value. So it takes the second argument as a content value so we take this instance of content value and pass it here. The third argument is the condition which we want to pass here. So what we want to do, we want to update data on the basis of for example id because id is our unique primary key here and on the basis of primary key we can differentiate data. So in here we will write So we will you know ask whatever id is passed using this id parameter we are going to query this and fourth is the value on the basis of which we want to update our data so this is the column name on the basis of which we want to update the data and our column name is id so you can just write here column name, id is equal to and then in here, fourth argument. Lets go inside this update, so hover over control and click and see it takes the fourth argument as the string array right. So we will go back and pass string array here right.

And if everything goes well, we want to return, return to know that if the data is really updated or not.

Step 7) Now this is done, what we are going to do is we are going to move to our main activity .javafile and in here we will declare one more button variable which will be our button for update so button update and then we are going to take this button instance and we will cast it as a button using the id.

So go to the onCreate method where you have type casted all other tools or widgets and cast this button.

Источник

Оцените статью