Android included layout shows in preview but not on emulator [duplicate] - java

Hello!
I'm just starting in Android Studio. I searched for a matching question but no joy, please yell out if you've seen this one already!
My main activity has a single button which opens the second activity, the button works and it opens. But the second activity shows as a blank screen instead of the text that should be there.
Apologies for any irrelevant copy/paste!
Manifest:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat.NoActionBar" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".fiveThreeOne"
android:label="#string/title531">
</activity>
</application>
Main activity:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:textColor="#ffdedede"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="fiveThreeOne"
android:textAllCaps="false"
android:id="#+id/open531btn"
android:layout_below="#+id/mainTitle"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="38dp" />
</RelativeLayout>
Button code in main class
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button open531button = (Button) findViewById(R.id.open531btn);
open531button.setOnClickListener(new OnClickListener(){
public void onClick(View v){
startActivity(new Intent(MainActivity.this, fiveThreeOne.class));
}
});
}
Second activity xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="#string/title531"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:editable="false"
android:textSize="35sp"
android:id="#+id/title531"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Thanks!

It sometimes happens when instead of overloading
protected void onCreate(Bundle savedInstanceState) {
you end up overloading
public void onCreate(#Nullable Bundle savedInstanceState, #Nullable PersistableBundle persistentState)
instead.
Make sure the onCreate with only savedInstanceState as a argument is overloaded.

Have you set the layout for your activity in the line setContentView() like this. Here activity_second is the activity layout of my SecondActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
if not then your activity will show up as blank.
Hope this solves your problem.

Check weather you have set the correct layout for the setContentView() method of your second activity.

You can just go to dependencies in build.gradle file and add this line there.. & try.
implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'

In my case, I changed device in Android Virtual Divice Manager and this fix problem

Related

Could not find method in a parent or ancestor Context

Problem
I am getting java.lang.IllegalStateException: Could not find method secondOne(View) in a parent or ancestor Context for android:onClick attribute defined on view class androidx.appcompat.widget.AppCompatButton
What I've done?
In manifest, I have activities:
<activity
android:name=".MainActivity"
android:label="#string/app_name">
</activity>
<activity
android:name=".LeadActivity"
android:label="#string/app_name">
</activity>
<activity
android:name=".MainMenu"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
In game_menu.xml, I have two buttons. First has android:onClick="firstOne" property, second has android:onClick="secondOne" property.
In class MainMenu, which extends AppCompatActivity I have two methods:
public void firstOne(View view) {
Intent intent = new Intent(MainMenu.this, MainActivity.class);
startActivity(intent);
}
public void secondOne(View view) {
Intent intent = new Intent(MainMenu.this, LeadActivity.class);
startActivity(intent);
}
When I tap on the first button, my MainActivity.class runs, as it should.
But when I tap on the second button this error appears. java.lang.IllegalStateException: Could not find method secondOne(View) in a parent or ancestor Context for android:onClick attribute defined on view class androidx.appcompat.widget.AppCompatButton
Please, help. What am I doing wrong?
UPD
full MainMenu class code:
public class MainMenu extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_menu);
//Hide the status bar and the action bar
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
}
public void firstOne(View view) {
Intent intent = new Intent(MainMenu.this, MainActivity.class);
startActivity(intent);
}
public void secondOne(View view) {
Intent intent = new Intent(MainMenu.this, LeadActivity.class);
startActivity(intent);
}}
UPD2
game_menu.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">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="#drawable/sky"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="-16dp" />
<Button
android:id="#+id/button_start"
android:layout_width="175dp"
android:layout_height="76dp"
android:layout_marginTop="200dp"
android:background="#color/black"
android:onClick="firstOne"
android:text="#string/playButtonText"
android:textColor="#color/white"
android:textSize="40sp"
android:textStyle="bold"
app:layout_constraintEnd_toStartOf="#+id/imageView"
app:layout_constraintStart_toEndOf="#+id/imageView"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button_lead"
android:layout_width="175dp"
android:layout_height="76dp"
android:layout_marginTop="312dp"
android:background="#color/black"
android:onClick="secondOne"
android:text="#string/leaderboardButtonText"
android:textColor="#color/white"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintEnd_toStartOf="#+id/imageView"
app:layout_constraintStart_toEndOf="#+id/imageView"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
That was terrible one. I've spent a lot of time on this, but the answer was simple. Always care about onCreate method and actually setContentView(R.layout.); line. I've been copy-pasting and tried to create classes with the same layout.

My app keeps force closing when using 2 intents

