So, I'm trying to follow along this website's tutorial.
https://developer.android.com/training/basics/firstapp/starting-activity.html#BuildIntent
I did the first part where I got the text box and a send button. I can enter text in the text box and click send. But the text box's text stays there. It doesn't disappear. So, the next part of the tutorial is how to get the text to disappear. I'm trying to follow along, but I can't get it to work.
Here's my code.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/editText"
android:layout_width="183dp"
android:layout_height="46dp"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="#string/edit_message"
android:inputType="textPersonName"
app:layout_constraintEnd_toStartOf="#+id/button_clear"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button_clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:text="#string/button_send"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/editText"
tools:layout_editor_absoluteY="14dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
strings.xml
<resources>
<string name="app_name">The Most Useless App</string>
<string name="edit_message">Enter a message</string>
<string name="button_send">Send</string>
</resources>
MainActivity.xml
package com.example.myfirstapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Capture the layout's TextView and set the string as its text
TextView textView = findViewById(R.id.textView);
textView.setText(message);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myfirstapp">
<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=".DisplayMessageActivity"
android:parentActivityName=".MainActivity">
<!-- The meta-data tag is required if you support API level 15 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
</activity>
</application>
</manifest>
MainActivity.java
package com.example.myfirstapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Capture the layout's TextView and set the string as its text
TextView textView = findViewById(R.id.textView);
textView.setText(message);
}
}
Errors I get
Cannot resolve symbol textView
Cannot resolve symbol activity_display_message
Cannot resolve symbol EXTRA_MESSAGE
The activity com.example.myfirstapp.MainActivity is not registered in
the manifest.
Any help would be appreciated.
Is a setting problem, the first thing you should do is
to do a clean build, you can select above android studio the option buld and then clean build. If does not work please post the output of your build.gradle file
There is also the possibility that you are just starting with android, and you do not know that have to import sometimes the needed libraries
Point your mouse to MainActivity and press alt+enter if you are in windows, and select add Activity to AndroidManifest, then do a clean build.
I suggest you to use the wizard building a new project, you go to Android studio and select file new project and follow the project, so MainActivity will be automatically added to your manifest
Related
I am building an android application where I am letting the users to sign in using google also. When they sign in using google and do not register themselves using the registration page then there are certain information which are left out.I also have a screen which updates the profile information of the user.
I want to set an icon on the home screen(kind of a bell icon) which displays that there are some notification and when the user click on that the button it tells that some information are left to be added and it redirects them to the update profile page.
The icon I want is like the notification icon(bell) in youtube.
Is there any way I can do this?
EDIT :
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/grdnt"
tools:context=".MainActivity">
<TextView
android:id="#+id/welcome_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome"
android:textColor="#2AF598"
android:textSize="50dp"
android:layout_alignParentTop="true"
android:layout_marginTop="80dp"
android:gravity="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/provide_food"
android:layout_width="270dp"
android:layout_height="60dp"
android:layout_below="#+id/welcome_text"
android:layout_marginTop="100dp"
android:layout_marginLeft="80dp"
android:gravity="center"
android:text="Do you have Food"
android:textSize="20dp"
android:background="#drawable/custombutton"
/>
<Button
android:id="#+id/need_food"
android:layout_width="270dp"
android:layout_height="60dp"
android:layout_below="#+id/provide_food"
android:layout_marginTop="50dp"
android:layout_marginLeft="80dp"
android:gravity="center"
android:text="Do you need Food"
android:textSize="20dp"
android:background="#drawable/custombutton"
/>
<Button
android:id="#+id/deliver_food"
android:layout_width="270dp"
android:layout_height="60dp"
android:layout_below="#+id/need_food"
android:layout_marginTop="50dp"
android:layout_marginLeft="80dp"
android:gravity="center"
android:text="Do you want to Deliver Food"
android:textSize="20dp"
android:background="#drawable/custombutton"
/>
</RelativeLayout>
MainActivity.java:
package com.example.helping_hands_individual;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button provide, need,deliver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
provide = (Button)findViewById(R.id.provide_food);
need = (Button)findViewById(R.id.need_food);
deliver = (Button)findViewById(R.id.deliver_food);
provide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Provide_food.class);
startActivity(intent);
}
});
}
}
Note: I am not using any custom toolbar, neither am I using any toolbar, my theme for the application is: NoActionBar
There are three ways to get that notification icon depending upon the theme you are using in your Activity.
1. No.ActionBar Theme: If you're not using any ActionBar or toolbar in your activity then you can create a View(ImageView or Button) in your Activity's layout file with Height and Width as same as the notification icon which is around 28dp and then position it at the top right corner of the screen. You can change the background image of the view according to the state you want.
2. Create your own toolbar: You can create your own toolbar and set the menu item in it. While creating the menu item make sure that you select showAsAction="always" this way your icon is always visible. here is a link for the reference
3.ActionBar Theme: If you're using the action bar theme then you can create a menu file with one item like in Option 2 and then override the onCreateOptionsMenu and inflate then inflate your menu in it.
Notification notification = new Notification.Builder(this)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.ic_notification)
.setContentIntent(pIntent)
.setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_LIGHTS|Notification.DEFAULT_VIBRATE)
.setAutoCancel(true)
.build();
Background
Just to set some context, I'm very new to Android app development. After using Android Developers guide on developing a basic app that would teach me how to create a "Hello, World!" project. However, after learning to build a user interface and start another activity. Ultimately, the main focus was to add some code to the MainActivity that starts a new activity to display a message when the user would tap the Send button. After running the app on my device, I attempted to type out a message and click send, only for the send button to ultimately close my app with no lag, or explaination as to why it closed.
MainActivity.java
package com.example.giglitz;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import static android.provider.AlarmClock.EXTRA_MESSAGE;
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** Called when the user taps the send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.giglitz">
<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=".DisplayMessageActivity">
android:parentActivityName=".MainActivity">
<!-- The meta-data tag is required if you support API level 15 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
</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>
DisplayMessageActivity.java
package com.example.giglitz;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class DisplayMessageActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Capture the layout's TextView and set the string as its text
TextView textView = findViewById(R.id.textView);
textView.setText(message);
}
}
activity_display_message.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DisplayMessageActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Logcat (after filtering Error, Show only selected application)
Process: com.example.giglitz, PID: 6422
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:402)
at android.view.View.performClick(View.java:7201)
at android.view.View.performClickInternal(View.java:7170)
at android.view.View.access$3500(View.java:806)
at android.view.View$PerformClick.run(View.java:27562)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397)
at android.view.View.performClick(View.java:7201)
at android.view.View.performClickInternal(View.java:7170)
at android.view.View.access$3500(View.java:806)
at android.view.View$PerformClick.run(View.java:27562)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.giglitz.MainActivity.sendMessage(MainActivity.java:24)
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397)
at android.view.View.performClick(View.java:7201)
at android.view.View.performClickInternal(View.java:7170)
at android.view.View.access$3500(View.java:806)
at android.view.View$PerformClick.run(View.java:27562)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/editTextTextPersonName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="#string/edit_message"
android:inputType="textPersonName"
app:layout_constraintEnd_toStartOf="#+id/button"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:onClick="sendMessage"
android:text="#string/button_send"
app:layout_constraintBaseline_toBaselineOf="#+id/editTextTextPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/editTextTextPersonName" />
</androidx.constraintlayout.widget.ConstraintLayout>
I think you either did not put anything in the 'onclick' field for your button, or you didn't set an ID for your EditText. Can you send your activity_main.xml file as well? If you want to know where it is, go to the 'res' directory, and then go into the 'layout' directory.
I will need to see your logcat output to determine what problems you encountered. Generally, when using Intent extras, I recommend checking for nullability of objects, as that string might not exist, although it clearly does in this case. So, please send a transcript of your logs.
Thanks!
It looks like you did not implement the 'onclick' behavior correctly in your app. In the XML file, you should add this line for your send button android:onClick="sendMessage"
Also, check out this for more details about implementing onClick behaviors in Android: https://developer.android.com/guide/topics/ui/controls/button#HandlingEvents, https://stackoverflow.com/a/4153842/1725535
It looks like you did not implement the 'onclick' behavior correctly in your app. In the XML file, you should add this line for your send button android:onClick="sendMessage"
To tell activity to listen the button click and call the onClickListner method.
It looks like you did not implement the 'onclick' behavior correctly in your app.
In the XML file, you should add this line for your send button
android:onClick="sendMessage" or you can use it programmatically by button id
For eg:-
Button btn = (Button) findViewById(R.Id.sendButton);
btn.setOnClickListner(new View.OnClickListner){
#Override
public onClick(View view){
// Your statement
}
}
To tell activity to listen the button click and call the onClickListner method.
I am working on a little Android Studio (version 2.2.3) application.
After adding a second activity with a lot of components I noticed that when I type R.id in the first activity, the auto-completion proposes me the components from the second activity.
Is this normal ?
And here is a working example of my issue (I took the screenshot from it), for simplicity I just created two empty activities each one with a button.
AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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=".Main2Activity"></activity>
</application>
MainActivity.java :
package com.example.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button btMain1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Here is the issue,
//autocompletion of R.id. shows every layout and their composents
btMain1 = (Button) findViewById(R.id.);
}
}
activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.myapplication.MainActivity">
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="198dp"
android:id="#+id/btMain1" />
</RelativeLayout>
Main2Activity.java :
package com.example.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
public class Main2Activity extends AppCompatActivity {
private Button btMain2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
}
activity_main2.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.myapplication.Main2Activity">
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="198dp"
android:id="#+id/btMain2" />
</RelativeLayout>
Yes. R.id will contain every single id defined in your app. Each id is just a number, and many of them are not used in any given activity or layout.
R.java is a generated file containing all the resource identifiers for your application.
R.id is just one subclass. You also would see R.layout auto-complete, for example on setContentView
The auto-completion will pull everything because there is no isolation inside of activities, fragments, services, etc.
(snippet of mine)
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
public final class R {
// ...
public static final class id {
public static final int action0=0x7f0e0090;
public static final int action_bar=0x7f0e0060;
public static final int action_bar_activity_content=0x7f0e0000;
public static final int action_bar_container=0x7f0e005f;
public static final int action_bar_root=0x7f0e005b;
public static final int action_bar_spinner=0x7f0e0001;
public static final int action_bar_subtitle=0x7f0e0041;
Your question been asked so even before I thought to learn android.
Android: What is R? Why is it so Cryptic?
R is a class containing the definitions for all resources of a
particular application package. It is in the namespace of the
application package.
For example, if you say in your manifest your package name is
com.foo.bar, an R class is generated with the symbols of all your
resources in com.foo.bar.R.
There are generally two R classes you will deal with
The framework resources in android.R
and
Your own in your namespace
It is named R because that stands for Resources, and there is no
point in making people type something longer, especially since it is
common to end up with fairly long symbol names after it, that can
cause a fair amount of line wrapper.
Now in my words,
If we are referencing our own resources that you have created, mostaly we use R. So android studio gives us suggestions based on that.
You should have also noticed android.R which is meant for utilizing resources built in to the operating system.
So yes you will get suggestions based on which R you use and now you should know suggestions based on that R is not for a particular Activity or view that's the reason it suggests them all.
Also there is an article, you can gain more knowledge about R.java , android.R and resources.
I am splitting this off from my other thread here: Display image in popout window after button is clicked -- Android/Java
The old thread got very convoluted and confusing, and a bit off-topic, so I wanted to create another one that is clearer with more information.
I am trying to display an image in Android using an image file path that changes every time the app is run. I know there are ways to declare resources in the XML layout file, but since the picture I'd like to display is taken from the camera, I can't do it that way. I need to be able to display the image without hardcoding it.
The following is the code that I have:
photo_viewer.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pictureViewer"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#string/viewImage" />
</RelativeLayout>
Java method to display image:
public void viewPhoto(String file){
ImageView imageView = new ImageView(getApplicationContext());
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
Bitmap image = BitmapFactory.decodeFile(file);
imageView.setImageBitmap(image);
RelativeLayout rl = (RelativeLayout)findViewById(R.id.pictureViewer);
rl.addView(imageView, lp);
}
However, when I run the above code the application crashes, saying it has stopped working. "file" is a string denoting the directory where the image from the camera is stored, and I know this part is correct. I can use it (using a different method) to change the wallpaper. It's just displaying it that is causing me trouble. I have tried various methods to simply display the image (dialogs, "drawable"s, bitmap factory, etc) and had the same problem with all of them. I feel like it's something simple that I have missed, since I'm new to Android app development. I'm hoping one of you folks might be able to shed some light on this.
EDIT:
I have decided to try another route, but I am still getting a null pointer exception. Here is all my code:
main class, viewPhoto method:
/* View photo */
public void viewPhoto(String file){
Intent imageView = new Intent(this, PhotoViewer.class);
imageView.putExtra("directory", file);
startActivity(imageView);
}
PhotoViewer class:
package com.androidproject;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class PhotoViewer extends Activity {
public String file;
ImageView image;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.photo_viewer);
//get file path of image
Bundle extras = getIntent().getExtras();
file = extras.getString("directory");
Drawable drawable = Drawable.createFromPath(file);
image.setImageDrawable(drawable);
}
}
photo_viewer.xml (created using the Eclipse tool, so it's not just any xml file)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/photo_viewer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".PhotoViewer" >
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#string/viewImage"/>
</RelativeLayout>
Project manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidproject"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Main"
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=".PhotoViewer"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.androidproject.PhotoViewer" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
The app continues to crash and tell me "unfortunately it stopped working". Here's the logcat of the error:
As always, help is appreciated!
The null pointer exception is because
Drawable drawable = Drawable.createFromPath(file);
image.setImageDrawable(drawable);
is referencing an uninitiated variable (image) which is null
My best guess would be that to eliminate said error you'd want to initiate the variable
ImageView image = (ImageView)findViewById(R.id.imageView);
UPDATE** so i did pretty much everything that was said below and still got this error(see new logcat file). Its different though so i dont know how to fix it.**
Ok so im a beginner so i really dont know whats going on. When i try to run this app in the emulator all it is "unfortunately this app has stopped." Ive search all the question similar to this but haven't been able to find an answer. btw this isnt a finished app or really even started, but i want to get it to run before i continue. Heres the log cat file thing.
error opening trace file: No such file or directory (2)
08-19 06:09:04.579: D/AndroidRuntime(1006): Shutting down VM
08-19 06:09:04.599: W/dalvikvm(1006): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
FATAL EXCEPTION: main
android.content.res.Resources$NotFoundException: Resource ID #0x7f080001 type #0x12 is not valid
at android.content.res.Resources.loadXmlResourceParser(Resources.java:2103)
at android.content.res.Resources.getLayout(Resources.java:852)
at android.view.MenuInflater.inflate(MenuInflater.java:107)
at com.nickymilton.testbasebal3.MainActivity.onCreateOptionsMenu(MainActivity.java:22)
at android.app.Activity.onCreatePanelMenu(Activity.java:2476)
at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:393)
at com.android.internal.policy.impl.PhoneWindow.invalidatePanelMenu(PhoneWindow.java:747)
at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:2913)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Now heres the activty_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="#string/EnterHome"
android:textColor="#color/White" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:ems="10"
android:hint="#string/home_team"
android:layout_below="#id/textView1"
android:shadowColor="#color/ICSBlue" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="#string/EnterAway"
android:textColor="#color/White" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:ems="10"
android:hint="#string/away_team"
android:shadowColor="#color/ICSBlue" />
<Button
android:id="#+id/button3"
android:layout_width="115dp"
android:layout_height="wrap_content"
android:layout_below="#id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="#string/Enter" />
<Button
android:id="#+id/button2"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_below="#id/button3"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="#string/Skip" />
</RelativeLayout>
Now the activity_display_message.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/hello_world"
tools:context=".DisplayMessageActivity" />
</RelativeLayout>
Then here the mainActivity.java file
package com.nickymilton.testbasebal3;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.nickymilton.Testbasebal3.MESSAGE";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText1);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
then the second activity DisplayMessageActivity.java
package com.nickymilton.testbasebal3;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
public class DisplayMessageActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
}
And finally the mainfest file
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nickymilton.testbasebal3"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:label="#string/title_activity_display_message" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.nickymilton.testbasebal3.MainActivity" />
</activity>
</application>
</manifest>
So there it is. Someone please help thanks!
There are issues with your XML - you can tell from the line:
Binary XML file line #54: Error inflating class <unknown>
One thing I spotted is that when you declare an android:id attribute, it needs to have a + in it, like this:
android:id="#+id/location"
This is because you're creating an id, not just referring to a pre-existing one defined elsewhere (like you might be with a string, e.g "#string/hello" might be in the values folder).
I've noticed one thing, you've not declared the 'id' values correctly in some of your xml.
android:id="#id/button3"
should be
android:id="#+id/button3"
And like wise for your other id declarations.
You'll notice that in your stack trace it gives you the line number in your xml for the location of the error.
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.nickymilton.testbasebal3/com.nickymilton.testbasebal3.MainActivity}:
android.view.InflateException: Binary XML file line #54: Error inflating class <unknown>
This might be something else. But essentially you have badly formed xml.
Error Two
You need to look through the stack trace backwards to find the source of your error, you will then most likely find the solution yourself.
android.content.res.Resources$NotFoundException: Resource ID #0x7f080001 type #0x12 is not valid
at android.content.res.Resources.loadXmlResourceParser(Resources.java:2103)
at android.content.res.Resources.getLayout(Resources.java:852)
at android.view.MenuInflater.inflate(MenuInflater.java:107)
at com.nickymilton.testbasebal3.MainActivity.onCreateOptionsMenu(MainActivity.java:22)
at android.app.Activity.onCreatePanelMenu(Activity.java:2476)
From the top down you'll get to the line MainActivity.oncreateOptionsMenu()
Above that you'll see that its trying to inflate (your options menu xml), i.e. loadXmlResourceParser()
It doesn't go as far as giving you an xml line number but it does tell you you have an issue with an Resource id not being valid.
You'll need to post your options xml in your question if you want an answer. But i would see if you can work it out your self first. Try commenting out elements and putting them back in to see whats broken. I say this because theres only so much one Stack overflow question should answer.
In the declaration for one of your TextViews you have :
android:textSize="#string/TextSizefifteen"
textSize should be a number or a dimension like:
android:textSize="#dimen/TextSizefifteen"
See what you have at TextSizefifteen and how you declared it(see http://developer.android.com/guide/topics/resources/more-resources.html#Dimension).
For example:
<dimen name="TextSizefifteen">25dp</dimen>