need to replace setUserVisibleHint in AndroidX as it is deprecated, can anybody help - Android Q&A, Help & Troubleshooting

I have 3 fragments attached with viewpager.
I have a single database and all three fragments data is connected to each other so if i make any change in fragment 1 & it should also be reflected in fragment 2(when it is visible to user)
previously i was using
Code:
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser){
getFragmentManager().beginTransaction().detach(this).attach(this).commit();
}
}
but setUserVisibleHint is deprecated so i need to replace it but cloudn't find proper solution.
I tried to used "detach().attach()" in onResume but it goes to infinite loop then.
Note: i tried to use "notifyDataSetChanged()" instead of detach.attach but it doesn't work properly and takes time to reflect data.
I tried to recreate activity but it push the recyclerView on first item. I want my recyclerView to be show on the same state where it previously was like if it was on item no 24 before leaving it then whenever user comeback on same fragment by doing detach.attach data is refreshed and recyclerView is on same position.
Please tell me the alternative solution for detach.attach on every desired fragment is visible to user.
Thanks

Related

[Q] Call method from view to activity

hi, how can i call a method that is in a view.java going to my activity.java? is there a command for that?
please help =(
In general, if the classes can "see" each other, and the method you want to call is accessible by the caller class, then just call the method via an instance of the according class. So let's say there were class A in file A.java with the method a() and you want to call it from class B in B.java you need to make sure that a() is not a private method (declared public, protected or not explicitly declared) and also it were good if the classes shared the same package.
Then just create an instance of A accessible by a method of B. (only necessary if a() isn't static!) For example like:
Code:
class B {
B() {
A objectOfTypeA = new A();
objectOfTypeA.a();
// voila
}
}
So as you can see there's no special command necessary to call a method of another class. Also I recommend you to read some tutorials about controlling access to members of a class.

[Q] Why is my onboot broadcastreceiver activty being killed

Im new to android development, so probably be making al the old mistakes.
I created an app it runs fine.
I added an broadcast receiver to do some actions on boot of the device
On boot i want to write some data to the SDcard so ill have to wait for it to become ready.
This is how i tried to do it.
psuedo code/code snipet
Code:
public class bootActivity extends BroadcastReceiver
{
@Override
public void onReceive(final Context context, final Intent intent)
{
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()))
{
new Thread()
{
@Override
public void run()
{
Log.d("TEST","starting");
for(;;)
{
Log.d("TEST","waitloop");
mc=Environment.getExternalStorageState();
try { Thread.sleep(10000); } catch(Exception ex) {}
if(mc.equals(Environment.MEDIA_MOUNTED)) break;
}
Log.d("TEST","do something");
// from here i write to sdcard...
}
}
}
}
In the emulator it works fine, with logcat i see
- D/TEST starting
- D/TEST waitloop (one or more)
- D/TEST do something
and the expected data gets writeen to the SDcard
On my real device i have problems, with logcat is see
- D/TEST starting
- D/TEST waitloop only once
- D/ActivityManager Kill hidden process PID: 333 with NAME test.test.test
Q1) Why is my broadcast activity being killed during boot
(and why does it work in the emulator and not on the real devices)
Q2) If case i'm doing everything wrong
What is the correct/better way to get the same result ?
First you'll want to confirm your process isn't crashing (look for a stack trace in your logcat view in Eclipse or on your phone using the alogcat app).
Besides that, Android is known to kill services if it runs low on memory. This is likely to happen during bootup when a lot of programs are run in sequence. By defining your service a certain way in your androidmanifest you can have the OS re-send intents if the service is killed. There's also a way to make your service a so called foreground service, which Android will think twice about killing. In either case, it's always safe to assume the OS may kill your service at any time so you'll have to pick up where you left off.
Hit up the reference on Services for more info.
- chris
Thanx for the heads up
I checked, my process is not crashing, (no stacktrace or any other errors in logcat)
I wil try to find out what to add to the manifest file
- to have the intents resend
- and how to get a higher dont kill me rank
Thanx
I redid my app doding the SDcard stuf in a service witch is reapplied/restarted if killed and start the service from the bootactivity.
It works fine

[Q] NullPointerException when trying to access MainActivity from different class