Why do my android apps keep closing when using 2 intent? when I delete one of them, it's work. especially if I delete the "Reg" Button in the java files.
Thanks
XML Files:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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=".LoginAct">
<TextView
android:id="#+id/daftar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="#string/daftar"
android:textAlignment="center"
android:textColor="#color/Linktext"
android:clickable="true"
android:focusable="true"
android:layout_marginTop="10dp">
</TextView>
<Button
android:id="#+id/pass"
android:layout_width="wrap_content"
android:layout_height="23dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="25dp"
android:background="#color/colorPrimaryDark"
android:clickable="true"
android:focusable="true"
android:text="#string/lewat"
android:textColor="#color/textwhite" />
Java Files (If I deleted the "Reg" Button from this file, the app is working, but otherwise it will force close after the splash screen):
package com.soerja.ngalamhistory;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class LoginAct extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_login);
Button Pass = (Button) findViewById(R.id.pass);
Button Reg = (Button) findViewById(R.id.daftar);
Pass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginAct.this, MainActivity.class);
startActivity(intent);
}
});
Reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginAct.this, RegisAct.class);
startActivity(intent);
}
});
}
}
AndroidManifest Files:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.soerja.ngalamhistory">
<application
android:allowBackup="true"
android:icon="#mipmap/logo"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".SplashAct"
android:theme="#style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".LoginAct"
android:label="#string/applogin"
android:theme="#style/LogTheme"></activity>
<activity
android:name=".MainActivity"
android:label="#string/home"
android:theme="#style/AppTheme"></activity>
<activity android:name=".RegisAct"
android:label="#string/appdaftar"
android:theme="#style/LogTheme"></activity>
</application>
</manifest>
I would really appreciate your help because this is my school project :)
You are casting a TextView into a Button. Probably the problem is a invalid cast exception.
In XML, you define the "daftar" as a TextView, but in java you are trying to use it as a Button.
Change it
Button Reg = (Button) findViewById(R.id.daftar);
To it
TextView Reg = (TextView) findViewById(R.id.daftar);
Or change your XML implamentation, defining "daftar" as a Button
here you are using your text view id
android:id="#+id/daftar"
as a reference to declaring button
Button Reg = (Button) findViewById(R.id.daftar);
so i think ,that may be the reason for crash
try this method :
add this in your text xml code:
android:onClick="daftar"
add for java class use this:
public void daftar(View v)
{
Intent intent = new Intent(this, RegisAct.class);
startActivity(intent);
}
and remove the old java code you used for this text view:
i hope this helps.

Live updating of ListView with ArrayAdapter

Beginner with Android here.
I have a MainActivity, which generates a String and send it to an ArrayList (singleton pattern). I also have a HistoryActivity, which will display the contents of the ArrayList.
I have the ArrayList being sent to an Array, and activity_history has a ListView with an ArrayAdapter in HistoryActivity. There are buttons on activity_history that will remove an item from the ArrayList (and recreate the Array) and clear the entire ArrayList. However, the ListView does not update automatically (the activity has to be closed and reopened).
I'm currently trying ((BaseAdapter) historyView.getAdapter()).notifyDataSetChanged(); (as seen below), but it is not working. Any advice or guidance would be great.
HistoryActivity.java
public class HistoryActivity extends AppCompatActivity {
DataStorage history = DataStorage.getDataStorage();
String[] historyArray;
private ListView historyView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
}
#Override
protected void onStart() {
super.onStart();
historyView = (ListView) findViewById(R.id.history);
historyArray = history.getHistory().toArray(new String[history.getHistory().size()]);
historyView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, historyArray));
}
/**
* Clear all of history
*/
public void clearHist(View view) {
history.getHistory().clear();
historyArray = history.getHistory().toArray(new String[history.getHistory().size()]);
((BaseAdapter) historyView.getAdapter()).notifyDataSetChanged();
}
/**
* Remove last entry to history
*/
public void clearOne(View view) {
history.getHistory().remove(0);
historyArray = history.getHistory().toArray(new String[history.getHistory().size()]);
((BaseAdapter) historyView.getAdapter()).notifyDataSetChanged();
}
/**
* Change to main view
*/
public void sendMessage(View view) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
activity_history.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="wrap_content"
android:layout_height="wrap_content"
android:background="#000000"
tools:context="com.mattbraddock.mbcgen.HistoryActivity">
<LinearLayout
android:id="#+id/buttons"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="clearOne"
android:text="Remove Last" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="sendMessage"
android:text="Return" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="clearHist"
android:text="Clear All" />
</LinearLayout>
<ListView
android:id="#+id/history"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/buttons"
android:layout_alignParentTop="true"
android:paddingBottom="16dp" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mattbraddock.mbcgen">
<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"
android:screenOrientation="portrait"
android:theme="#style/Theme.AppCompat.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".HistoryActivity"
android:label="Card History"
android:theme="#style/Theme.AppCompat.Dialog"
android:screenOrientation="portrait"></activity>
<!-- ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information. -->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
The problem is that each time you use
historyArray = history.getHistory().toArray(new String[history.getHistory().size()]);
you change the reference of the historyArray variable to another newly created array, but the adapter still holds a reference to the old array which you passed to the adapter constructor.
My suggestion would be to replace you array with an ArrayList and use clear(), add(), and addAll() methods. Also avoid reassigning the historyArray if you want to keep the reference to the data of the adapter, and for notifyDataSetChanged() to work.
I would save a reference to the adapter and use an Arraylist instead of an array.
historyView = (ListView) findViewById(R.id.history);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, history.getHistory());
historyView.setAdapter(adapter);
Then when you want to update the view, then just modify the adapter.
adapter.clear();
Or
adapter.remove(0);

