I'm beginner in Android Studio. My app allows me to add users(fn,ln,adrs,Uri::ImageUri) and list them and view their info.
I want to be able to display one user's info when clicking on my listview.
The problem is that i only get a blank space instead of my desired imageview.
My main activity :
public class MainActivity extends AppCompatActivity {
public static ArrayList <User> users =new ArrayList <User>();
public static User userSelected;
public static ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
mListView = (ListView) findViewById(R.id.List);
}
public void InputInfo(View view) {
Intent AddEmployee = new Intent(this, NewEmployeeInfo.class);
startActivityForResult(AddEmployee,0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(0, resultCode, data);
finaltest =NewEmployeeInfo .targetUri ;
UserAdapter useradapter;
useradapter = new UserAdapter (MainActivity .this, android.R.layout.simple_list_item_1, users ) ;
mListView.setAdapter(useradapter );
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
Intent appInfo = new Intent(MainActivity.this, DisplayInfo.class);
User temp= users.get(position );
userSelected =new User(temp.first_name ,temp.last_name,temp.adr,temp.url );
startActivity(appInfo);
}
});
}
}
My second one (where the user inputs the info :
public class NewEmployeeInfo extends AppCompatActivity {
public ImageView imageview;
public ImageView targetImage;
public User u;
public static Bitmap photo;
public static Uri targetUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_employee_info);
}
public void takePhoto(View view) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);
}
public void pickphoto(View view) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
imageview = (ImageView) this.findViewById(imageView);
resultphoto(requestCode, resultCode, imageReturnedIntent);
}
public void Save(View view) {
Intent SaveDataIntent = new Intent(this, MainActivity.class);
EditText FN = (EditText) findViewById(R.id.editText);
EditText LN = (EditText) findViewById(R.id.editText5);
EditText ADDRESS = (EditText) findViewById(R.id.editText6);
String firstname = FN.getText().toString();
String lastname = LN.getText().toString();
String address = ADDRESS.getText().toString();
if (firstname.length() == 0 || lastname.length() == 0 || address.length() == 0) {
Toast.makeText(this, "No Emty Fields!!",
Toast.LENGTH_LONG).show();
return;
}
u = new User(firstname, lastname, address, targetUri);
users.add(u);
setResult(RESULT_OK, SaveDataIntent);
finish();
}
private void resultphoto(int requestCode, int resultCode, Intent imageReturnedIntent) {
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
targetUri = imageReturnedIntent.getData();
imageview.setImageURI(targetUri);
imageReturnedIntent.getExtras().get("data");
}
break;
case 1:
if (resultCode == RESULT_OK) {
targetUri = imageReturnedIntent.getData();
targetImage = (ImageView) findViewById(imageView);
try {
photo = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
targetImage.setImageBitmap(photo);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;
}
}
}
the third and final one(Where the info should be displayed)
public class DisplayInfo extends AppCompatActivity {
public ImageView imageView;
public Bitmap image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_info);
TextView fn = (TextView) findViewById(R.id.firstname);
TextView ln = (TextView) findViewById(R.id.lastname);
TextView adr = (TextView) findViewById(R.id.address);
imageView = (ImageView) findViewById(R.id.imageView2);
fn.setText(MainActivity.userSelected.first_name);
ln.setText(MainActivity.userSelected.last_name);
adr.setText(MainActivity.userSelected.adr);
imageView.setImageURI(MainActivity.userSelected.url ) ;
This error keep showing up
E/DatabaseUtils: Writing exception to parcel
java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/810 from pid=12644, uid=10280 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
Though I included these permissions in my manifest file:
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Ask runTime permissions
tutorial
My problem was in the Manifest file;
It was
<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=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NewEmployeeInfo">
android:parentActivityName=".MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
</activity>
<activity android:name=".DisplayInfo" />
<activity android:name=".UserAdapterActivity"></activity>
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</application>
I misplaced my permissions. It should've been like this
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mobilonia.employeesapp">
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<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=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NewEmployeeInfo">
android:parentActivityName=".MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
</activity>
<activity android:name=".DisplayInfo" />
<activity android:name=".UserAdapterActivity"></activity>
</application>
</manifest>
Related
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 keep getting this build error 'class' or 'interface' expected. Everything I'm finding on SO is saying that my Java class is missing (or has an extra) a "}" I'm getting this error in my AndroidManifest.xml for all my Java activities. Here is the Java code:
public class MainActivity extends AppCompatActivity {
protected static final String TAG = "com.example.grey";
EditText SendValue;
Button SendEditTextValue;
Intent intent;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
Log.d(TAG, "onCreate started from Main Activity");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mMenuInflater = getMenuInflater();
mMenuInflater.inflate(R.menu.my_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.action_setting){
Toast.makeText(MainActivity.this,
"Settings Clicked",
Toast.LENGTH_SHORT).show();
}
if(item.getItemId() == R.id.about_us){
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
public void sendButton(View view){
SendEditTextValue = (Button) findViewById(R.id.button1);
SendValue = (EditText) findViewById(R.id.editText1);
SendEditTextValue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent = new Intent(getApplicationContext(), TextBoxMsgSend.class);
intent.putExtra("EdiTtEXTvALUE", SendValue.getText().toString());
startActivity(intent);
}
});
}
public void movieButton(View view){
Intent intent = new Intent(this, ShowMovies.class);
startActivity(intent);
}
public void button7(View view){
CharSequence text = "Two";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(this, text, duration);
toast.show();
}
public void button8(View view){
CharSequence text = "Three";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(this, text, duration);
toast.show();
}
public void button9(View view){
CharSequence text = "Four";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(this, text, duration);
toast.show();
}
#Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart started from Main Activity");
}
#Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause started from Main Activity");
}
#Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop started from Main Activity");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy started from Main Activity");
}
#Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart started from Main Activity");
}
}
And here is the AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.grey">
<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/Theme.AppCompat.Light.NoActionBar">
<!-- The main/home activity (it has no parent activity) -->
<activity android:name="MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- A child of the main activity -->
<activity
android:name=".TextBoxMsgSend"
android:parentActivityName=".MainActivity" />
<activity
android:name=".ShowMovies"
android:parentActivityName=".MainActivity" />
<activity
android:name=".RecyclerAdapter"
android:parentActivityName=".MainActivity" />
<activity
android:name=".MovieDetails"
android:parentActivityName=".ShowMovies" />
<activity
android:name=".AboutActivity"
android:parentActivityName=".MainActivity">
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.grey.MainActivity" />
</activity>
</application>
</manifest>
I keep getting build errors and am not able to do any commits. It was working fine the other day so I'm not really sure what changed. I can post my other activities if needed.
public class MovieDetails extends AppCompatActivity{
private static final String TAG = "MovieDetailsActivity";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_details);
Log.d(TAG, "Started program.");
getGalleryIntent();
}
private void getGalleryIntent(){
if(getIntent().hasExtra("image_url") && getIntent().hasExtra("image_name")){
Log.d(TAG,"Found intents.");
String imageURL = getIntent().getStringExtra("image_url");
String imageName = getIntent().getStringExtra("image_name");
String imageYear = getIntent().getStringExtra("image_year");
String imageDirector = getIntent().getStringExtra("image_director");
String imageDescription = getIntent().getStringExtra("image_description");
setImage(imageURL, imageName, imageYear, imageDirector, imageDescription);
}
}
private void setImage(String imageURL, String imageName, String imageYear, String imageDirector, String imageDescription){
TextView name = findViewById(R.id.title);
name.setText(imageName);
TextView year = findViewById(R.id.year);
year.setText(imageYear);
TextView director = findViewById(R.id.director);
director.setText(imageDirector);
TextView description = findViewById(R.id.description);
description.setText(imageDescription);
ImageView image = findViewById(R.id.image);
Glide.with(this).asBitmap().load(imageURL).into(image);
}
}
Try a period before MainActivity where it's declared in the manifest.
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'm doing a basic activity of moving from one page to another. Everything was going perfect until I get two pages deep into the app. I used the same exact code for each page class, put the activities in the manifest and made sure all words were spelled correctly, etc., but the intent doesn't do anything when I try to go three pages deep. There are no error messages in the log at all. When I click on a button on the third page, it just turns blue but doesn't move to the next page like the previous pages. Here's my code:
from page 1 to 3:
Page1:
public class MainActivity extends ActionBarActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton(); }
public void addListenerOnButton() {
final Context context = this;
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, MainMenu.class);
startActivity(intent);
}
});
}
}
Page 2: has more buttons...
public class MainMenu extends ActionBarActivity {
Button button;
Button button2;
Button button3;
Button button4;
Button button5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
addListenerOnButton();
}
public void addListenerOnButton() {
final Context context = this;
button = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
button5 = (Button) findViewById(R.id.button5);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, OneMain.class);
startActivity(intent);
}
});
button2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, TwoMain.class);
startActivity(intent);
}
});
button3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, ThreeMain.class);
startActivity(intent);
}
});
button4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, FourMain.class);
startActivity(intent);
}
});
button5.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, FiveMain.class);
startActivity(intent);
}
});
}
}
Page 3:
public class OneMain extends ActionBarActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.one_main);
}
public void addListenerOnButton() {
final Context context = this;
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, Alphabet.class);
startActivity(intent);
}
});
}
}
I also made sure I put in all the imports. Someone help. I'm stuck :(.
Here is the manifest xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.juwar74.alarabic"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity android:name=".MainActivity"
android:label="#string/app_name"
android:launchMode="singleTop"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:label="#string/app_name"
android:name=".MainMenu" >
</activity>
<activity
android:label="#string/app_name"
android:name=".OneMain" >
</activity>
<activity
android:label="#string/app_name"
android:name=".TwoMain" >
</activity>
<activity
android:label="#string/app_name"
android:name=".ThreeMain" >
</activity>
<activity
android:label="#string/app_name"
android:name=".FourMain" >
</activity>
<activity
android:label="#string/app_name"
android:name=".FiveMain" >
</activity>
<activity
android:label="#string/app_name"
android:name=".OneVoc" >
</activity>
</application>
</manifest>
And here is the code for the Alphabet.class
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
public class Alphabet extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alphabet);
}
}
in page3 you never called addListenerOnButton() .
public class OneMain extends ActionBarActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.one_main);
// HERE you missed addListenerOnButton();
}
<activity
android:name=".Alphabet " >
</activity>
You missed this in the manifest.xml
First call addListenerOnButton() in OneMain.java after setContentView.
Then check manifest.
Alphabet.class is not registered in manifest.
<activity
android:label="#string/app_name"
android:name=".Alphabet" >
</activity>
After adding it, make sure you are rendering correct xml in Alphabet.java
I am trying to put 2 different layouts in my android application
and that on value in register using shared preferences
this is my code .. it stopped once i click logo
Part of
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs;
//String register;
prefs = PreferenceManager.getDefaultSharedPreferences(this);
register=prefs.getString("register", "no");
if(register.equalsIgnoreCase("no")) {
setContentView(R.layout.main_activity);
}
else
{
setContentView(R.layout.about);
}
}
the LogCat error
FATAL EXCEPTION: main
Process:com,cpcs,irissystem, PID:31749
java.lang.RuntimeExeption : unable to start activity componentInfo
{......MainActivity }:java.lang.NullPointerException
at android.app.ActivityThread.preformLaunchActivity(ActivityThread.java2328)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java2386)
At android.app.ActivityThread.access$900(ActivityThread.java:169)
At android.app.ActivityThread$H.handleMessage(ActivityThread.java:1277)
At android.os.Handler.dispatchMeesage(Handler.java:102)
At android.os.looper.loop(LooperLjava:136)
At android.app.ActivityThread.Main(ActivityThread.java:5476)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$methodAndArgsCaller.run....:1268)
Activity Class
public class MainActivity extends Activity {
public static String register;
private static final int CAMERA_REQUEST = 1888;
public static String IrisCode;
String IrisCode2;
ImageView imageView;
private static Bitmap eyeImage;
EditText passwordText;
public static float perc ;
SharedPreferences prefs;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
register=prefs.getString("register", "no");
if(register.equalsIgnoreCase("no")) {
setContentView(R.layout.main_activity);
}
else
{
setContentView(R.layout.about);
}
Toast.makeText(MainActivity.this,"befroe: "+ register, Toast.LENGTH_LONG).show();
Button InstructionButton = (Button) findViewById(R.id.inst);
Button enrollButton = (Button) findViewById(R.id.enroll);
Button verifyButton = (Button) findViewById(R.id.ver);
passwordText = (EditText) findViewById(R.id.pass);
if(register.equalsIgnoreCase("no")){
verifyButton.setEnabled(false);
}
enrollButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//Go to the next page
//if Not registered before go to start to enter data
//else go to setting
Intent i = new Intent();
if(register.equalsIgnoreCase("no")) {
i = new Intent (MainActivity.this,start.class);
startActivity(i);
}
else
{
i = new Intent (MainActivity.this,setting.class);
startActivity(i);
}
}
});
InstructionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//Go to the instruction page
Intent i = new Intent (MainActivity.this,instruction.class);
startActivity(i);
}
});
verifyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if("0000".equals(passwordText.getText().toString())){
String same="aothorizes acess";
Toast.makeText(MainActivity.this, same, Toast.LENGTH_LONG).show();
Intent i = new Intent (MainActivity.this,setting.class);
startActivity(i);
}
}
});
}
Manifest
<application
android:allowBackup="true"
android:icon="#drawable/logo"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.cpcs.irissystem.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>
<activity
android:name=".start" />
<activity
android:name=".setting" />
<activity
android:name=".aboutus" />
<activity
android:name=".instruction" />
<activity
android:name=".setting2"/>
<activity
android:name=".ver"/>
</application>
// Try this way,hope this will help you...
SharedPreferences prefs;
String register;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
register=prefs.getString("register", "no");
if(register.equalsIgnoreCase("no")) {
setContentView(R.layout.activity_main);
}
else
{
setContentView(R.layout.activity_main2);
}
}