I am developing an Android Application.I have create an another XML file for layout:-
Chatfile.XML
<?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="#color/suitableblack"
android:orientation="vertical">
<Button
android:id="#+id/signout"
android:layout_width="422dp"
android:layout_height="64dp"
android:text="Button" />
<ListView
android:id="#+id/Msgdisplay"
android:layout_width="374dp"
android:layout_height="593dp"
android:layout_below="#id/signout"
android:layout_marginLeft="20dp"
android:forceDarkAllowed="false" />
<LinearLayout
android:layout_width="390dp"
android:layout_height="83dp"
android:layout_below="#id/Msgdisplay"
android:layout_marginLeft="20dp"
android:orientation="horizontal">
<EditText
android:id="#+id/Msginput"
android:layout_width="482dp"
android:layout_height="67dp"
android:layout_weight="1"
android:ems="10"
android:inputType="textPersonName"
android:text="Name" />
<Button
android:id="#+id/Sendbtn"
android:layout_width="match_parent"
android:layout_height="68dp"
android:layout_weight="1"
android:text="Button" />
</LinearLayout>
So I want to access the button with ID-Sendbtn in my MainActivity.java file and the code for that part is here:-
Button sendbtn=findViewById(R.id.Sendbtn);
sendbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg=message.getText().toString();
if(msg.length()==0)
{
Toast.makeText(getApplicationContext(),"Blank message detected",Toast.LENGTH_SHORT);
}
else
{
FirebaseDatabase.getInstance().getReference().push().setValue(new chatcolumns(msg,FirebaseAuth.getInstance().getCurrentUser().getDisplayName()));
}
}
});
But whenever I run this code it gives me following error:-
Process: com.example.anochatzone, PID: 18398
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anochatzone/com.example.anochatzone.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.anochatzone.MainActivity.onCreate(MainActivity.java:87)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
My main question is how can I access the button from chatfile.xml in my MainActivity.java
Update
MainActivity.java
package com.example.anochatzone;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.*;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth authenticate;
private String email_str="";
private String password_str="";
private EditText email,password,message;
private Button loginbtn,resetbtn,sendbtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title
Objects.requireNonNull(getSupportActionBar()).hide(); // hide the title bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN); //enable full screen
setContentView(R.layout.activity_main);
email=findViewById(R.id.EmailInput);
password=findViewById(R.id.Passwordinput);
message=findViewById(R.id.Msginput);
loginbtn=findViewById(R.id.Loginbtn);
resetbtn= findViewById(R.id.ResetBtn);
sendbtn=findViewById(R.id.Sendbtn);
authenticate=FirebaseAuth.getInstance();
loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Please wait while we are processing your request........",Toast.LENGTH_SHORT).show();
email_str=email.getText().toString();
password_str=password.getText().toString();
if(email_str.length()==0||password_str.length()==0)
{
Toast.makeText(getBaseContext(),"Please check email and password",Toast.LENGTH_LONG).show();
}
else
{
authenticate.signInWithEmailAndPassword(email_str,password_str).addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Log.d("User display name" , FirebaseAuth . getInstance() . getCurrentUser().getDisplayName());
Toast.makeText(getApplicationContext(),"Welcome "+email_str+" you have sucessfully logged in",Toast.LENGTH_LONG).show();
setContentView(R.layout.chatfile);
}
else
{
Toast.makeText(getApplicationContext(),"Failed to sign in .Please check internet connection or try again later",Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
sendbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg=message.getText().toString();
if(msg.length()==0)
{
Toast.makeText(getApplicationContext(),"Blank message detected",Toast.LENGTH_SHORT);
}
else
{
FirebaseDatabase.getInstance().getReference().push().setValue(new chatcolumns(msg,FirebaseAuth.getInstance().getCurrentUser().getDisplayName())) ;
}
}
});
}
}
According to your purpose, when you launch or start the app, login page will appear. If login success, the chat page will appear.
So, you need to separate your activity to two activity such as LoginActivity as a launcher activity and ChatActivity(MainActivity) as follow.
For login page, may be one activity_login.xml and LoginActivity.java
In activity_login.xml
<!-- You need one button for login action. -->
<Button
android:id="#+id/btnLogin"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Login"
/>
In LoginActivity.java
#Override protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// This line is important to access your resource id
setContentView(R.layout.activity_login);
findViewById(R.id.btnLogin).setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
// isLoginSuccess is an example condition for you
if (isLoginSuccess) {
// Navigate to mainpage
startActivity(new Intent(LoginActivity.this, MainActivity.class));
// Terminate the login activity for one time show.
finish();
} else {
// TODO: Try again implementations
}
}
});
}
For main page, like above, you need one activity_main.xml and one MainActivity.java
In Chatfile.xml
// other codes....
<Button
android:id="#+id/Sendbtn"
android:layout_width="match_parent"
android:layout_height="68dp"
android:layout_weight="1"
android:text="Button" />
// other codes....
In MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// This line is important for your 'chatfile.xml'
setContentView(R.layout.Chatfile);
// You can access id `SendBtn` right now.
findViewById(R.id.SendBtn).setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
// TODO: implement something here.
}
});
}
In AndroidManifest.xml, you need to change launcher activity as LoginActivity.
<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=".LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"/>
</application>
According to my solution, you don't have to consider that what the ui element should be hidden when login success or fail.
If anything wrong in my answer, please let me free to know.
Put below code in your activity_main.xml
<include
layout="#layout/chatfile"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Now you can access the button in Your MainActivity.
Related
This question already has answers here:
AndroidStudio Cannot Find Layout
(2 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I have three layouts, activity_main, activity_login and activity_home. When in the LoginActivity or HomeActivity java file, I get the error "cannot resolve symbol activity_(home or login). I have tried deleting it and creating a new one by clicking "alt+enter" on the error but still did not work. I'm thinking I have to add something to the AndroidManifest but we never went over that in class. If anyone could help that'd be great. Thanks.
Here is my activity_main.xml (note: my activity_login and activity_main are pretty much the same exact code just different #+id's):
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/emailEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"
android:ems="10"
android:hint="email"
android:inputType="textEmailAddress"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/passwordEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="password"
android:inputType="textPassword"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/emailEditText"
app:layout_constraintVertical_bias="0.052" />
<ImageView
android:id="#+id/imageView"
android:layout_width="356dp"
android:layout_height="235dp"
android:cropToPadding="false"
android:scaleType="fitStart"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.032"
app:srcCompat="#drawable/guitar" />
<Button
android:id="#+id/signUpButton"
android:layout_width="133dp"
android:layout_height="73dp"
android:text="Sign Up!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/passwordEditText"
app:layout_constraintVertical_bias="0.54" />
<TextView
android:id="#+id/signInTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Already have an account? Sign in here!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/signUpButton" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here is my LoginActivity.java:
package com.antonioocasio.finalproject;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class LoginActivity extends AppCompatActivity {
public EditText emailIdEditText, passwordEditText;
private FirebaseAuth.AuthStateListener firebaseAuthStateListener;
Button signInBtn;
TextView signUpTextView;
FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth = FirebaseAuth.getInstance();
emailIdEditText = findViewById(R.id.emailEditText2);
passwordEditText = findViewById(R.id.passwordEditText);
signInBtn = findViewById(R.id.signInButton);
signUpTextView = findViewById(R.id.signUpTextView);
firebaseAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if(firebaseUser != null){
Toast.makeText(LoginActivity.this, "You are logged in", Toast.LENGTH_LONG).show();
Intent i = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(i);
} else {
Toast.makeText(LoginActivity.this, "Please Login", Toast.LENGTH_LONG).show();
}
}
};
signInBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = emailIdEditText.getText().toString();
String password = passwordEditText.getText().toString();
if(email.isEmpty()){
Toast.makeText(getApplicationContext(), "Error: Email must be entered.", Toast.LENGTH_LONG).show();
emailIdEditText.requestFocus();
} else if(password.isEmpty()){
Toast.makeText(getApplicationContext(), "Error: Password must be entered.", Toast.LENGTH_LONG).show();
passwordEditText.requestFocus();
} else if(email.isEmpty() && password.isEmpty()){
Toast.makeText(getApplicationContext(), "Error:Both fields must be entered.", Toast.LENGTH_LONG).show();
} else if(!(email.isEmpty() && password.isEmpty())){
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(getApplicationContext(), "Login Error, Please try again.", Toast.LENGTH_LONG).show();
} else {
Intent intToHome = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(intToHome);
}
}
});
} else {
Toast.makeText(getApplicationContext(), "Error Occurred!", Toast.LENGTH_LONG).show();
}
}
});
signUpTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intSignUp = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intSignUp);
}
});
}
#Override
protected void onStart() {
super.onStart();
firebaseAuth.addAuthStateListener(firebaseAuthStateListener);
}
}
Finally, here is my AndroidMainfiest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.antonioocasio.finalproject">
<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=".HomeActivity"></activity>
<activity android:name=".LoginActivity" />
<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>
Again, I'm really not sure what the problem could be. I am at a complete loss.
EDIT:
This error finally popped up. I really don't know where to start since there is so much to it:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.antonioocasio.finalproject, PID: 17363
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.antonioocasio.finalproject/com.antonioocasio.finalproject.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.antonioocasio.finalproject.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
This is the error report whenever I launch the app it crashes and says
Unfortunately, {app-name} has stopped
java.lang.RuntimeException:
at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2339)
at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2413)
at android.app.ActivityThread.access$800 (ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1317)
at android.os.Handler.dispatchMessage (Handler.java:102)
at android.os.Looper.loop (Looper.java:135)
at android.app.ActivityThread.main (ActivityThread.java:5343)
at java.lang.reflect.Method.invoke (Native Method)
at java.lang.reflect.Method.invoke (Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:700)
Caused by: android.view.InflateException:
at android.view.LayoutInflater.createViewFromTag (LayoutInflater.java:763)
at android.view.LayoutInflater.rInflate (LayoutInflater.java:806)
at android.view.LayoutInflater.inflate (LayoutInflater.java:504)
at android.view.LayoutInflater.inflate (LayoutInflater.java:414)
at android.view.LayoutInflater.inflate (LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView (AppCompatDelegateImplV9.java:287)
at android.support.v7.app.AppCompatActivity.setContentView (AppCompatActivity.java:139)
at com.khokhar.yousaf.cipher.Splash.onCreate (Splash.java:15)
at android.app.Activity.performCreate (Activity.java:6010)
at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1129)
at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2292)
Caused by: android.content.res.Resources$NotFoundException:
at android.content.res.Resources.loadDrawableForCookie (Resources.java:2444)
at android.content.res.Resources.loadDrawable (Resources.java:2384)
at android.content.res.TypedArray.getDrawable (TypedArray.java:749)
at android.view.View.<init> (View.java:3742)
at android.widget.ImageView.<init> (ImageView.java:149)
at android.widget.ImageView.<init> (ImageView.java:145)
at android.support.v7.widget.AppCompatImageView.<init> (AppCompatImageView.java:71)
at android.support.v7.widget.AppCompatImageView.<init> (AppCompatImageView.java:67)
at android.support.v7.app.AppCompatViewInflater.createImageView (AppCompatViewInflater.java:181)
at android.support.v7.app.AppCompatViewInflater.createView (AppCompatViewInflater.java:105)
at android.support.v7.app.AppCompatDelegateImplV9.createView (AppCompatDelegateImplV9.java:1035)
at android.support.v7.app.AppCompatDelegateImplV9.onCreateView (AppCompatDelegateImplV9.java:1092)
at android.view.LayoutInflater.createViewFromTag (LayoutInflater.java:725)
This is my Splash Screen coding
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Window;
public class Splash extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_splash);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
//thread for splash screen running
Thread logoTimer = new Thread() {
public void run() {
try {
sleep(2500);
} catch (InterruptedException e) {
Log.d("Exception", "Exception" + e);
} finally {
startActivity(new Intent(Splash.this, MainActivity.class));
}
finish();
}
};
logoTimer.start();
}
}
And this 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/splashScreen"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/colorPrimary"
android:orientation="vertical"
tools:context="com.khokhar.yousaf.cipher.Splash">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#drawable/ic_launcher_foreground"
android:contentDescription="#string/app_name"
android:scaleType="fitXY"
android:src="#drawable/mediumload" />
</RelativeLayout>
The drawable image I used is 600x1024 PNG
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.khokhar.yousaf.cipher">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:fullBackupContent="true"
android:hardwareAccelerated="true"
android:icon="#drawable/cee"
android:label="#string/app_name"
android:roundIcon="#drawable/cee"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity"
android:theme="#style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!-- Accepts URIs that begin with "java-lang-programming://android-app-google-plus-demo"-->
<data
android:host="cipherengineers"
android:scheme="android-app-cipher-engineers" />
</intent-filter>
</activity>
<activity android:name=".Splash"
android:theme="#style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
My MainActivity is basically webview
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
ProgressBar progressBar;
WebView webView;
String url="https://website/";
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
webView = (WebView) findViewById(R.id.webView);
textView = (TextView) findViewById(R.id.textView1212);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
textView.setText(progress + "");
}
#Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
WebView newWebView = new WebView(MainActivity.this);
newWebView.getSettings().setJavaScriptEnabled(true);
newWebView.getSettings().setSupportZoom(true);
newWebView.getSettings().setBuiltInZoomControls(true);
newWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
newWebView.getSettings().setSupportMultipleWindows(true);
view.addView(newWebView);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(newWebView);
resultMsg.sendToTarget();
newWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
return true;
}
});
webView.setWebViewClient(new MyWebViewClient());
WebSettings browserSetting = webView.getSettings();
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
browserSetting.setJavaScriptCanOpenWindowsAutomatically(true);
browserSetting.setJavaScriptEnabled(true);
browserSetting.setLoadWithOverviewMode(true);
browserSetting.setSupportMultipleWindows(true);
browserSetting.setDatabaseEnabled(true);
browserSetting.setAppCacheEnabled(true);
browserSetting.setDomStorageEnabled(true);
browserSetting.setDomStorageEnabled(true);
browserSetting.setGeolocationEnabled(true);
browserSetting.setSaveFormData(false);
browserSetting.setUseWideViewPort(true);
browserSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
browserSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
browserSetting.setDomStorageEnabled(true);
if (android.os.Build.VERSION.SDK_INT >= 21) {
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
}else {
CookieManager.getInstance().setAcceptCookie(true);
}
webView.loadUrl(url);
}
private class MyWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressBar.setVisibility(View.INVISIBLE);
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
public void onBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
// set title
alertDialogBuilder.setTitle("Exit");
// set dialog message
alertDialogBuilder
.setMessage("Are You Sure?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
MainActivity.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.GRAY));
}
}
I removed background from Splash Screen XML and nothing worked
MainActivity XML
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:background="#drawable/loading_screen"
android:orientation="vertical"
tools:context="com.khokhar.yousaf.cipher.MainActivity">
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_marginTop="218dp"
android:progressTint="?android:attr/fastScrollTextColor"
android:visibility="invisible" />
<TextView
android:id="#+id/textView1212"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="23dp"
android:textColor="#android:color/holo_red_dark"
android:textSize="13sp"
android:textStyle="bold|italic" />
<WebView
android:id="#+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:animationCache="true"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="41dp" />
</RelativeLayout>
I can't figure it out.
Removing the background from ImageView
The reason is lower versions are not able to find ic_launcher_foreground in the drawable directory which actually exists in drawable-v24.
Remove the background image and write your ImageView like this
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:contentDescription="#string/app_name"
android:scaleType="fitXY"
android:src="#drawable/mediumload" />
you cant start a new Activity on Background Thread.. since you run new Thread and inside you start a new Activity it will crash..
2 solutions : declare Handler outside the Thread
Handler handler = new Handler();
inside the thread run
handler.post(new Runnable() { public void run() { startActivity(..) } });
or use function :
RunOnUiThread(new Runnable() { public void run() { startActivity(...) } );
I'm trying to store the users input from a text field in shared preferences and use that input in a webview link.
Here's what I have so far;
LoginActivity.java
package com.example.app;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.content.Intent;
public class LoginActivity extends Activity {
EditText subdomain;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
subdomain = (EditText) findViewById(R.id.subdomain);
Button btn=(Button)findViewById(R.id.sign_in_button);
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent myIntent = new Intent(LoginActivity.this,
MainActivity.class);
LoginActivity.this.startActivity(myIntent);
}
});
}
public void saveInfo (View view) {
SharedPreferences sharedPref = getSharedPreferences("spfile",
Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("name", YourSchool.getText().toString());
editor.commit();
}
}
MainActivity.java
package com.example.app;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
// Force links and redirects to open in the WebView instead of in a
browser
mWebView.setWebViewClient(new WebViewClient());
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// Use remote resource
mWebView.loadUrl("https://"+client_subdomain+".domain.co.uk/texts");
// Stop local links and redirects from opening in browser instead
of WebView
mWebView.setWebViewClient(new MyAppWebViewClient());
}
public void displayData (View view) {
SharedPreferences sharedPref = getSharedPreferences("spfile",
Activity.MODE_PRIVATE);
String client_subdomain = sharedPref.getString("name", "");
}
// Prevent the back-button from closing the app
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
#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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_login.xml
<LinearLayout
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:gravity="center_horizontal"
android:orientation="vertical"
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.app.LoginActivity">
<LinearLayout
android:id="#+id/email_login_form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="#+id/YourSchool"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Your school"
android:maxLines="1"
android:singleLine="true" />
<Button
android:id="#+id/sign_in_button"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onClick="webView"
android:text="SIGN IN"
android:textStyle="bold" />
</LinearLayout>
</ScrollView>
</LinearLayout>
activity_main.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"
tools:context=".MainActivity">
<WebView
android:id="#+id/activity_main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app">
<uses-permission android:name="android.permission.INTERNET" />
<!-- To auto-complete the email text field in the login form with the
user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen">
<activity
android:name=".MainActivity"
android:label="#string/app_name"></activity>
<activity
android:name=".LoginActivity"
android:label="#string/title_activity_login">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
</application>
</manifest>
My problem is that the client_subdomain is flagged as red in the MainActivity.java and when I try to build the project, I get the error: cannot find symbol variable client_subdomain
I think it's probably something small that I've missed out but any help would be greatly appreciated.
Many thanks,
Sam
Its because haven't declared "client_subdomain" as a variable within scope of onCreate
why don't you try changing displayData to
public String displayData () {
SharedPreferences sharedPref = getSharedPreferences("spfile",
Activity.MODE_PRIVATE);
return sharedPref.getString("name", "");
}
and in onCreate of the Main Activity
...
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// Use remote resource
mWebView.loadUrl("https://"+displayData()+".domain.co.uk/texts");
...
Also, I don't see you ever calling "saveInfo" anywhere in your Login Activity. As well, you should probably change the function too. You aren't grabbing the text from the EditText correctly (whatever YourSchool) is
public void saveInfo() {
SharedPreferences sharedPref = getSharedPreferences("spfile", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("name", subdomain.getText().toString());
editor.commit();
}
And this will be what your onCreate should have,
protected void onCreate(Bundle savedInstanceState) {
...
btn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
saveInfo();
Intent myIntent = new Intent(LoginActivity.this, MainActivity.class);
LoginActivity.this.startActivity(myIntent);
}
});
...
}
firstly sorry for my bad english, I hope you can understand me.
I'm making an android app on Android Studio. And I'm here because my app crashes while I start the Third Activity.
Well, I have three activies. Going to second from the first and going to first from second works well, But when I tried to go to Third from Second, I press the Button to go to Third Activity, and my app crashes, it says "Unfortunately, Project Saya has stopped."
Here's my 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: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.missmagius.projectsaya.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Merhaba, Project Saya'ya hoşgeldiniz! Başlamadan önce sorun yaşamamak için lütfen talimatları gözden geçirin. İyi eğlenceler!"
android:id="#+id/textView"
android:enabled="false"
android:textColor="#color/abc_input_method_navigation_guard" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Talimatlar"
android:id="#+id/buttonActOne"
android:layout_marginTop="29dp"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
Here's MainActivity.java
package com.missmagius.projectsaya;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnOne =(Button)findViewById(R.id.buttonActOne);
btnOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(getApplicationContext(),ActivityTwo.class);
startActivity(intent);
}
});
}
}
Here's activity_two.xml
package com.missmagius.projectsaya;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnOne =(Button)findViewById(R.id.buttonActOne);
btnOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(getApplicationContext(),ActivityTwo.class);
startActivity(intent);
}
});
}
}
Here's ActivityTwo.java
package com.missmagius.projectsaya;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class ActivityTwo extends AppCompatActivity {
Button btnTwo;
Button getBtnTwo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
Button btnTwo =(Button)findViewById(R.id.buttonActTwo);
Button btnThree=(Button)findViewById(R.id.buttonActThree);
btnTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent2 = new Intent(ActivityTwo.this,MainActivity.class);
startActivity(intent2);
}
});
btnThree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent4 = new Intent(ActivityTwo.this,SpeechActivity.class);
startActivity(intent4);
}
});
}
}
Here's activity_speech.xml(Third Activity)
<?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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.missmagius.projectsaya.SpeechActivity">
<TextView
android:id="#+id/txtKGiris"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:textSize="26sp"
android:textStyle="normal"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="60dp"
android:gravity="center"
android:orientation="vertical" >
<ImageButton
android:id="#+id/btnKonus"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="#null"
android:src="#+id/micc" />
</LinearLayout>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tap_on_mic"
android:textSize="15dp"
android:textStyle="normal"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Here's SpeechActivity.java
package com.missmagius.projectsaya;
import android.content.Intent;
import android.speech.RecognizerIntent;
import android.os.Bundle;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Locale;
public class SpeechActivity extends Activity {
private TextView txtKGiris;
private ImageButton btnKonus;
private final int REQ_CODE_SPEECH_INPUT = 100;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speech);
txtKGiris = (TextView) findViewById(R.id.txtKGiris);
btnKonus = (ImageButton) findViewById(R.id.btnKonus);
// action bar’ı gizle
getActionBar().hide();
btnKonus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
promptSpeechInput();
}
});
}
/**
* Google konuşma girişi diyalogunu gösterme
* */
private void promptSpeechInput() {
Intent intent3 = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent3.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent3.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent3.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(intent3, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
/**
* Konuşma girişi kabulü.
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtKGiris.setText(result.get(0));
}
break;
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Here's AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.missmagius.projectsaya">
<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=".ActivityTwo" />
<activity android:name=".SpeechActivity"></activity>
</application>
</manifest>
Here's Strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Project Saya</string>
<string name="action_settings">Ayarlar</string>
<string name="hello_world">Merhaba Dünya!</string>
<string name="speech_prompt">Bana bir şeyler söyle.</string>
<string name="speech_not_supported">Çok Üzgünüm! Senin sürümün buna yetmiyor…</string>
<string name="tap_on_mic">Mikrofona basıp konuşabilirsin.</string>
</resources>
My Error Log:
04-27 09:55:26.880 6606-6606/com.missmagius.projectsaya E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.missmagius.projectsaya, PID: 6606
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.missmagius.projectsaya/com.missmagius.projectsaya.SpeechActivity}: android.view.InflateException: Binary XML file line #37: Error inflating class ImageButton
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: android.view.InflateException: Binary XML file line #37: Error inflating class ImageButton
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:809)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:276)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:136)
at com.missmagius.projectsaya.SpeechActivity.onCreate(SpeechActivity.java:27)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: android.content.res.Resources$NotFoundException: Resource "com.missmagius.projectsaya:id/micc" (7f0c0054) is not a Drawable (color or path): TypedValue{t=0x12/d=0x0 a=2 r=0x7f0c0054}
at android.content.res.Resources.loadDrawableForCookie(Resources.java:2390)
at android.content.res.Resources.loadDrawable(Resources.java:2330)
at android.content.res.TypedArray.getDrawable(TypedArray.java:749)
at android.widget.ImageView.<init>(ImageView.java:146)
at android.widget.ImageButton.<init>(ImageButton.java:86)
at android.widget.ImageButton.<init>(ImageButton.java:82)
at android.support.v7.widget.AppCompatImageButton.<init>(AppCompatImageButton.java:57)
at android.support.v7.widget.AppCompatImageButton.<init>(AppCompatImageButton.java:53)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:114)
at android.support.v7.app.AppCompatDelegateImplV7.createView(AppCompatDelegateImplV7.java:972)
at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(AppCompatDelegateImplV7.java:1030)
at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:725)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:809)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:276)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:136)
at com.missmagius.projectsaya.SpeechActivity.onCreate(SpeechActivity.java:27)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
That's it. I don't know where did I make mistake. I need your help. Thanks.
Change android:src="#+id/micc" to android:src="#drawable/micc" /> in ImageButton. It's causing the problem.
Change the following code
**
Intent intent=new Intent(getApplicationContext(),ActivityTwo.class);
startActivity(intent);
**
To :
**
Intent intent=new Intent(MainActivity.this,ActivityTwo.class);
startActivity(intent);
**
Application contexts are not allowed to start Activities unless the Intent contains the FLAG_ACTIVITY_NEW_TASK flag.
Simply change (at least)
Intent intent=new Intent(getApplicationContext(),ActivityTwo.class);
startActivity(intent);
To :
Intent intent=new Intent(MainActivity.this,ActivityTwo.class);
startActivity(intent);
Inside the clickListener in your MainActivity
You missed to finish your old activity just add finish() after startActivity()
so this is the code:
startActivity(i);
finish();
I am currently trying to develop a simple feature for switching from one page to another but every time I launch the app it crashes.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Screen One......"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/scan"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Click me to another screen" />
</LinearLayout>
MainActivity.java
package com.example.mdpmk1;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addListenerOnButton();
}
public void addListenerOnButton() {
final Context context = this;
button = (Button) findViewById(R.id.scan);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, ScanScreen.class);
startActivity(intent);
}
});
}
}
ScanScreen.java
package com.example.mdpmk1;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
public class ScanScreen extends Activity {
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scan_screen);
}
}
scan_screen.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="You have done it!!"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Im quite new to this sort of stuff but i am doing an app for my major at school and would like to have it actually working. Any help would be lovely. Thanks
You forgot to write following statement in your MainActivity's onCreate() method,
setContentView(R.layout.activity_main);
Write here,
public class MainActivity extends Activity
{
Button button;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // You forgot this line
addListenerOnButton();
}
Also change following line of code,
public void onClick(View arg0)
{
Intent intent = new Intent( MainActivity.this, ScanScreen.class ); // Change here
startActivity(intent);
}
Try editing intent statement in class MainActivity to:
Intent intent = new Intent(MainActivity.this, ScanScreen.class);
startActivity(intent);
You must also add:
setContentView(R.layout.activity_main);
in your ActivityMain class onCreate function to set a view.
setContentView(R.your_layout) doesnt exists in your MainActivity's onCreate(). Try providing your activity a layout.
In your MainActivity onCreate you need to add
setContentView(R.layout.activity_main);
First of all, add SetContentView(R.layout.activity_main) in your MainActivity.OnCreate method befor call to addListenerOnButton.
then be sure that you add your activities entries in your manifest.xml and make MainActivity as your Main Application Activity, like below:
<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=".ScanScreen"/>