Android Application Force Crash at main Activity Launch

I just started working on this application I feel like I've done everything right (This isn't my first application I've been working on) but when I try to run it It crashes?? It gives me no errors.
Here's the code from the main activity, then from manufest and then from the xml layout.
`
package com.theory.game;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class GameTheoryActivity extends Activity implements View.OnClickListener{
Button play, settings;
int i;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
play.setOnClickListener(this);
settings.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.bPlay:
Random irand = new Random();
i = irand.nextInt(4);
switch(i){
case 0:
Intent GoMillionair = new Intent(GameTheoryActivity.this, millionair.class);
startActivity(GoMillionair);
return;
case 1:
return;
case 2:
return;
case 3:
return;
}
return;
case R.id.bSettings:
return;
}
}
}
Manufest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.theory.game"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<application >
<activity
android:name=".GameTheoryActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".millionair" >
<intent-filter>
<action android:name="com.theory.game.MILLIONAIR" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/backgroundimage"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="390dp"
android:orientation="vertical" >
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/bPlay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.38"
android:background="#drawable/play" />
<Button
android:id="#+id/bSettings"
android:layout_width="match_parent"
android:layout_height="58dp"
android:layout_weight="0.36"
android:background="#drawable/settings" />
</LinearLayout>
</LinearLayout>
`
And I have another class called millionair which is just a normal class nothing much, nothing wrong there I guess. Please check whats up with this and let me know why my application wont start saying it "has stopped working".. Thanks
My guess is that you are getting a NullPointerException because both play and settings objects are null.
change your onCreate() to look like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
play = (Button)findViewById(R.id.bPlay);
settings = (Button)findViewById(R.id.bSettings);
play.setOnClickListener(this);
settings.setOnClickListener(this);
}
You'll probably get a NullPointerException because you forgot to assign the buttons to your fields (Button play, settings;).
Here's an example on how to assign them:
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
play = (Button) findViewById(R.id.bPlay);
settings = (Button) findViewById(R.id.bSettings);
}
Looks like play and settings will both be null when you try to use then during the onCreate() method:
play.setOnClickListener(this);
settings.setOnClickListener(this);
make sure to initiate them like so:
play = (Button)findViewById(R.id.bPlay);
settings = (Button)findViewById(R.id.bSettings)
play.setOnClickListener(this);
settings.setOnClickListener(this);

Display soft keyboard automatically on a dialog activity

I have a simple Activity that uses a android:theme="#android:style/Theme.Dialog" in the manifest.
My activity consists of an EditText, 2 Buttons, and a TextView. It is nothing more than a box for the user to enter in a name and press OK/Cancel.
I just want to focus the EditText and have the soft keyboard automatically show when the Activity is started. I've read countless posts about this but I just can't seem to get it to work. When the activity starts the blinking cursor appears in the EditText, but the keyboard won't show until I click inside it.
Here is my Activity:
public class Finalize extends Activity {
private EditText mEditName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.finalize_dialog);
mEditName = (EditText) findViewById(R.id.file_name_edit);
mEditName.setFocusable(true);
mEditName.requestFocus();
mEditName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
});
}
}
I've also tried this in onCreate:
InputMethodManager mgr = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
mgr.showSoftInput(mEditName, 0);
Edit: My manifest for reference
<activity class=".Finalize"
android:name=".Finalize"
android:label="#string/file_name_title"
android:theme="#android:style/Theme.Dialog"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysVisible">
</activity>
The following should work. Go to your manifest and update your activity line with the android:windowSoftInputMode attribute.
<activity android:name=".Finalize"
android:windowSoftInputMode="stateAlwaysVisible">
...
</activity>
See the following documentation page for more details on the different parameters that can be passed into this attribute.
I tested the above and it works fine for me. Here is my terribly simple example.
Code:
public class DialogActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<EditText android:id="#+id/edit_text_test"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Manifest:
<activity android:name=".DialogActivity"
android:windowSoftInputMode="stateAlwaysVisible"
android:label="#string/app_name"
android:theme="#android:style/Theme.Dialog">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Try this its work for me
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

Categories