Hi so I have been going at this for days and I keep getting a crash everytime I try to move into my list view activity. I have rewritten the list view activity twice here is the activity code:
protected List<ParseObject> exercise_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exersise_display);
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Exercises");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if(e==null){
//success
exercise_name = list;
Excercise_Adapter adapter = new Excercise_Adapter(getListView().getContext(), exercise_name);
setListAdapter(adapter);
}
else {
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_exersise__display, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
here is the Exercise Adapter class
protected Context mContext;
protected List mExercise;
public Excercise_Adapter (Context context, List exercise){
super(context, R.layout.da_excerisises, exercise);
mContext = context;
mExercise = exercise;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
convertView = LayoutInflater.from(mContext).inflate(R.layout.da_excerisises, null);
holder = new ViewHolder();
//holder.exerciseImage = (ImageView)convertView.findViewById(R.id.Exersise_image);
holder.exerciseName = (TextView) convertView.findViewById(R.id.Exersise_name_menu);
convertView.setTag(holder);
}
else{
holder = (ViewHolder)convertView.getTag();
}
ParseObject exercise_object = mExercise.get(position);
String title = exercise_object.getString("exercise_name");
holder.exerciseName.setText(title);
return convertView;
}
public static class ViewHolder{
//ImageView exerciseImage;
TextView exerciseName;
}
and here is the calling code:
protected Button fitcalcmain;
protected Button excersise;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Parse.initialize(this, "BEFmOu6ru7ulUKCaFaNP8JdGU73RBc4wFfvOjfWp", "dV460EGCxMwhzvRhHQDne2zlYoeOQu2aDypfuTTW");
fitcalcmain = (Button)findViewById(R.id.FitnessCalcMain);
excersise = (Button)findViewById(R.id.ExersisesMain);
fitcalcmain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent gomeasure = new Intent(MainActivity.this, fitcalc.class);
startActivity(gomeasure);
}
});
excersise.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent goexcercises = new Intent(MainActivity.this, Exersise_Display.class);
startActivity(goexcercises);
}
});
}
here is the log (sorry it doesn't let me paste it into here because of "bad formatting":google doc with logcat
XML file of activity:
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/list"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true" />
here is the manifest
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="Workout Buddy"
android:theme="#style/AppTheme" >
<activity
android:name=".LoginActivity"
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=".MainActivity"
android:label="#string/Mainmenu" >
</activity>
<activity
android:name=".RegisterActivity"
android:label="#string/app_name" >
</activity>
<activity
android:name=".fitcalc"
android:label="#string/title_activity_fitcalc" >
</activity>
<activity
android:name=".Exersise_Display"
android:label="#string/title_activity_exersise__display" >
</activity>
<activity
android:name=".Types_Activity"
android:label="#string/title_activity_types_" >
</activity>
</application>
You should return convertView in your adapter getView instead of calling super. Plus if this didnt help you please post the code to start your activity.
edit
Please add the two of your activities into the manifest inside of application tag ex:
<activity android:name="myActivity">
<activity android:name="myActivity"Two>
Related
I am trying to create a recycle view list of NBA teams and when each team is clicked it will display a recycler view list of the NBA players in that particular team. To do this, I have constructed my main activity, which will launch the "NBA_Adapter" in the OnCreate method as shown below:
package com.example.nba;
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
state state = new state();
private NBA_Adapter adapter;
private RecyclerView recyclerView;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(this);
return true;
}
#Override
public void onCreate(Bundle savedInstanceState) {//originally 'protected'
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
adapter = new NBA_Adapter(getApplicationContext());
recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL, false));
}
}
NBA_Adapter:
package com.example.nba;
public class NBA_Adapter extends RecyclerView.Adapter<NBA_Adapter.NBAViewHolder> implements Filterable {
public static class NBAViewHolder extends RecyclerView.ViewHolder { //constructer for recyclerview adapter
public LinearLayout containerView;
public TextView textView;
NBAViewHolder(View view) {
super(view);
containerView = view.findViewById(R.id.nba_row);
textView = view.findViewById(R.id.nba_row_text_view);
containerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TEAMS current = (TEAMS) containerView.getTag();
Intent intent = new Intent(v.getContext(), SecondMain.class);
intent.putExtra("id", current.getId());
v.getContext().startActivity(intent);
}
});
}
}
}
Second Main:
public class SecondMain extends AppCompatActivity implements SearchView.OnQueryTextListener {
private int team_id;
private Player_Adapter rapter;
private RecyclerView mrecyclerView;
private RecyclerView.LayoutManager layoutManager;
#Override
public void onCreate(Bundle savedInstanceState) {//originally 'protected'
Log.v("cs100", "I exist!");
team_id = getIntent().getIntExtra("id",0);
Log.v("cs100", "" + team_id);
super.onCreate(savedInstanceState);
setContentView(R.layout.second_main);
mrecyclerView = findViewById(R.id.mrecycler_view);
rapter = new Player_Adapter(getApplicationContext());
mrecyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
state.setstate(false);
mrecyclerView.setAdapter(rapter);
}
}
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.nba">
<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">
<activity android:name=".SecondMain">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Now I am able to launch the "SecondMain" class as evident of a Log.v statement printing(Meaning at this point the teams but not the players in the teams are displaying). Since "MainActivity" is almost identical to "SecondMain" I assumed that similar to how "MainActivity" launches "NBA_Adapter" so will "SecondMain" launch "Player_Adapter". Player_Adapter is almost identical to "NBA_Adapter" but it is not launching at all. This is why I suspect that the problem is how I described "SecondMain" in the Android Manifest. I only included the relevant parts for each class. Any tips or links on this issue is appreciated, thanks!
EDIT: Included Player_Adapter class below:
public class Player_Adapter extends RecyclerView.Adapter<Player_Adapter.PlayerViewHolder> implements Filterable {
private int team_id;
public class myclass extends AppCompatActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
team_id = getIntent().getIntExtra("id",0);
recyclerView.setAdapter(adapter);
Log.v("Player",""+ team_id); //Not displaying statement which indicates that "Player_Adapter" is not being launched
}
}
public static class PlayerViewHolder extends RecyclerView.ViewHolder {
public LinearLayout containerView;
public TextView textView;
PlayerViewHolder(View view) {
super(view);
containerView = view.findViewById(R.id.Player_List_row);
textView = view.findViewById(R.id.Player_List_row_text_view);
containerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Players current = (Players) containerView.getTag();
Intent intent = new Intent(v.getContext(), Compare_Stats.class);
//we get the "fullName"
intent.putExtra("id", current.getPlayer_id());
v.getContext().startActivity(intent);
}
});
}
}
#NonNull
#Override
public PlayerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.player_list, parent, false);
return new PlayerViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PlayerViewHolder holder, int position) {
Players current = PlayersList.get(position);
holder.textView.setText(current.FullName());
holder.containerView.setTag(current);
}
#Override
public int getItemCount() {
return PlayersList.size();
}
}
Inside the class myclass you are definitely setting the adapter , but it looks like you are missing the code that sets the LayoutManager to RecyclerView .
recyclerView.setLayoutManager(new LinearLayoutManager(this/*Context here*/));
Another suggestion is that you should keep activity separately and not nest it inside a adapter.
I have a funny problem, I have my project act wired, am following some tutorials and copied some codes, but now I figured that I cannot put any of my activities as launcher activity except the main activity , I looked really deep in it and didn't find anything that make it the only activity that fits to be the launcher activity , is it a manifest problem ? or special flag in the main activity ??!!
please take a look at the main activity and the manifest:-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rozdoum.socialcomponents">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.CAMERA" />
<application
android:name=".Application"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id" />
<activity
android:name=".main.main.MainActivity"
android:configChanges="orientation|screenSize"
android:theme="#style/AppCompat.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".main.postDetails.PostDetailsActivity"
android:configChanges="orientation|screenSize"
android:label="#string/label_post_detail_activity" />
<activity
android:name=".main.post.createPost.CreatePostActivity"
android:configChanges="orientation|screenSize"
android:label="#string/label_create_post_activity" />
<activity
android:name=".main.imageDetail.ImageDetailActivity"
android:configChanges="orientation|screenSize"
android:label="#string/label_image_detail_activity"
android:theme="#style/AppCompat.Black.NoActionBar" />
<activity
android:name=".main.login.LoginActivity"
android:label="#string/title_activity_login"
android:theme="#style/AppCompat.NoActionBar" />
<activity
android:name=".main.editProfile.createProfile.CreateProfileActivity"
android:configChanges="orientation|screenSize"
android:label="#string/title_activity_create_profile" />
<activity
android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
android:theme="#style/Base.Theme.AppCompat" />
<activity
android:name=".main.profile.ProfileActivity"
android:configChanges="orientation|screenSize"
android:label="#string/title_activity_profile"
android:theme="#style/AppCompat.NoActionBar" />
<activity
android:name=".main.editProfile.EditProfileActivity"
android:configChanges="orientation|screenSize"
android:label="#string/title_activity_edit_profile" />
<activity
android:name=".main.post.editPost.EditPostActivity"
android:configChanges="orientation|screenSize"
android:label="#string/title_activity_edit_post" />
<activity
android:name=".main.usersList.UsersListActivity"
android:configChanges="orientation|screenSize"
android:theme="#style/AppCompat.NoActionBar" />
<activity
android:name=".main.followPosts.FollowingPostsActivity"
android:configChanges="orientation|screenSize"
android:label="#string/title_activity_following_posts"
android:theme="#style/AppCompat.NoActionBar" />
<activity
android:name=".main.search.SearchActivity"
android:configChanges="orientation|screenSize"
android:theme="#style/AppCompat.NoActionBar"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
<meta-data
android:name="io.fabric.ApiKey"
android:value="84e05e27c9fcba7e1de6a47e355a1aa247264a46" />
<service android:name=".services.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".services.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
main activity
public class MainActivity extends BaseActivity<MainView, MainPresenter> implements MainView {
private PostsAdapter postsAdapter;
private RecyclerView recyclerView;
private FloatingActionButton floatingActionButton;
private TextView newPostsCounterTextView;
private boolean counterAnimationInProgress = false;
private ProgressBar progressBar;
private SwipeRefreshLayout swipeContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initContentView();
}
#Override
protected void onResume() {
super.onResume();
presenter.updateNewPostCounter();
}
#NonNull
#Override
public MainPresenter createPresenter() {
if (presenter == null) {
return new MainPresenter(this);
}
return presenter;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case ProfileActivity.CREATE_POST_FROM_PROFILE_REQUEST:
refreshPostList();
break;
case CreatePostActivity.CREATE_NEW_POST_REQUEST:
presenter.onPostCreated();
break;
case PostDetailsActivity.UPDATE_POST_REQUEST:
presenter.onPostUpdated(data);
break;
}
}
}
#Override
public void onBackPressed() {
attemptToExitIfRoot(floatingActionButton);
}
public void refreshPostList() {
postsAdapter.loadFirstPage();
if (postsAdapter.getItemCount() > 0) {
recyclerView.scrollToPosition(0);
}
}
#Override
public void removePost() {
postsAdapter.removeSelectedPost();
}
#Override
public void updatePost() {
postsAdapter.updateSelectedPost();
}
#Override
public void showCounterView(int count) {
AnimationUtils.showViewByScaleAndVisibility(newPostsCounterTextView);
String counterFormat = getResources().getQuantityString(R.plurals.new_posts_counter_format, count, count);
newPostsCounterTextView.setText(String.format(counterFormat, count));
}
private void initContentView() {
if (recyclerView == null) {
progressBar = findViewById(R.id.progressBar);
swipeContainer = findViewById(R.id.swipeContainer);
initFloatingActionButton();
initPostListRecyclerView();
initPostCounter();
}
}
private void initFloatingActionButton() {
floatingActionButton = findViewById(R.id.addNewPostFab);
if (floatingActionButton != null) {
floatingActionButton.setOnClickListener(v -> presenter.onCreatePostClickAction(floatingActionButton));
}
}
private void initPostListRecyclerView() {
recyclerView = findViewById(R.id.recycler_view);
postsAdapter = new PostsAdapter(this, swipeContainer);
postsAdapter.setCallback(new PostsAdapter.Callback() {
#Override
public void onItemClick(final Post post, final View view) {
presenter.onPostClicked(post, view);
}
#Override
public void onListLoadingFinished() {
progressBar.setVisibility(View.GONE);
}
#Override
public void onAuthorClick(String authorId, View view) {
openProfileActivity(authorId, view);
}
#Override
public void onCanceled(String message) {
progressBar.setVisibility(View.GONE);
showToast(message);
}
});
recyclerView.setLayoutManager(new LinearLayoutManager(this));
((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
recyclerView.setAdapter(postsAdapter);
postsAdapter.loadFirstPage();
}
private void initPostCounter() {
newPostsCounterTextView = findViewById(R.id.newPostsCounterTextView);
newPostsCounterTextView.setOnClickListener(v -> refreshPostList());
presenter.initPostCounter();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
hideCounterView();
super.onScrolled(recyclerView, dx, dy);
}
});
}
#Override
public void hideCounterView() {
if (!counterAnimationInProgress && newPostsCounterTextView.getVisibility() == View.VISIBLE) {
counterAnimationInProgress = true;
AlphaAnimation alphaAnimation = AnimationUtils.hideViewByAlpha(newPostsCounterTextView);
alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
counterAnimationInProgress = false;
newPostsCounterTextView.setVisibility(View.GONE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
alphaAnimation.start();
}
}
#SuppressLint("RestrictedApi")
#Override
public void openPostDetailsActivity(Post post, View v) {
Intent intent = new Intent(MainActivity.this, PostDetailsActivity.class);
intent.putExtra(PostDetailsActivity.POST_ID_EXTRA_KEY, post.getId());
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
View imageView = v.findViewById(R.id.postImageView);
View authorImageView = v.findViewById(R.id.authorImageView);
ActivityOptions options = ActivityOptions.
makeSceneTransitionAnimation(MainActivity.this,
new android.util.Pair<>(imageView, getString(R.string.post_image_transition_name)),
new android.util.Pair<>(authorImageView, getString(R.string.post_author_image_transition_name))
);
startActivityForResult(intent, PostDetailsActivity.UPDATE_POST_REQUEST, options.toBundle());
} else {
startActivityForResult(intent, PostDetailsActivity.UPDATE_POST_REQUEST);
}
}
public void showFloatButtonRelatedSnackBar(int messageId) {
showSnackBar(floatingActionButton, messageId);
}
#Override
public void openCreatePostActivity() {
Intent intent = new Intent(this, CreatePostActivity.class);
startActivityForResult(intent, CreatePostActivity.CREATE_NEW_POST_REQUEST);
}
#SuppressLint("RestrictedApi")
#Override
public void openProfileActivity(String userId, View view) {
Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
intent.putExtra(ProfileActivity.USER_ID_EXTRA_KEY, userId);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && view != null) {
View authorImageView = view.findViewById(R.id.authorImageView);
ActivityOptions options = ActivityOptions.
makeSceneTransitionAnimation(MainActivity.this,
new android.util.Pair<>(authorImageView, getString(R.string.post_author_image_transition_name)));
startActivityForResult(intent, ProfileActivity.CREATE_POST_FROM_PROFILE_REQUEST, options.toBundle());
} else {
startActivityForResult(intent, ProfileActivity.CREATE_POST_FROM_PROFILE_REQUEST);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.profile:
presenter.onProfileMenuActionClicked();
return true;
case R.id.followingPosts:
Intent followingPosts = new Intent(this, FollowingPostsActivity.class);
startActivity(followingPosts);
return true;
case R.id.search:
Intent searchIntent = new Intent(this, SearchActivity.class);
startActivity(searchIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
I tried to change my Launcher Activity in my Manifest file. After changing it, I went reseted my code of again (re-edited so that it was the same as before). So I just copy pasted this code between my activities
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
After reseting my code the app won't open.
I got an error
java.lang.IllegalArgumentException: AppCompat does not support the current theme features, poiting out on my setContentView(R.layout.activity_main);
I got really frustrated by this problem cause I didn't change anything in my code (it is excaclty as it used to be when it was working)
Here is my manifest file code
<manifest package="com.inthessaloniki.cityguide"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:installLocation="auto">
<!-- versionCode, versionName, minSdkVersion, targetSdkVersion properties are set via Gradle script -->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<!-- allows the API to access Google web-based services -->
<!-- maps API needs OpenGL ES 2.0 -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="false"/>
<!--
You can easily change the main theme. Just modify application.android:theme attribute.
There are 8 main themes you can use:
Theme.CityGuide.Blue
Theme.CityGuide.Brown
Theme.CityGuide.Carrot
Theme.CityGuide.Gray
Theme.CityGuide.Green
Theme.CityGuide.Indigo
Theme.CityGuide.Red
Theme.CityGuide.Yellow
Don't forget to modify also MainActivity's theme.
-->
<application
android:name=".CityGuideApplication"
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.CityGuide.Indigo"
tools:replace="android:icon">
<!--
Themes for MainActivity:
Theme.CityGuide.TransparentStatusBar.Blue
Theme.CityGuide.TransparentStatusBar.Brown
Theme.CityGuide.TransparentStatusBar.Carrot
Theme.CityGuide.TransparentStatusBar.Gray
Theme.CityGuide.TransparentStatusBar.Green
Theme.CityGuide.TransparentStatusBar.Indigo
Theme.CityGuide.TransparentStatusBar.Red
Theme.CityGuide.TransparentStatusBar.Yellow
-->
<activity
android:name=".activity.MainActivity"
android:label="#string/app_name"
android:theme="#style/Theme.CityGuide.TransparentStatusBar.Indigo"
android:launchMode="standard">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".activity.PoiDetailActivity"
android:label="#string/title_poi_detail"
android:launchMode="standard"/>
<activity
android:name=".activity.TourDetailActivity"
android:label="#string/title_tour_detail"
android:launchMode="standard"/>
<activity
android:name=".activity.MapActivity"
android:label="#string/title_map"
android:launchMode="standard"/>
<activity
tools:replace="android:configChanges"
android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|uiMode|smallestScreenSize"/>
<activity
android:name=".activity.DescriptionDetailsActivity"
android:label="#string/title_activity_description_details"
android:theme="#style/Theme.CityGuide.TransparentStatusBar.Indigo">
</activity>
<activity
android:name=".activity.MailFormActivity"
android:label="#string/title_tour_detail"
android:theme="#style/Theme.CityGuide.TransparentStatusBar.Indigo">
</activity>
<provider
android:name=".content.PoiSearchRecentSuggestionsProvider"
android:authorities="com.inthessaloniki.cityguide.content.PoiSearchRecentSuggestionsProvider"
android:exported="false"/>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<meta-data
android:name="com.google.android.gms.analytics.globalConfigResource"
android:resource="#xml/analytics_global_tracker"/>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="#string/maps_api_key"/>
</application>
Main Activity Code
public class MainActivity extends AppCompatActivity implements DrawerAdapter.CategoryViewHolder.OnItemClickListener, OnSearchListener
{
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private ScrimInsetsFrameLayout mDrawerScrimInsetsFrameLayout;
private DrawerAdapter mDrawerAdapter;
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private List<CategoryModel> mCategoryList;
public static Intent newIntent(Context context)
{
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
return intent;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupActionBar();
setupRecyclerView();
setupDrawer(savedInstanceState);
// init analytics tracker
((CityGuideApplication) getApplication()).getTracker();
}
#Override
public void onStart()
{
super.onStart();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStart(this);
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onPause()
{
super.onPause();
}
#Override
public void onStop()
{
super.onStop();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStop(this);
}
#Override
public void onDestroy()
{
super.onDestroy();
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// open or close the drawer if home button is pressed
if(mDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
// action bar menu behaviour
switch(item.getItemId())
{
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfiguration)
{
super.onConfigurationChanged(newConfiguration);
mDrawerToggle.onConfigurationChanged(newConfiguration);
}
#Override
public void setTitle(CharSequence title)
{
mTitle = title;
getSupportActionBar().setTitle("");
Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/nexa-bold.otf");
final TextView toolbarName = (TextView) findViewById(R.id.toolbar_title);
toolbarName.setText(mTitle);
}
#Override
public void onItemClick(View view, int position, long id, int viewType)
{
// position
int categoryPosition = mDrawerAdapter.getCategoryPosition(position);
selectDrawerItem(categoryPosition);
}
#Override
public void onSearch(String query)
{
Fragment fragment = PoiListFragment.newInstance(query);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.activity_main_container, fragment).commitAllowingStateLoss();
mDrawerAdapter.setSelected(mDrawerAdapter.getRecyclerPositionByCategory(0));
setTitle(getString(R.string.title_search) + ": " + query);
}
private void setupActionBar()
{
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar bar = getSupportActionBar();
bar.setDisplayUseLogoEnabled(false);
bar.setDisplayShowTitleEnabled(true);
bar.setDisplayShowHomeEnabled(true);
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
}
private void setupRecyclerView()
{
// reference
RecyclerView recyclerView = getRecyclerView();
// set layout manager
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
// load categories from database
loadCategoryList();
// set adapter
if(recyclerView.getAdapter()==null)
{
// create adapter
mDrawerAdapter = new DrawerAdapter(mCategoryList, this);
}
else
{
// refill adapter
mDrawerAdapter.refill(mCategoryList, this);
}
recyclerView.setAdapter(mDrawerAdapter);
// add decoration
List<Integer> dividerPositions = new ArrayList<>();
dividerPositions.add(3);
RecyclerView.ItemDecoration itemDecoration = new DrawerDividerItemDecoration(
this,
null,
dividerPositions,
getResources().getDimensionPixelSize(R.dimen.global_spacing_xxs));
recyclerView.addItemDecoration(itemDecoration);
}
private void setupDrawer(Bundle savedInstanceState)
{
mTitle = getTitle();
mDrawerTitle = getTitle();
Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/nexa-bold.otf");
final TextView toolbarName = (TextView) findViewById(R.id.toolbar_title);
toolbarName.setText(mTitle);
toolbarName.setTypeface(typeface);
// reference
mDrawerLayout = (DrawerLayout) findViewById(R.id.activity_main_layout);
mDrawerScrimInsetsFrameLayout = (ScrimInsetsFrameLayout) findViewById(R.id.activity_main_drawer);
// set drawer
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerLayout.setStatusBarBackgroundColor(ResourcesHelper.getValueOfAttribute(this, R.attr.colorPrimaryDark));
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close)
{
#Override
public void onDrawerClosed(View view)
{
toolbarName.setText(mTitle);
getSupportActionBar().setTitle("");
supportInvalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView)
{
toolbarName.setText(mTitle);
getSupportActionBar().setTitle("");
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
// show initial fragment
if(savedInstanceState == null)
{
selectDrawerItem(0);
}
}
private void selectDrawerItem(int position)
{
long mCategoryId = mCategoryList.get(position).getId();
Fragment fragment = null;
if(mCategoryId==PoiListFragment.CATEGORY_ID_ALL || mCategoryId==PoiListFragment.CATEGORY_ID_FAVORITES ){
fragment = PoiListFragment.newInstance(mCategoryId);
}else{
fragment = SubCategoryListFragment.newInstance(mCategoryId);
}
FragmentManager fragmentManager = getSupportFragmentManager();
String categoryName = mCategoryList.get(position).getName();
fragmentManager.beginTransaction().replace(R.id.activity_main_container, fragment, categoryName).addToBackStack(categoryName).commitAllowingStateLoss();
mDrawerAdapter.setSelected(mDrawerAdapter.getRecyclerPositionByCategory(position));
setTitle(categoryName);
mDrawerLayout.closeDrawer(mDrawerScrimInsetsFrameLayout);
}
public void showPOIFragment(long categoryId, String categoryName){
PoiListFragment fragment = PoiListFragment.newInstance(categoryId);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.activity_main_container, fragment, categoryName).addToBackStack(categoryName).commitAllowingStateLoss();
if (!TextUtils.isEmpty(categoryName)){
setTitle(categoryName);
}
}
public void showSubCategoryFragment(long categoryId, String categoryName){
SubCategoryListFragment fragment = SubCategoryListFragment.newInstance(categoryId);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.activity_main_container, fragment, categoryName).addToBackStack(categoryName).commitAllowingStateLoss();
if (!TextUtils.isEmpty(categoryName)){
setTitle(categoryName);
}
}
private void loadCategoryList()
{
try
{
mCategoryList = CategoryDAO.readAll(-1l, -1l);
}
catch(SQLException e)
{
e.printStackTrace();
}
CategoryModel Thessaloniki = new CategoryModel();
Thessaloniki.setId(PoiListFragment.CATEGORY_ID_THESSALONIKI);
Thessaloniki.setName("Thessaloniki");
Thessaloniki.setImage("drawable://" + R.drawable.ic_category_all);
CategoryModel all = new CategoryModel();
all.setId(PoiListFragment.CATEGORY_ID_ALL);
all.setName(getResources().getString(R.string.drawer_category_all));
all.setImage("drawable://" + R.drawable.ic_category_all);
CategoryModel favorites = new CategoryModel();
favorites.setId(PoiListFragment.CATEGORY_ID_FAVORITES);
favorites.setName(getResources().getString(R.string.drawer_category_favorites));
favorites.setImage("drawable://" + R.drawable.ic_category_favorites);
mCategoryList.add(0,Thessaloniki);
mCategoryList.add(1, all);
mCategoryList.add(2, favorites);
}
private RecyclerView getRecyclerView()
{
return (RecyclerView) findViewById(R.id.activity_main_drawer_recycler);
}
#Override
public void onBackPressed() {
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count == 1) {
finish();
}else{
getSupportFragmentManager().popBackStack();
String name = getSupportFragmentManager().getBackStackEntryAt(count-2).getName();
setTitle(name);
}
// super.onBackPressed();
}
}
I had face similar issue when i had firstly created project in android stdio with API 23 so for fixing these issue try to do some changes.
Please change your activity code first line :-
public class MainActivity extends AppCompatActivity
to these :-
public class MainActivity extends Activity
It had worked for me when i was in same problem.
Part of an app I'm working on has two buttons, and my problem is that when I call startActivity() it will work as expected for one activity but not another.
So this works:
startActivity(new Intent(StartScreenActivity.this, FiltersActivity.class));
But this does not:
startActivity(new Intent(StartScreenActivity.this, MainActivity.class));
Both worked fine yesterday, but since updating Android Studio this morning nothing happens when I try to start MainActivity. Both are present in my manifest:
<activity
android:name=".FiltersActivity"
android:label="#string/title_activity_filters"
android:theme="#style/AppTheme.NoActionBar" >
</activity>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main"
android:theme="#style/AppTheme.NoActionBar" >
</activity>
There are no errors thrown to the LogCat or anything like that, simply one works and nothing happens for the other. I would assume something is wrong with the MainActivity class, but it worked fine until a few hours ago and the only changes since then have been updating Studio, as I mentioned, and some small xml layout changes to the main activity layout file which I have tried undoing but that doesn't fix the problem.
Full manifest:
<?xml version="1.0" encoding="utf-8"?>
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity
android:name=".StartScreenActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".FiltersActivity"
android:label="#string/title_activity_filters"
android:theme="#style/AppTheme.NoActionBar" >
</activity>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main"
android:theme="#style/AppTheme.NoActionBar" >
</activity>
<activity
android:name=".AddNewVenue"
android:theme="#style/AppTheme.NoActionBar" >
</activity>
<activity
android:name=".AddNewMenuItemActivity"
android:label="#string/title_activity_add_new_menu_item"
android:theme="#style/AppTheme.NoActionBar" >
</activity>
</application>
MainActivity.java:
package me.theglassboard.vee;
public class MainActivity extends FragmentActivity
implements VenueListFragment.OnFragmentInteractionListener, LocationListener {
private VenueDao venueDao;
private ArrayList<Venue> venues;
private LocationManager locationManager;
private Location userLocation;
// Static strings to be used when putting and getting extras to/from intents
public static String MAX_PRICE = "maxPrice";
public static String MAX_DISTANCE = "maxDistance";
public static String ACCEPTS_CARD = "acceptsCard";
public static String WHEELCHAIR_ACCESS = "wheelchairAccess";
public static String SERVES_NON_VEGAN = "servesNonVegan";
public static float DEFAULT_MAX_DISTANCE = 5000;
public static int DEFAULT_MAX_PRICE = 999;
public static FragmentManager fragmentManager;
public SectionsPagerAdapter mSectionsPagerAdapter;
/**
* Request codes:
*
* Used in the MapFragment and ListFragment when adding a new
* Venue or Menu Item. Those operations use startActivityForResult()
* and the request code parameter of that method will be one of these
* codes. They are therefor public static to ensure the fragments
* have access, and final to ensure their values can't change at runtime.
*/
public static final int ADD_NEW_VENUE = 111;
public static final int ADD_NEW_MENU_ITEM = 222;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupLocation();
//venueDao = new VenueDao(this);
//venues = venueDao.getAllVenues();
fragmentManager = getSupportFragmentManager();
// Enable custom back button
findViewById(R.id.toolbarLeftButton).setVisibility(View.VISIBLE);
findViewById(R.id.toolbarLeftButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private void searchVenues() {
Log.d("INSIDE", "searchVenues()");
Bundle extras = getIntent().getExtras();
int maxPrice = extras.getInt(FiltersActivity.MAX_PRICE, DEFAULT_MAX_PRICE);
float maxDistance = extras.getFloat(FiltersActivity.MAX_DISTANCE, DEFAULT_MAX_DISTANCE);
Boolean acceptsCard = extras.getBoolean(FiltersActivity.ACCEPTS_CARD, false);
Boolean wheelchairAccess = extras.getBoolean(FiltersActivity.WHEELCHAIR_ACCESS, false);
Boolean servesNonVegan = extras.getBoolean(FiltersActivity.SERVES_NON_VEGAN, false);
GetVenuesTask getVenuesTask = new GetVenuesTask(
(int)maxDistance,
(float)userLocation.getLatitude(),
(float)userLocation.getLongitude(),
maxPrice,
acceptsCard,
wheelchairAccess,
servesNonVegan,
this);
getVenuesTask.execute();
}
public void launchMainActivity(ArrayList<Venue> fetchedVenues) {
Log.d("INSIDE", "launchMainActivity()");
// Create the adapter that will return a fragment for both of the
// primary sections of the activity.
venues = fetchedVenues;
//findViewById(R.id.loadingFrame).setVisibility(View.GONE);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter
ViewPager mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.setTabsFromPagerAdapter(mSectionsPagerAdapter);
}
#Override
public void onFragmentInteraction(String id) {
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Pass the activity result to both the map and list fragments
// to perform whatever task they need to do.
for(Fragment fragment : fragmentManager.getFragments())
fragment.onActivityResult(requestCode, resultCode, data);
}
/**
* Fragment Adapter that returns either the VenueMap or VenueList fragments
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
VenueMapFragment mapFragment;
VenueListFragment listFragment;
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
if(position == 0/* && GooglePlayServicesUtil.isGooglePlayServicesAvailable(MainActivity.this) == ConnectionResult.SUCCESS*/) {
mapFragment = VenueMapFragment.newInstance(venues);
return mapFragment;
}
if(position == 1) {
listFragment = VenueListFragment.newInstance(venues);
return listFragment;
}
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "MAP";
case 1:
return "LIST";
}
return null;
}
}
/**
* The placeholder fragment initially provided by Studio.
*
* I am keeping it here for the time being as a default fragment
* to be displayed if, for some reason, the map or list fragment
* cannot be loaded.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
public void onLocationChanged(Location location) {
userLocation = location;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 5, this);
searchVenues();
return;
}
locationManager.removeUpdates(this);
searchVenues();
}
public void onProviderDisabled(String provider) {
//CODE
}
public void onProviderEnabled(String provider) {
//CODE
}
public void onStatusChanged(String provider, int status, Bundle extras) {
//CODE
}
public void setupLocation() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 5, this);
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 5, this);
}
#Override
protected void onResume()
{
super.onResume();
if(venues == null)
finish();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 5, this);
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 5, this);
}
#Override
protected void onPause()
{
super.onPause();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 5, this);
return;
}
locationManager.removeUpdates(this);
}
}
StartScreenActivity.java:
public class StartScreenActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_screen);
VenueDao venueDao = new VenueDao(this);
findViewById(R.id.startScreenGoButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("CLICKED", "Start Main Activity");
Intent mainActivity = new Intent(StartScreenActivity.this, MainActivity.class);
mainActivity.putExtra(MainActivity.MAX_PRICE, MainActivity.DEFAULT_MAX_PRICE);
mainActivity.putExtra(MainActivity.MAX_DISTANCE, MainActivity.DEFAULT_MAX_DISTANCE);
mainActivity.putExtra(MainActivity.ACCEPTS_CARD, false);
mainActivity.putExtra(MainActivity.WHEELCHAIR_ACCESS, false);
mainActivity.putExtra(MainActivity.SERVES_NON_VEGAN, false);
startActivity(mainActivity);
}
});
findViewById(R.id.startScreenFilterButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(StartScreenActivity.this, FiltersActivity.class));
}
});
}
}
Change your <activity> in manifest with:
<activity
android:name=".FiltersActivity"
android:label="#string/title_activity_filters"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="me.theglassboard.vee.FiltersActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="me.theglassboard.vee.MainActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Try the follow:
reference your button like this:
mButton1 = (Button) findViewById(R.id.button_1);
mButton2 = (Button) findViewById(R.id.button_2);
call your button with onClickListener
mButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent button1 = new Intent(StartScreenActivity.this, FiltersActivity.class);
startActivity(button1);
}
}
mButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent button2= new Intent(StartScreenActivity.this, MainActivity.class);
startActivity(button);
}
}
if not working, send printout of the MainsActivity.class and StartScreenActivity
I create a project using Wifi. I implement a standalone class(WifiScanReceiver) extends BroadcastReceiver. I try to call the standalone class from MainActivity. I want to trigger the wifiList alertdialog when I touch a ImageView. Now I got the null pointer exception.
In here It shown another one error You need to use a Theme.AppCompat theme (or descendant) with this activity.
Please help me to solve these problems.Any help I would really appreciated.
MainActivity:
public class MainActivity extends AppCompatActivity {
private boolean isWifiStart = false;
WifiManager wifiManager;
String[] strWifiList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wifiManager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
ImageView imgView = (ImageView)findViewById(R.id.floorPlan);
imgView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (isWifiStart) {
LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View inflateView = inflater.inflate(R.layout.dialog_wifi_list, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getBaseContext());
WifiScanReceiver receiver = new WifiScanReceiver(wifiManager);
registerReceiver(receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifiManager.startScan();
try {
strWifiList = receiver.getWifiListString();
} catch (Exception e) {
shortMsg(getBaseContext(),"Exception : " + e.getMessage());
}
ListView wifiList = (ListView)inflateView.findViewById(R.id.list_Wifi);
builder.setView(inflateView);
wifiList.setAdapter(new ArrayAdapter<>(getBaseContext(), android.R.layout.simple_list_item_1,strWifiList));
builder.setView(inflateView);
builder.show();
}
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.wifiStart:
shortMsg(this,"Wifi Start");
isWifiStart = true;
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void shortMsg(Context ctx,String msg) {
Toast.makeText(ctx,msg,Toast.LENGTH_SHORT).show();
}
}
WifiScanReceiver :(Standalone class)
public class WifiScanReceiver extends BroadcastReceiver {
private String[] wifiListString;
private WifiManager wifiMgr;
public WifiScanReceiver(WifiManager manager) {
this.wifiMgr = manager;
}
#Override
public void onReceive(Context context, Intent intent) {
List<ScanResult> wifiScanList = wifiMgr.getScanResults();
Collections.sort(wifiScanList, new Comparator<ScanResult>() {
#Override
public int compare(ScanResult lhs, ScanResult rhs) {
return (lhs.level > rhs.level ? -1 : (lhs.level == rhs.level ? 0 : 1));
}
});
wifiListString = new String[wifiScanList.size()];
for (int i = 0; i < wifiScanList.size(); i++) {
wifiListString[i] = (wifiScanList.get(i).SSID);
}
}
public String[] getWifiListString() {
return wifiListString;
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sample.rewifiheatmap" >
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>