Hi!
I am trying to develop an android app with a google map v2, location service and some control buttons.
But I don't want to put all these things inside one MainActivity class. So I thought I could split all the code into some more classes. The MainActivity shall controll all the GUI things and react on map or location events...
Now I have the following problem. Inside my onCreate I instanziate the additional classes:
Code:
// Preferences as singleton
pref = Prefs.getInstance(this.getApplicationContext());
pref.loadSettings();
// Set up the location
loc = new Locations(pref);
loc.setCallback(this);
map = new MyMap(pref);
It seems to work fine. But inside the MyMap class every time I start the app a null pointer exception is thrown. When I am calling MyMap() the following code will be executed:
Code:
[...]
private Prefs pref;
private GoogleMap mMap;
[...]
public MyMap(Prefs prefs) {
pref = (Prefs) prefs;
if (mMap == null) {
FragmentManager fmanager = getSupportFragmentManager();
mMap = ((SupportMapFragment) fmanager.findFragmentById(R.id.map)).getMap();
[...]
}
The line with the findFragmentById is the one that causes the exception.
If I write
Code:
SupportMapFragment f = ((SupportMapFragment) fmanager.findFragmentById(R.id.map));
f is allways null. But how can I access the fragments and view elements defined within my MainActivity?
It works if I put the code inside my MainAcitivity.
Every class extends "android.support.v4.app.FragmentActivity"
I tried to save the application context within my Prefs() class, so that I can access it from everywhere.
But I don't know how to use it inside my additional classes.
How to share the "R" across all my classes?
Can someone help me please?
Thank you very much!!
Thorsten
Are you having trouble adding a Map to a Fragment? If so, then you may take a look at this tutorial. I haven't tried it myself since I couldn't install Google Play Services on my development device. If it helps, do write back, as I am definitely going to try it myself soon.

How to add list view items to an array list? or a work around to achieve the below?

In the below code, where the item’s position and title is getting saved in list_items works fine if list_items and items are ArrayList. For ex;
Code:
ArrayList.add(ArrayList.get(position));
But I am trying to use listview:
Code:
ArrayList.add(Listview.get(position));
The problem exists on line # 10
Code:
1. final Listadapter Adapter = new Listadapter(this,packageList1, packageManager);
2. items.setAdapter(Adapter);
3. items.setChoiceMode(apps.CHOICE_MODE_MULTIPLE_MODAL);

4. items.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
5. @Override
6. public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {

7. count = count +1;

8. mode.setTitle(count + "items selected");
9. //problem resides in the below line

10. [B]list_items.add(items.get(position));[/B]

11. }

In the above code, on selecting an item from listview I am trying to save it in an Arraylist i.e list_items which could be used in onActionItemClicked method for further action on that respective item.
Any ideas on how to solve or find a workaround to use a listview in the above situation?

Getting Place Details with HMS Site Kit

If we briefly talk about what HMS Site Kit is, you can provide users to explore the world faster with Site Kit. You can search for locations by keywords, find places which are close to the specified coordinate point, get detailed information about a place and get suggestions for places by keyword.
We can get detailed information about a place with Place Detail Search, another feature of Site Kit. The only condition for this, we need to know Site model’s id value that belongs to the place we want to search.
Before I explain the use of Place Detail Search, I would like to share with you a function that we can use this feature.
Code:
fun placeDetail(siteId: String){
val searchService = SearchServiceFactory.create(context,
URLEncoder.encode(
"Your-API-KEY",
"utf-8"))
var request = DetailSearchRequest()
request.siteId = siteId
request.language = Locale.getDefault().language // Getting system language
searchService.detailSearch(request, object: SearchResultListener<DetailSearchResponse>{
override fun onSearchError(searchStatus: SearchStatus?) {
Log.e("SITE_KIT","${searchStatus?.errorCode} - ${searchStatus?.errorMessage}")
}
override fun onSearchResult(detailSearchResponse: DetailSearchResponse?) {
var site = detailSearchResponse?.site
site?.let {
Log.i("SITE_KIT", "Name => ${it.name}," +
"Format address => ${it.formatAddress}, " +
"Coordinate => ${it.location.lat} - ${it.location.lng}, " +
"Phone => ${it.poi.phone}, " +
"Photo URLS => ${it.poi.photoUrls}, " +
"Rating => ${it.poi.rating}, " +
"Address Detail => ${it.address.thoroughfare}, ${it.address.subLocality}, " +
"${it.address.locality}, ${it.address.adminArea}, ${it.address.country}")
} ?: kotlin.run {
Log.e("SITE_KIT","Site Place couldn't find with the given site ID")
}
}
})
}
First, we need to create a SearchService object from the SearchServiceFactory class. For this, we can use the create() method of the SearchServiceFactory class. We need to declare two parameters in create() method.
The first of these parameters is context value. It is recommended that Context value should be in Activity type. Otherwise, when HMS Core(APK) needs to be updated, we can not receive any notification about it.
The second parameter is API Key value that we can access via AppGallery Connect. This value is generated automatically by AppGallery Connect when a new app is created. We need to encode API parameter as encodeURI.
After creating our SearchService object as I described above, we can create a DetailSearchRequest object. We will specify the necessary parameters on this object related to the place which we want want to get information.
After creating our DetailSearchRequest object, we can determine parameters for a place that we want to get information. Two parameters are specified here:
SiteId: There is a unique id value for each Site in Site Kit. This parameter is used to specify the id value of the place whose information is to be obtained.
Language: It is used to specify the language that search results have to be returned. If this parameter is not specified, language of the query field we have specified in the query field is accepted by default. In example code snippet in above, language of device has been added automatically in order to get a healthy result.
After entering the id value and language parameter of the place that we want to learn in detail, we can start learning the details. For this, we will use detailSearch() method of the SearchService object. This method takes two parameters.
For the first parameter, we must specify DetailSearchRequest object we have defined above.
For the second parameter, we have to implement SearchResultListener interface. Since this interface has a generic structure, we need to specify class belonging to the values to be returned. We can get the incoming values by specifying DetailSearchResponse object. Two methods should be override with this interface. onSearchError() method is executed if operation fails, and onSearchResult() method is executed if operations is successful. There is one value in DetailSearchResponse. This value is Site object that belongs to the id value. With the Site variable of DetailSearchResponse object, we can access information belong to place we have searched.
sujith.e said:
Hi,Why API key is required?
Click to expand...
Click to collapse
API key is a simple credential for accessing Huawei services. Your API key is creating automatically on the AppGallery Connect when you create an application, and then your app can use the key to call public APIs provided by Huawei.
When an app calls a public API provided by Huawei, we should give this information to API to help Huawei to identify our application.

Categories

Resources