This is my first time using Fragments and I'm rather new to Android. I'm using Fragments to manage a settings menu for my app.
I have a MainActivity with a FragmentContainerView, the XML is like so:
<androidx.fragment.app.FragmentContainerView
android:visibility="gone"
android:id="#+id/main_activity_fragment_container"
android:background="#color/white"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
In the MainActivity.java File I have a method assigned to a button to make the FragmentContainerView visible, like so:
private void showFragments(FragmentContainerView fragmentContainerView) {
fragmentContainerView.setVisibility(View.VISIBLE);
// There is more to this method, but I don't think it is necessary for this example
}
I'm able to navigate all around the settings menu: inflate fragments, replace fragments, update Shared Preferences, use Browser Intent, etc. - everything I need to do for a settings menu.
What I haven't been able to figure out is how to closeout the Settings Menu (close the FragmentContainerView in the MainActivity) after a selection has been made (and thus return to the game). I can create a "close" button in every fragment - but I can't figure out a method to close (setVisibility to GONE) the MainActivity's FragmentContainerView.
Once I'm in a Fragment - is it even possible to access the FragmentContainerView the fragment resides inside of? I've tried a number of ways to access it and set the visibility to GONE, but I just get a crash.
Inside a fragment:
FragmentContainerView mainActivityFragmentContainer = (FragmentContainerView) view.findViewById(R.id.main_activity_fragment_container);
public void closeFragment(FragmentContainerView mainActivityFragmentContainer) {
mainActivityFragmentContainer.setVisibility(View.GONE);
// This causes a crash, the error log states:
// NullPointerException: Attempt to invoke virtual method 'void androidx.fragment.app.FragmentContainerView.setVisibility(int)' on a null object reference
}
I know a workaround where I don't have the fragmentContainerView fill up the entire screen and leave space for an external close button - but this solution seems inefficient.Any advice would be helpful!
Yes you can do it,
1- Create a public function in your MainActivity that closes the fragment container:
public void closeFragment() {
fragmentContainerView.setVisibility(View.GONE);
}
2- Call that function from your fragment when you need it:
// getActivity() will return the activity linked to that fragment so this fragment should be linked MainActivity
MainActivity activity = (MainActivity) getActivity();
acitvity.closeFragment();
A week ago, I was successfully using ListView, adding an item to it every time a button is clicked. Then I found I needed to put something in a thread separate from the main UI thread, and somewhere along the way, something broke.
Now I'm seeing an error every time I start Android Studio, saying FileNotFoundException: Entry fileTemplates//code/Google Test Fixture SetUp Method.cc.ft not found in E:/Programs/Android Studio/lib/idea.jar I go to that very folder though, and I can see that the file exists. This is the closest I've come to figuring out how to fix it.
I've also tried a cold reboot of both my computer and my phone, reinstalling Android Studio, creating a brand new project, and File > Invalidate Caches and Restart, none of which were helpful.
The only other answers I can find say it's because of being a 64 bit version on a 32 bit system. I am certain that's not the case, unless I somehow downloaded 64 bit while specifically looking for 32 bit.
I have no idea whether it's a problem with Android Studio, Gradle, something to do with the phone I'm using as a testing platform, or what.
I'm using:
Windows 8.1 Pro (32-bit)
2x Pentium 3.2 GHz (x64)
Android Studio 2.3.3
minimum SDK of API 15: Android 4.0.3 IceCreamSandwich
Java v1.8.0_144 (according to "java -version" in a command prompt)
Java 8 updates 60 and 144 are in my list of installed programs, along with Java SE Development Kit 8 updates 60 and 144
Here's the code from the fresh project that I mentioned:
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<String> listItems;
ArrayAdapter<String> adapter;
ListView listview = (ListView) findViewById(R.id.listview);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listItems = new ArrayList<>();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
listview.setAdapter(adapter);
}
public void sendAnother(View view) {
adapter.add("button clicked");
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
tools:context="meh.myapplication.MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="Testing"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
<ListView
android:id="#+id/listview"
android:layout_width="0dp"
android:layout_height="431dp"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toTopOf="#+id/button"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
It turns out, all I was doing wrong was trying to initialize listview before onCreate(). Declaring it is fine, but initializing breaks it. I guess, despite being defined in the xml, View objects aren't instantiated until runtime?
I have a backup I had made from before anything broke, but it was also broken. Or, now that I'm messing with it again, partially broken. (button doesn't work, but I can output to the listview) I suppose I took this to mean something within Android Studio might have been broken. I think that's why I didn't notice the difference in where I tried to initialize listview.
I guess any rock will break if you hit it long enough with a hammer, eh?
I'm trying to display AdMob NativeExpressAds in my Android application.
Sample ads show up in the emulator and I thought everything seems fine.
However, on actual testing on real Android devices, ads refuse to show up - whether or not I set addTestDevice("...").
My code is:
public NativeExpressAdView getNativeExpressAdView(Activity activity) {
NativeExpressAdView adView = new NativeExpressAdView(activity);
adView.setAdListener(new TestAdListener(adView));
adView.setAdSize(new AdSize(adWidth, adHeight));
adView.setAdUnitId(adUnitID);
AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
//adRequestBuilder.addTestDevice("187AE74C3A6B5BA1B5E94A46EC9FD3F6");
adView.loadAd(adRequestBuilder.build());
return adView;
}
Note: the adWidth and adHeight is exactly the same as what is set in the AdMob AdUnit.
and:
...
#Override
public void onAdLoaded() {
super.onAdLoaded();
Log.i("I/Ads", "onAdLoaded");
}
Yes, onAdLoaded is indeed called.
I also tried this, but it didn't work. I also research many other materials, but none worked.
EDIT:
I debugged further and found this error:
09-04 13:53:46.204 2502-2502/com.swars.android W/Ads: Not enough space to show ad. Needs 360x100 dp, but only has 320x0 dp.
The size is the same size as set in AdMob AdUnit. So, it seems that I should make is smaller. However, there is a mystery about the error because it says the height is 0 (320x0 dp). Can anyone help to shed some lights on this?
Config your RelativeLayer, so :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
...
android:paddingLeft="0dp"
android:paddingRight="0dp"
...
>
AdView config to:
<com.google.ads.AdView
android:id="#+id/adMobadView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
...
/>
Source
I have written an application for Android that has an issue (crash) when it is launched immediately (with in 5 seconds or so) after the phone is rebooted. Due to one reason or another, the OnCreate method is called for a second time. I thought this may have been the problem, but after researching this, I found out the android system may recall onCreate after start up as it is still starting system services - such as getting the "MCM".
In my application in the MainActivity I have a statically bound fragment that is bound through XML. The fragment has code in it that checks that location permissions were granted:
if (ActivityCompat.checkSelfPermission(this.getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
The problem is, this.getContext() returns null! It definitely has something to do with the fact onCreate is being called more than once, because when the phone is not booting and onCreate is only called once the application works perfectly!
Here is the only reference I make to the fragment in my onCreate method in the mainActivity:
android.support.v4.app.Fragment fragMap = getSupportFragmentManager().findFragmentById(R.id.mv_1);
if (fragMap instanceof FragmentMap)
{
theMap = (FragmentMap) fragMap;
}
Here is the fragment bound through XML:
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="#+id/mv_1"
android:name="com.sunhillo.personneltrackerv002.FragmentMap"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="64dp"/>
Thank you very much for any help you can provide! I am still new to Android programming, and am attempting to learn the ins and outs!
If your ultimate aim is to access the location permissions, simply add these permissions in manifest file. And if you wish to perform this check via java, don't add this to individual fragments. Add this syntax only to the MainActivity java file that refers to the fragments. I hope this helps. :)
You should use launch mode Single Task or Single top which will avoid calling multiple onCreate and you should use getApplicationContext().
I have the following layout (virtually empty):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/set_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:contentDescription="content desc"
android:orientation="vertical" >
<TextView android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
</LinearLayout>
The Activity class contains the following:
public class TestActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
}
}
When I run this on my mobile device I get the following error:
SpannableStringBuilder
SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
I have tried this with and without the TextView and the error still remains, I must be doing something fundamentally wrong for such a basic layout to cause this.
Does anyone have any ideas on how I can get this to load without the error?
I have run into the same error entries in LogCat. In my case it's caused by the 3rd party keyboard I am using. When I change it back to Android keyboard, the error entry does not show up any more.
Because the error you're getting is not related to an EditText, then it's not related to your keyboard.
The errors you are getting are not a result of your code; you probably are testing on a Samsung device that has Samsung's TouchWiz.
I had the same errors, then I tested on a Nexus S (also by Samsung, but pure Android OS without TouchWiz) and I didn't get this error.
So, in your case, just ignore these errors while testing on a device! :)
Looking at your code, I'm not sure why you're getting that error, but I had this same error but with EditText fields.
Changing android:inputType="text" (or any of the other inputType text variations) to android:inputType="textNoSuggestions" (or android:inputType="textEmailAddress|textNoSuggestions", for example) fixed it for me.
You can also set this in Code with something like
mInputField.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
Looks like Android assumes by default that EditText fields will have suggestions. When they don't, it errors. Not 100% confident in that explanation, but the above mentioned changes fixed it for me.
http://developer.android.com/reference/android/text/Spanned.html#SPAN_EXCLUSIVE_EXCLUSIVE
Hope this helps!
On your android phone go to:
settings -> application manager -> all -> samsung keyboard and then click on "clear cache"
(delete all data collected by this application).
Try using the default Android keyboard it will disappear
Make clear you have pass a value in your MainAcitivity for the following methods onCreateOptionsMenu and onCreate
In some cases, the developer deletes the "return super.onCreateOptionsMenu(menu)" statement and changed to "return true".
This worked for me...on every device
<EditText
android:maxLines="1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="15sp"
android:layout_centerVertical="true"
android:textColor="#000"
android:id="#+id/input_search"
android:background="#null"
android:inputType="text"
android:hint="Enter Address, City or Zip Code"
android:imeOptions="actionSearch"
/>
In Java code:
mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
if(actionId == EditorInfo.IME_ACTION_SEARCH
|| actionId == EditorInfo.IME_ACTION_DONE
|| keyEvent.getAction() == KeyEvent.ACTION_DOWN
|| keyEvent.getAction() == KeyEvent.KEYCODE_ENTER){
//execute our method for searching
}
return false;
}
});
I had the same warning and found that removing an unused #id got rid of the warning. For me it was obvious as the #id was associated with a growing list of textViews linked to a database, so there was a warning for each entry.
Masood Moshref is right, this error occur because the option menu of Menu is not well prepared by lacking "return super.onCreateOptionsMenu(menu)" in onCreate() method.
To try to debug this error, first go to your android terminal / console and execute this command:
ps | grep THE_ERROR_PID_YOU_GET_(IT_IS_A_NUMBER)
then if the output comes out as your app... it is your app causing the error. Try to look for empty Strings that you pass into the layout.
I had this exact same problem and it was my fault as I was passing an empty String into my layout. After changing the "" to " " this error went away.
If you don't get your app from the console output, then it is something else causing it (probably, as others said, the android keyboard)
I have faced the same issue. I almost wasted almost couple of weeks to resolved this issue.
Finally I had on doubt on myself and tried to create another project by copy and paste some startup files like SplashScreen & LoginScreen.
But with the same code still i was getting SPAN_EXCLUSIVE_EXCLUSIVE.
Then i have removed the handler code from splash screen and tried again and Wow its working.
I am not getting SPAN_EXCLUSIVE_EXCLUSIVE issue in logcat.
I wondering, why it is? till the time did not get any other solution but by removing handler from splash screen it is working.
Try and update here if it is resolved or not.
Check if you have any element such as button or text view duplicated (copied twice) in the screen where this encounters. I did this unnoticed and had to face the same issue.
I ran into this problem too when I copied some text from the Internet. My solution is to trim the text/remove formatting before doing any further processing.
I had the same problem but with a listView.... i solved it because i was using a wrong R.id.listView that list View needed to have a value, in my case it was strings that i saved on listView2... so the right code was R.id.listView2
I had the same problem then i fixed it by following code!
text = (EditText)findViewById(R.id.TextVoiceeditText);
text.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
this error also occurs due to changed API URL. try hitting the URL you are using in postman and c if it's working properly.
rechecking the APIs solved my problem
try avoiding use of view in xml design.I too had the same probem but when I removed the view. its worked perfectly.
like example:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:inputType="number"
android:textColor="#fff" />
<view
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#f9d7db" />
also check and try changing by trial and error android:inputType="number" to android:inputType="text" or better not using it if not required .Sometimes keyboard stuck and gets error in some of the devices.
In my case, the EditText fields with inputType as text / textCapCharacters were casing this error. I noticed this in my logcat whenever I used backspace to completely remove the text typed in any of these fields.
The solution which worked for me was to change the inputType of those fields to textNoSuggestions as this was the most suited type and didn't give me any unwanted errors anymore.
in my case i click on recent apps shortcut on my cell phone and close all apps. This solution always work for me, because this error not related to code.
**DONT PUT SET TEXT IN TEXT WATCHER**etSearch.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable) {
visibleResultList = false
if (s.toString().length != 0) {
getSearchSuggetion(no_of_rec, 0, s.toString())
} else {
// etSearch.setText("")
}
Log.e("text_change","============"+s.toString())
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
}
})
To solve this problem just add android:usesCleartextTraffic="true" in your AndroidManifest.xml file which is at ..\app\src\main\AndroidManifest.xml just like bellow...