One code and deferent result in android2.2 vs android4.2 - java
In a big project i have below codes that run step is
first GalleryMeno runs and then GalleryActivityMain
GalleryMeno.java
public class GalleryMeno extends Activity{
private Integer[] mThumbIds = {
R.drawable.gallary_farhad1 ,
R.drawable.gallary_farhad2,
R.drawable.gallary_naser ,
R.drawable.gallary_mehdi ,
R.drawable.gallary_other ,
R.drawable.gallary_old ,
R.drawable.gallary_amir ,
R.drawable.gallary_bazikonan
};
private String[] name = {
"gallary_farhad1",
"gallary_farhad2",
"gallary_naser",
"gallary_mehdi",
"gallary_other",
"gallary_old",
"gallary_amir",
"gallary_bazikonan"
};
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery_meno_activity);
TextView titleName = (TextView) findViewById(R.id.title_name);
titleName.setText("گالری تصاویر");
//found width of Screen for Gridview
WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
int densityX = display.getWidth();
Button btnUpdate = (Button) findViewById(R.id.update);
btnUpdate.setVisibility(View.INVISIBLE);
Button backButton = (Button) findViewById(R.id.backward);
backButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-g
finish();
}
});
GridView grid = (GridView) findViewById(R.id.gridViewSms);
grid.setAdapter(new ImageAdapter(getApplicationContext(), densityX, mThumbIds));
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position ,
long id) {
Intent MainGallery = new Intent(GalleryMeno.this , GalleryActivityMain.class);
MainGallery.putExtra("position", position);
MainGallery.putExtra("title", name[position]);
startActivity(MainGallery);
}
});
}
}
ImageAdapter .java
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private int widthOfScrren;
public Integer[] mThumbIds;
public ImageAdapter(Context c,int ScrrenSize,Integer[] mThumbIds){
mContext = c;
widthOfScrren=ScrrenSize;
this.mThumbIds = mThumbIds;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
final int w;
if ( widthOfScrren == 0 )
w = 75;
else
w = widthOfScrren/3;
imageView.setLayoutParams(new GridView.LayoutParams(w,w));
return imageView;
}
}
GalleryActivityMain.java
public class GalleryActivityMain extends Activity {
public static Integer[] ImageGroup1 = {
R.drawable.farhad01,
R.drawable.farhad02,
R.drawable.farhad03,
R.drawable.farhad04,
R.drawable.farhad05,
R.drawable.farhad06,
R.drawable.farhad07,
R.drawable.farhad08,
R.drawable.farhad09,
R.drawable.farhad10,
R.drawable.farhad11,
R.drawable.farhad12,
R.drawable.farhad13,
R.drawable.farhad14,
R.drawable.farhad15,
R.drawable.farhad16
};
public static Integer[] ImageGroup2 = {
R.drawable.farhad17,
R.drawable.farhad18,
R.drawable.farhad19,
R.drawable.farhad20,
R.drawable.farhad21,
R.drawable.farhad22,
R.drawable.farhad23,
R.drawable.farhad24,
R.drawable.farhad25,
R.drawable.farhad26,
R.drawable.farhad27,
R.drawable.farhad28,
R.drawable.farhad29,
R.drawable.farhad30,
R.drawable.farhad31,
R.drawable.farhad32,
R.drawable.farhad33
};
public static Integer[] ImageGroup3 = {
R.drawable.naser01,
R.drawable.naser02,
R.drawable.naser03,
R.drawable.naser04,
R.drawable.naser05,
R.drawable.naser06,
R.drawable.naser07,
R.drawable.naser08,
R.drawable.naser09,
R.drawable.naser10,
R.drawable.naser11,
R.drawable.naser12,
R.drawable.naser13,
R.drawable.naser14,
R.drawable.naser15,
R.drawable.naser16,
R.drawable.naser17
};
public static Integer[] ImageGroup4 = {
R.drawable.mehdi01,
R.drawable.mehdi02,
R.drawable.mehdi03,
R.drawable.mehdi04,
R.drawable.mehdi05,
R.drawable.mehdi06,
R.drawable.mehdi07,
R.drawable.mehdi08,
R.drawable.mehdi09,
R.drawable.mehdi10,
R.drawable.mehdi11,
R.drawable.mehdi12,
R.drawable.mehdi13,
R.drawable.mehdi14,
R.drawable.mehdi15,
R.drawable.mehdi16,
R.drawable.mehdi17
};
public static Integer[] ImageGroup5 = {
R.drawable.other01,
R.drawable.other02,
R.drawable.other03,
R.drawable.other04,
R.drawable.other05,
R.drawable.other06,
R.drawable.other07,
R.drawable.other08,
R.drawable.other09,
R.drawable.other10,
R.drawable.other11,
R.drawable.other12,
R.drawable.other13,
R.drawable.other14,
R.drawable.other15,
R.drawable.other16,
};
public static Integer[] ImageGroup6 = {
R.drawable.old01,
R.drawable.old02,
R.drawable.old03,
R.drawable.old04,
R.drawable.old05,
R.drawable.old06,
R.drawable.old07,
R.drawable.old08,
R.drawable.old09,
R.drawable.old10,
R.drawable.old11,
R.drawable.old12,
R.drawable.old13,
R.drawable.old14,
R.drawable.old15,
R.drawable.old16,
R.drawable.old17,
R.drawable.old18,
R.drawable.old19
};
public static Integer[] ImageGroup7 = {
R.drawable.amir01,
R.drawable.amir02,
R.drawable.amir03,
R.drawable.amir04,
R.drawable.amir05,
R.drawable.amir06,
R.drawable.amir07,
R.drawable.amir08,
R.drawable.amir09,
R.drawable.amir10,
R.drawable.amir11,
R.drawable.amir12,
R.drawable.amir13,
R.drawable.amir14,
R.drawable.amir15
};
public static Integer[] ImageGroup8 = {
R.drawable.b1,
R.drawable.b2,
R.drawable.b3,
R.drawable.b4,
R.drawable.b5,
R.drawable.b6,
R.drawable.b7,
R.drawable.b8,
R.drawable.b9,
R.drawable.b10,
R.drawable.b11,
R.drawable.b12,
R.drawable.b13,
R.drawable.b14,
R.drawable.b15,
R.drawable.b16,
R.drawable.b17,
R.drawable.b18,
R.drawable.b19,
R.drawable.b20
};
public static Integer[] SelectedGroup;
private int Global_position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.galery_activity);
TextView titleName = (TextView) findViewById(R.id.title_name);
Intent current = getIntent();
Global_position=current.getExtras().getInt("position");
titleName.setText(current.getExtras().getString("title"));
Button btnUpdate = (Button) findViewById(R.id.update);
btnUpdate.setVisibility(View.INVISIBLE);
Button backButton = (Button) findViewById(R.id.backward);
backButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
GridView grid=(GridView) findViewById(R.id.grid_view_gallery);
//connect xml_gridView to Class ImageAdapter
//when we sent 0 to screensize we want to auto generating image independent device
grid.setAdapter(new ImageAdapter(getApplicationContext(), 0, getCorrectItem(Global_position)));
//set item on click listener
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
Intent FullImage = new Intent(getApplicationContext(), GalleryFullImageView.class);
/******
* by below syntax we sent some information by a id
* to new intent and on new intent we extract it and use it
******/
FullImage.putExtra("position", position);
startActivity(FullImage);
}
});
}
private Integer[] getCorrectItem(int position)
{
switch (position) {
case 0:
SelectedGroup = ImageGroup1;
return ImageGroup1;
case 1:
SelectedGroup = ImageGroup2;
return ImageGroup2;
case 2:
SelectedGroup = ImageGroup3;
return ImageGroup3;
case 3:
SelectedGroup = ImageGroup4;
return ImageGroup4;
case 4:
SelectedGroup = ImageGroup5;
return ImageGroup5;
case 5:
SelectedGroup = ImageGroup6;
return ImageGroup6;
case 6:
SelectedGroup = ImageGroup7;
return ImageGroup7;
case 7:
SelectedGroup = ImageGroup8;
return ImageGroup8;
default:
SelectedGroup = ImageGroup7;
return ImageGroup7;
}
}
}
Mymanifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.esteghlaliha"
android:versionCode="8"
android:installLocation="preferExternal"
android:versionName="1.9" >
<uses-sdk
android:minSdkVersion="6"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/esteghlal_big"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.perspolisiha.Esteghlal"
android:theme="#android:style/Theme.NoTitleBar"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.perspolisiha.Main"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar">
</activity>
<activity android:name="com.example.rank.Resultshow"
android:configChanges="orientation|screenSize"
android:screenOrientation="landscape"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.rank.RankLayout"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.perspolisiha.SmsshowActivity"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.perspolisiha.GalleryActivityMain"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.perspolisiha.GalleryFullImageView"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.perspolisiha.GalleryMeno"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.tv.TVLayout"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.tv.TVResultshow"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.bio.BioMainActivity"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.bio.BioResultShow"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.history.HistoryActivity"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.news.NewsActivityMain"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.news.ShowDetailActivity"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.news.setting"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
</application>
</manifest>
Case1:When i ran above code in android 2.2 i seen a menu of image that made from gridview
and when i click on every item all image about this item shown.(in this case all result is OK)
Case2:But when I ran same code in android 4.2
by click on item (for view all image about it) my program become exit without any forceClose
for ex: when i click on image gallary_amir i expect that a gridview of image from ImageGroup7
Why?How i can fix Case2?
You said that you don't receive any force close, thereby no LogCat. What I would say is since you are checking on Android 4.2 which is API level 17, try to make your android:targetSdkVersion="" as 17 instead of 16 and see if you receiver any errors in LogCat. If you read about android:targetSdkVersion, it says:
If the API level of the platform is higher than the version declared by your app's targetSdkVersion, the system may enable compatibility behaviors to ensure that your app continues to work the way you expect.
Android tries to enable those compatibility behaviors when you test on higher version that targeted. There might be some function call or some other thing which got changed in API version 17 and is behaving in appropriately.
Other point is that try to see in your code that which thing have been depreciated for API 17 and have been used in your code. Using upto date stuff is always recommended.
Hope this helps in some way.
Related
How do you use a Google MapView inside of a Fragment?
Desired Behavior In case it affects any answers or suggestions, what I would like to ultimately see in this app is a navigation UI where one of the Fragment is a map. I used a template to start with a navigation UI, which gave me several Fragments, one for each tab. Currently, I'm trying to use the Google API to put a MapView inside of one of those Fragments. Current Behavior Generally, this isn't working (obviously). I have everything up and running, but when I pull up the tab with the map in it, the map is blank. Nothing crashes, and no errors are output: I/Google Maps Android API: Google Play services client version: 12451000 I/Google Maps Android API: Google Play services package version: 201516040 D/NetworkSecurityConfig: No Network Security Config specified, using platform default I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:4 Selected remote version of com.google.android.gms.googlecertificates, version >= 4 Other Details/Troubleshooting I know that my API key works because I have another app in which the maps work as expected. I doubt I need a second API key, but I looked anyway and since it wasn't overly obvious how to create a second API key, I think that hunch is correct. Most of the code I'm using was copied from that working example; the primary difference is that other example uses a SupportMapFragment and it has a class MapsActivity extends FragmentActivity. Here, since I don't really want to deal with nesting fragments, I'm trying to use a MapView inside that fragment. What bits of my code that weren't copied largely came from online sources. None of what I've tried has produced better results. MapView inside fragment is answering a different problem Creating google maps v2 in a fragment using Navigation Drawer contains only things I already have android MapView in Fragment gave me the idea to use MapsInitializer.initialize(this.getActivity()); but that didn't help Mapview in separate fragment android has nothing new how do i solve integrating google map in fragment in android uses a Fragment not a MapView I also know that onMapReady is being called. Inside of that, I move the camera and that subsequently calls onCameraMoveStarted. However, it does not enter onCameraMove or onCameraIdle. Code This is the code as it is, which uses some of the ideas from the above links. I tried to cut out anything that's unrelated (other fragments, etc) AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.retailtherapy"> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="#mipmap/ic_launcher" android:label="#string/app_name" android:roundIcon="#mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="#style/AppTheme"> <meta-data android:name="com.google.android.geo.API_KEY" android:value="#string/google_maps_key" /> <activity android:name=".MainActivity" android:label="#string/app_name" android:windowSoftInputMode="stateVisible|adjustResize" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-feature android:glEsVersion="0x00020000" android:required="true"/> </manifest> activity_main.xml <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:id="#+id/container" android:layout_width="match_parent" android:layout_height="match_parent"> <com.google.android.material.bottomnavigation.BottomNavigationView android:id="#+id/nav_view" app:menu="#menu/bottom_nav_menu" /> <fragment android:id="#+id/nav_host_fragment" android:name="androidx.navigation.fragment.NavHostFragment" app:defaultNavHost="true" app:navGraph="#navigation/mobile_navigation" tools:context=".MainActivity" /> </androidx.constraintlayout.widget.ConstraintLayout> mobile_navigation.xml <navigation 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/mobile_navigation" app:startDestination="#+id/navigation_map"> <fragment android:id="#+id/navigation_map" android:name="com.example.retailtherapy.ui.map.MapFragment" android:label="Map" tools:layout="#layout/fragment_map" /> </navigation> fragment_map.xml <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:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ui.map.MapFragment" > <com.google.android.gms.maps.MapView android:id="#+id/googleMap" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout> MapFragment.java public class MapFragment extends Fragment implements OnMapReadyCallback, LocationListener { /************************************************************************* * * M E M B E R S * */ // Location manager for getting current location private LocationManager mLocationManager = null; // The map object for reference for ease of adding points and such private GoogleMap mGoogleMap = null; private MapView mMapView = null; // The camera position tells us where the view is on the map private CameraPosition mCameraPosition = Constants.GetDefaultCameraPosition(); // Current latitude and longitude of user private LatLng mCurrentLatLong = new LatLng(0.0, 0.0); // These are flags that allow us to selectively not move the camera and // instead wait for idle so the movement isn't jerky private boolean mCameraMoving = false; private boolean mPendingUpdate = false; /************************************************************************* * * F R A G M E N T * */ public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View root = inflater.inflate(R.layout.fragment_map, container, false); // The google map... MapsInitializer.initialize(getActivity()); mMapView = (MapView) root.findViewById(R.id.googleMap); mMapView.onCreate(savedInstanceState); mMapView.getMapAsync(this); // The required permissions... final String[] REQUIRED_PERMISSIONS = { Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET, }; requestPermissions(REQUIRED_PERMISSIONS, 0); return root; } #Override public void onStart() throws SecurityException { super.onStart(); // Location manager for getting info current location mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this); } #Override public void onResume() { super.onResume(); mMapView.onResume(); } #Override public void onStop() { super.onStop(); } #Override public void onDestroyView() { super.onDestroyView(); mMapView.onDestroy(); } #Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mMapView.onSaveInstanceState(outState); } #Override public void onLowMemory() { super.onLowMemory(); mMapView.onLowMemory(); } /************************************************************************* * * G O O G L E M A P S * */ #Override public void onMapReady(GoogleMap googleMap) { mGoogleMap = googleMap; // Assuming if here that we have permissions okay. Dangerous sure // but I'm lazy... mGoogleMap.setMyLocationEnabled(true); // Store the location of the camera for UI purposes so we can go // back to where we were mGoogleMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() { #Override public void onCameraMove() { mCameraPosition = mGoogleMap.getCameraPosition(); } }); mGoogleMap.setOnCameraMoveStartedListener(new GoogleMap.OnCameraMoveStartedListener() { #Override public void onCameraMoveStarted(int i) { mCameraMoving = true; } }); mGoogleMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() { #Override public void onCameraIdle() { mCameraMoving = false; if (mPendingUpdate) { centerCameraOnLocation(false); } } }); // Start with user centered in view centerCameraOnLocation(true); } /************************************************************************* * * L O C A T I O N * */ #Override public void onLocationChanged(Location location) { // Store the current location so if we start auto-center but aren't // already, we know where to pan to LatLng newLatLng = new LatLng(location.getLatitude(), location.getLongitude()); if (!newLatLng.equals(mCurrentLatLong)) { mCurrentLatLong = new LatLng(location.getLatitude(), location.getLongitude()); centerCameraOnLocation(false); } } #Override public void onStatusChanged(String provider, int status, Bundle extras) {} #Override public void onProviderDisabled(String provider) {} #Override public void onProviderEnabled(String provider) {} /************************************************************************* * * M A P C A M E R A * */ /* * Updates the camera position based on current state. If the camera is * already moving, then wait. */ private void centerCameraOnLocation(boolean animate) { if (mGoogleMap == null) { return; } if (mCameraMoving) { mPendingUpdate = true; return; } // Get the CameraPosition to update to based on whether we are auto // centering or not. if (mCameraPosition == null) { mCameraPosition = Constants.GetDefaultCameraPosition(); } // If this is the same as it was before, then don't reset it if (mCameraPosition.equals(mGoogleMap.getCameraPosition())) { return; } // Make the update so we can move the camera CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(mCameraPosition); // Move the camera with or without animation. The time we don't want // animation is when we're setting the position initially if (animate) { mGoogleMap.animateCamera(cameraUpdate); } else { mGoogleMap.moveCamera(cameraUpdate); } mPendingUpdate = false; } }
FINALLY I found the answer in a comment at https://stackoverflow.com/a/51464293/3038157. Basically, it seems there was something stale. Without changing any code, I uninstalled the app, cleaned the build, rebuilt, and voila it worked.
You must forward all the life cycle methods from the Activity or Fragment containing this view to the corresponding ones in this class. View this official guide or example code // *** IMPORTANT *** // MapView requires that the Bundle you pass contain _ONLY_ MapView SDK // objects or sub-Bundles.
Android SearchView.OnQueryTextListener() Unexpectedly Launching an Intent
I have implemented a Searchview into my application, and have run into a weird problem. Basically, the user is able to enter a string to be searched and it is submitted properly. However, my application will filter the ListView based on the search query, and then an Intent will be launched resulting in the activity starting again and returning to it's original state where it is displaying all the results. Here is the related code. #Override public boolean onCreateOptionsMenu(Menu menu) { ... searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { #Override public boolean onQueryTextSubmit(String query) { updateEntriesView(dbHelper.queryByName(query)); Toast.makeText(getApplicationContext(), "Searching for " + query, Toast.LENGTH_LONG).show(); return true; } #Override public boolean onQueryTextChange(String newText) { return false; } }); } private void updateEntriesView(ArrayList<Entry> response) { mListView = (ListView) findViewById(R.id.listview_entries); if (adapter == null) { adapter = new EntryListAdapter(EntriesActivity.this, R.layout.row_entry_layout, response); mListView.setAdapter(adapter); } else { adapter.clear(); adapter.addAll(response); adapter.notifyDataSetChanged(); } adapter.setNotifyOnChange(true); } I can not figure out to change this behavior and I can not find any documentation regarding it's implementation online. Is there a way I can override this feature and prevent it from launching an intent and restarting the activity to it's original unfiltered state? EDIT: I was able to solve this issue myself. For anyone who may be having the same problem here was my solution. So I had an intent-filter in my AndroidManifest.xml under the activity that would launch an intent upon a search action. This is what was causing it to launch an intent and start a new instance of my activity. My solution to this was to convert this activity into a single top activity and add code to handle the intent. By making the activity single top, it allows the activity to handle incoming intents without starting up a new instance of the intent. For a more detailed description on the difference between a normal and single top activity, this is a good article on the subject https://www.mobomo.com/2011/06/android-understanding-activity-launchmode/ Now, because my activity is single top, I can override the onNewIntent() method and add my code for handling this intent without having it launch a new instance. The relevant code for solving my problem is below. AndroidManifest.xml <activity android:name=".EntriesActivity" android:launchMode="singleTop"> <intent-filter> <action android:name="android.intent.action.SEARCH" /> </intent-filter> <meta-data android:name="android.app.searchable" android:resource="#xml/searchable"></meta-data> </activity> EntriesActivity.java public class EntriesActivity extends AppCompatActivity { ... #Override public boolean onCreateOptionsMenu(Menu menu) { ... searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { #Override public boolean onQueryTextSubmit(String query) { updateEntriesView(dbHelper.queryByName(query)); Toast.makeText(getApplicationContext(), "Searching for " + query, Toast.LENGTH_LONG).show(); return true; } #Override public boolean onQueryTextChange(String newText) { return false; } }); } #Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); handleIntent(intent); } private void handleIntent(Intent intent) { if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); updateEntriesView(dbHelper.queryEntriesByName(query)); } } private void updateEntriesView(ArrayList<Entry> response) { if (adapter == null) { adapter = new EntryListAdapter(EntriesActivity.this, R.layout.row_entry_layout, response); mEntriesList.setAdapter(adapter); } else { adapter.clear(); adapter.addAll(response); adapter.notifyDataSetChanged(); } adapter.setNotifyOnChange(true); } } I hope this helps.
You need to clear focus of the text view using searchView.clearFocus(); Refer This Answer: https://stackoverflow.com/a/15127252/7710739
I know this is old but if your searching and resulting in the same Activity try removing the <intent-filter> <action android:name="android.intent.action.SEARCH" /> </intent-filter> It should not try to launch a new activity then i don't beleive.
Cordova Plugin Stop/Restart Activity
I have a Cordova plugin which uses the https://github.com/googlesamples/android-Camera2Video example. I would like to disable the back button while in Camera. To do this, I believe Fragments can't accept back button events, so have added an Activity to the plugin. I can successfully run the plugin, camera and activity, disabled the back button. However when I close the plugin it errors with: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState To get around this I have used commitAllowingStateLoss instead of commit however when I open the plugin the second time, it errors with: java.lang.NullPointerException: Attempt to invoke interface method 'android.app.Activity org.apache.cordova.CordovaInterface.getActivity()' on a null object reference I presume I'm not stopping the activity correctly, and allowing the state to be lost, which causes a second error. How do I get around this? I've tried this method but no luck: PhoneGap Android Plugin - close the plugin Activity I've put my code in a branch here: https://github.com/kmturley/cordova-plugin-media-custom/tree/feature/back-button Add a summary of the changes: plugin.xml <config-file target="AndroidManifest.xml" parent="/manifest/application"> <activity android:name="com.example.android.camera2video.MediaCustomActivity" android:label="#string/activity_name" android:theme="#style/Theme.Transparent"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </config-file> <source-file src="src/android/MediaCustom.java" target-dir="src/com/example/android/camera2video" /> <source-file src="src/android/MediaCustomActivity.java" target-dir="src/com/example/android/camera2video" /> <source-file src="src/android/Camera2VideoFragment.java" target-dir="src/com/example/android/camera2video" /> MediaCustom.java public void show() { if (cameraFragment != null) { return; } cameraFragment = Camera2VideoFragment.newInstance(cordova, callbackContext); cordova.getActivity().runOnUiThread(new Runnable() { #Override public void run() { cordova.getActivity().setContentView(resources.getIdentifier("activity_camera", "layout", packageName)); FragmentManager fragmentManager = cordova.getActivity().getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(resources.getIdentifier("container", "id", packageName), cameraFragment); fragmentTransaction.commit(); MediaCustomActivity.start(cordova.getActivity()); } }); } public void hide() { if (cameraFragment == null) { return; } cordova.getActivity().runOnUiThread(new Runnable() { #Override public void run() { MediaCustomActivity.stop(cordova.getActivity()); cordova.getActivity().setContentView(getView()); FragmentManager fragmentManager = cordova.getActivity().getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.remove(cameraFragment); fragmentTransaction.commitAllowingStateLoss(); // commit(); cameraFragment = null; } }); } MediaCustomActivity.java public static void start(Activity activity) { Intent intent = new Intent(activity, MediaCustomActivity.class); activity.startActivity(intent); } public static void stop(Activity activity) { // what can we do here? } #Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.init(); Window window = this.getWindow(); window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE); } #Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { return false; } return super.onKeyDown(keyCode, event); }
Android UnityPlayerActivity Action Bar
I am building an Android application which includes a Unity 3d interactive experience. I have imported the Unity project into Android Studio but when launched the activity is fullscreen and does not show the Android action bar. How can I do this? Integration Steps Create new Unity project. Export "Google Android Project" from Unity. Import project into Android Studio. Attempted Solutions Changing the theme in the manifest. Setting the theme in the UnityPlayerActivity Java class. Overriding the Unity Android Manifest by placing a manifest with an updated theme in the Unity directory /Assets/Plugins/Android. Changing UnityPlayerActivity to extend AppCompatActivity. This will show the action bar but there is a white gap between it and the status bar. Setting "Screen.fullScreen = false;" in Unity SceneManager. This removes the immersive mode so that the Android status bar is visible. Turning off "Status Bar Hidden" in player settings. Appears to have no effect. Wrapping the UnityPlayer in a FrameLayout. This allows me to resize the the Unity as a view. AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.company.unity.test" android:installLocation="preferExternal" android:versionCode="1" android:versionName="1.0"> <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:smallScreens="true" android:xlargeScreens="true" /> <application android:banner="#drawable/app_banner" android:debuggable="false" android:icon="#drawable/app_icon" android:isGame="true" android:label="#string/app_name" android:theme="#android:style/Theme.NoTitleBar.Fullscreen"> <activity android:name="com.company.unity.test.UnityPlayerActivity" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale" android:label="#string/app_name" android:launchMode="singleTask" android:screenOrientation="fullSensor"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LEANBACK_LAUNCHER" /> </intent-filter> <meta-data android:name="unityplayer.UnityActivity" android:value="true" /> </activity> </application> <uses-sdk android:minSdkVersion="9" android:targetSdkVersion="23" /> <uses-feature android:glEsVersion="0x00020000" /> <uses-feature android:name="android.hardware.sensor.accelerometer" android:required="false" /> <uses-feature android:name="android.hardware.touchscreen" android:required="false" /> <uses-feature android:name="android.hardware.touchscreen.multitouch" android:required="false" /> <uses-feature android:name="android.hardware.touchscreen.multitouch.distinct" android:required="false" /> </manifest> UnityPlayerActivity.java package com.company.unity.test; import android.app.Activity; import android.content.res.Configuration; import android.graphics.PixelFormat; import android.os.Bundle; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.Window; import com.unity3d.player.UnityPlayer; public class UnityPlayerActivity extends Activity { protected UnityPlayer mUnityPlayer; // don't change the name of this variable; referenced from native code // Setup activity layout #Override protected void onCreate (Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); getWindow().setFormat(PixelFormat.RGBX_8888); // <--- This makes xperia play happy mUnityPlayer = new UnityPlayer(this); setContentView(mUnityPlayer); mUnityPlayer.requestFocus(); } // Quit Unity #Override protected void onDestroy () { mUnityPlayer.quit(); super.onDestroy(); } // Pause Unity #Override protected void onPause() { super.onPause(); mUnityPlayer.pause(); } // Resume Unity #Override protected void onResume() { super.onResume(); mUnityPlayer.resume(); } // This ensures the layout will be correct. #Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mUnityPlayer.configurationChanged(newConfig); } // Notify Unity of the focus change. #Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mUnityPlayer.windowFocusChanged(hasFocus); } // For some reason the multiple keyevent type is not supported by the ndk. // Force event injection by overriding dispatchKeyEvent(). #Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_MULTIPLE) return mUnityPlayer.injectEvent(event); return super.dispatchKeyEvent(event); } // Pass any events not handled by (unfocused) views straight to UnityPlayer #Override public boolean onKeyUp(int keyCode, KeyEvent event) { return mUnityPlayer.injectEvent(event); } #Override public boolean onKeyDown(int keyCode, KeyEvent event) { return mUnityPlayer.injectEvent(event); } #Override public boolean onTouchEvent(MotionEvent event) { return mUnityPlayer.injectEvent(event); } /*API12*/ public boolean onGenericMotionEvent(MotionEvent event) { return mUnityPlayer.injectEvent(event); } }
for Unity version 5.5 best way to avoid Immersive Mode in Android is to pass in the constructor not an Activity but to cast of the ApplicationContext to the Wrapper Context. mUnityPlayer = new UnityPlayer((ContextWrapper) getApplicationContext()); That works because in the obfuscated UnityPlayer.class (in unity-classes.jar) there is a check of instance. private void h() { if(this.h instanceof Activity) { ((Activity)this.h).getWindow().setFlags(1024, 1024); } } So if it's not an Activity the UnityPlayer.class doesn't set the flag.
I think I've found solution. Change that line: mUnityPlayer = new UnityPlayer(this); so it creates your own UnityPlayer subclass, which overrides setFullscreen method (little bit hacky): public class UnityPlayerWrapper extends UnityPlayer { public UnityPlayerWrapper(ContextWrapper contextWrapper) { super(contextWrapper); } #Override protected void setFullscreen(boolean b) { super.setFullscreen(false); } } In addition, please remove that line: requestWindowFeature(Window.FEATURE_NO_TITLE);
Piotr answer is working for older version and Lorenzo DM's answer also valid but mUnityPlayer = new UnityPlayer((ContextWrapper) getApplicationContext()); not working in some devices. So Finally I've modify UnityPlayerActivity here is new solution public class UnityPlayerActivity extends AppCompatActivity { protected UnityPlayer mUnityPlayer; // don't change the name of this variable; referenced from native code ActionBar actionBar; private Toolbar toolbar; private FrameLayout unityContainer; // Setup activity layout #Override protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); mUnityPlayer = new UnityPlayer(this); setContentView(R.layout.activity_unity_player); mappingWidgets(); init(); } void mappingWidgets(){ toolbar = (Toolbar) findViewById(R.id.toolbar); unityContainer = (FrameLayout) findViewById(R.id.unity_container); FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT); unityContainer.addView(mUnityPlayer.getView(), 0, layoutParams); mUnityPlayer.requestFocus(); } void init(){ setSupportActionBar(toolbar); actionBar = getSupportActionBar(); if (actionBar != null) actionBar.setDisplayHomeAsUpEnabled(true); toolbar.setNavigationOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { finish(); onDestroy(); } }); setTitle(getString(R.string.app_name)); } #Override protected void onNewIntent(Intent intent) { setIntent(intent); } // Quit Unity #Override protected void onDestroy () { mUnityPlayer.quit(); super.onDestroy(); } // Pause Unity #Override protected void onPause() { super.onPause(); mUnityPlayer.pause(); } // Resume Unity #Override protected void onResume() { super.onResume(); mUnityPlayer.resume(); } // Low Memory Unity #Override public void onLowMemory() { super.onLowMemory(); mUnityPlayer.lowMemory(); } // Trim Memory Unity #Override public void onTrimMemory(int level) { super.onTrimMemory(level); if (level == TRIM_MEMORY_RUNNING_CRITICAL) { mUnityPlayer.lowMemory(); } } // This ensures the layout will be correct. #Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mUnityPlayer.configurationChanged(newConfig); } // Notify Unity of the focus change. #Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mUnityPlayer.windowFocusChanged(hasFocus); } // For some reason the multiple keyevent type is not supported by the ndk. // Force event injection by overriding dispatchKeyEvent(). #Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_MULTIPLE) return mUnityPlayer.injectEvent(event); return super.dispatchKeyEvent(event); } // Pass any events not handled by (unfocused) views straight to UnityPlayer //#Override public boolean onKeyUp(int keyCode, KeyEvent event) { return mUnityPlayer.injectEvent(event); } // Pass any events not handled by (unfocused) views straight to UnityPlayer #Override public boolean onKeyUp(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { finish(); onDestroy(); return true; } return mUnityPlayer.injectEvent(event); } #Override public boolean onKeyDown(int keyCode, KeyEvent event) { return mUnityPlayer.injectEvent(event); } #Override public boolean onTouchEvent(MotionEvent event) { return mUnityPlayer.injectEvent(event); } /*API12*/ public boolean onGenericMotionEvent(MotionEvent event) { return mUnityPlayer.injectEvent(event); } }
Android: onTouchEvent start new activity
I have been searching for a while now but can't find a working solution for my android code. Well at least one I am able to implement. I have an activity (StartActivity) with a few animations. Then I have an onTouchEvent. This works fine to prompt a few more animations however after this I want to open a new Activity. Here is my code: public class StartActivity extends Activity { #Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.start); RunAnimations(R.anim.translate1, R.anim.translate2); } public void RunAnimations(int t1, int t2) { Animation a = AnimationUtils.loadAnimation(this, t1); a.reset(); Animation b = AnimationUtils.loadAnimation(this, t2); b.reset(); ImageView drop = (ImageView) findViewById(R.id.drop); ImageView iflush = (ImageView) findViewById(R.id.iflush); drop.clearAnimation(); iflush.clearAnimation(); drop.startAnimation(a); iflush.startAnimation(b); } #Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { RunAnimations(R.anim.translate3, R.anim.translate4); } return true; } } In the onTouchEvent, after calling RunAnimations, I want to start a new activity (TipActivity). That is all.
Add another activity to you AndroidManifest file like so: <activity android:label="YourActivity" android:name=".YourActivity" > <intent-filter > <action android:name="net.learn2develop.YourActivity" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> And then you could do something like (after calling RunAnimations()) : startActivity(new Intent("net.learn2develop.YourActivity")); Hope that helps.
Use that: Intent intent=new Intent(context, TipActivity.class); startActivity(intent); overridePendingTransition(R.anim.translate3, R.anim.translate4); ^-^