How to 'link' an activity to a java class in Android Studio - java

So, I'm trying to wrap my head around Android Studio, but I find something very confusing. When you make a new activity it also makes a Java class, yet coding anything into that java class doesn't seem to do anything. Yet coding something into the MainActivity does.
Example names
MainActivity
SecondActivity
main_activity
second_activity
Adding an onClick event for a (Button for example) in second_activity, it checks the MainActivity class for the pubic void onClickName(){ } rather than the SecondActivity class. Is there something somewhere that I have to change?
<?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">
<EditText
android:layout_width="match_parent"
android:layout_height="40dp"
android:text=""
android:hint="Player name here"
android:layout_alignParentTop="true"
android:id="#+id/txtName"
android:layout_toStartOf="#+id/btnAddPlayer" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back to Main menu"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:onClick="backToMain"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spnCharacters"
android:layout_below="#+id/txtName"
android:layout_marginTop="56dp"
android:layout_alignParentEnd="true"
android:background="#drawable/bg_key"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Player"
android:id="#+id/btnAddPlayer"
android:layout_alignBottom="#+id/txtName"
android:layout_alignParentEnd="true"
android:onClick="addPlayer"/>
Yet neither addPlayer nor backToMain in SecondActivity does nothing, yet if in MainActivity they do whatever I've coded in
SecondActivity onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
}

\
make sure that the Java file is connected to the XML file
the first line of the Java file should show something like this
public class balance extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_balance);
}
this means that my class(Java file) balance is connected to activity (layout) activity_balance.
if this is not the case, make sure that you are adding new activities from (file >new>activity> (blank activity for example)
Hope this helps

An Activity "is a single, focused thing that the user can do.". The internal of make an Activity when developing is actually the bundle of several actions:
Create a Java class that extends Activity directly or indirectly (for example, AppCompatActivity).
Create a corresponding layout file (this is not necessary, you may generate the layouts inside that class with Java dynamically).
Register this Activity inside AndroidManifest.xml, with a new tag like <activity android:name=".NecessaryActivityName" android:label="#string/optional" android:icon="#drawable/optional"/>, or you may specify more details of this Activity, for example the <intent-filter>.
So,
When you make a new activity it also makes a Java class.
Yes. A better description is, "When you make a new Activity, you are making a Java class that extends Activity".
yet coding anything into that java class doesn't seem to do anything.
"An activity is a single, focused thing that the user can do.". When you click on an application icon on Launcher ("desktop" of Android), you are starting a corresponding Activity (to be more precisely, sending an Intent to that Activity).
When you create another Activity, you are willing to have an Intent to start it, by adding a Launcher icon or by redirecting from another Activity (for example, MainActivity). The way of adding it to Launcher is posted by #J0B, by adding an <intent-filter> as the child of <activity> inside AndroidManifest.xml. The way of redirecting from another Activity is to build an Intent then call startActivity(), for example in Java:
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);

Each Android Application contains Activities. Each activity is declared in AndroidManifest.xml e.g. main_activity.xml and MainActivity.java is an 'Activity'. java classes, interfaces... can be used as normal in the java controller part of an activity.
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
Should be part of the activity that launches first.

In order to solve this issue simply go to your activity_second and use any of the palette tools before referencing your activity_second in your java file(SecondActivity).

Related

App keeps crashing after button click

I'm making a simple app and when I press a button that has an onClick() it crashes. I'm trying to open another activity on the button click.
Here's my onClick method from MainActivity.java:
public void gameActivity(View view){
Intent intent = new Intent(MainActivity.this, GameActivity.class);
MainActivity.this.startActivity(intent);
}
Here's my Button code from activity_main.xml:
<Button
android:id="#+id/play_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#f01c00"
android:onClick="gameActivity"
android:padding="16dp"
android:text="Play"
android:textColor="#FFF" />
Let me know what you think's the problem. Thanks
Well, I tried different things like moving around the startActivity(), but nothing happened. I deleted the activity I wanted to start and made a new one. That worked. I don't know what happened, but it's solved.
GameActivity must be registered in the AndroidManifest.

Android, ActionBar hiding other widgets

Disclaimer: It's build with CLI only tools, so certainly some "auto-generated lines" are missing
It's a small application with a MainActivity with a EditText and a Button
It works fine, but if I extends now from ActionBarActivity now my EditText and Button are hidden behind the Action Bar
https://developer.android.com/guide/topics/ui/actionbar.html The android documentation does not state about changes needing to be made in the layout.xml nor does the Training guide from which my application is based on
My MainActivity.java
public class MainActivity extends ActionBarActivity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// adding these lines show that the widget are correctly added
//ActionBar actionBar = getSupportActionBar();
//actionBar.hide();
}
}
My main layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText
android:id="#+id/enter_verb"
android:hint="#string/enter_verb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button
android:text="#string/button_conjugate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
My guess would be that I need to add something in my layout to make it aware there's a Action Bar, but I can't find anywhere what it should be.
Very strange, I've added the line coming from this link
https://developer.android.com/training/basics/actionbar/overlaying.html
Which is:
android:paddingTop="?attr/actionBarSize"
in my LinearLayout tag, and then recompiled, after that the widget were shown but with a padding of the size of the actionBar in addition to the actionBar itself.
I then removed the line, recompiled and it now works as expected
A bug because of temporary files?

Button causes Android app to "Unfortunately close"

Been stuck on this for about an hour now - May be an easy fix but I just cannot figure it out.
I have a button on the start screen, which once clicked will move to another activity.
This is from the xml:
<ImageButton
android:id="#+id/btn_text_scan"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#string/scan_button_description"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#null"
android:gravity="center"
android:scaleType="centerInside"
android:onClick="textExtract"
android:src="#drawable/ic_btn_text" />
and this is from the manifest:
<activity
android:configChanges="orientation|keyboardHidden"
android:launchMode="singleTop"
android:name=".OCRActivity">
</activity>
And from the class I want to move from, I use this code to move to the other activity. (However, even by removing this code, I still get this problem - so probably not this)
public void textExtract(View view)
{
Intent intent = new Intent(ScannerActivity.this, OCRActivity.class);
startActivity(intent);
}
I can provide the code for the activities, but I dont think this is needed
Any help would be appreciated!
Dan
EDIT
LogCat error
http://i.imgur.com/zK43neM.png
You have to call super.onCreate(bundle); as the first line in your onCreate(Bundle bundle) method. bundle might be named something else, but it's whatever is passed into this method.
The same goes for other lifecycle methods in an Activity. For example, the first line in your onPause method should be a call to super.onPause().
Try this:
Intent intent = new Intent(getApplicationContext(), OCRActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(intent);
Try and remove that android:background="#null" line in your XML and see if that works.

Trying to call an activity with a button onClick

I've been racking my brain for the past two days trying to get a button to work.
Basically I want my button to call 'add a password function'.
If you like to view my entire code, its at github.com/servingbaby/UPM-Epassafe .
Here is my main.xml (The button shows up succesfully however when pushing it nothing happens)
main.xml
<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:id="#android:id/empty"
android:layout_width="fill_parent"
android:layout_height="2dp"
android:gravity="center"
android:text="#string/no_accounts" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_gravity="center"
android:text="#string/add_account" android:id="#+id/add" android:minWidth="125dip"></Button>
<ListView android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
Here is my AndroidManifest slimmed down to the parts I believe are where I am going wrong.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.epassafe.upm"
android:versionCode="3"
android:versionName="1.2">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-sdk android:minSdkVersion="3" android:targetSdkVersion="16"/>
<application android:icon="#drawable/upm"
....>
<activity android:name=".AppEntryActivity">
</activity>
<activity android:name=".FullAccountList">
<meta-data android:name="android.app.default_searchable"
android:value=".SearchResults" />
</activity>
<activity android:name=".AddEditAccount">
</activity>
</application>
</manifest>
Here is my MainActivity.Java, where I believe I should be calling the correct code.
public abstract class MainActivity extends Activity implements OnClickListener{`
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button countButton = (Button) findViewById(R.id.add);
countButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,AddEditAccount.class);
MainActivity.this.startActivity(intent);
}
});
}
}
But pushing the button nothing happens like I expect. No errors or force close, so Im really at a loss at the moment. Thankyou!
**Edit
Thank you all how attempt to help me. I have tried many of the suggested solutions and still haven't figured it out just yet. I have uploaded my files to github with some of the attempted edits I have made as commented. Basically I am just trying to figure out how to add a button and get it to run the necessary code to add an account. (The original code works well, but I would like to improve upon it. Sorry my competence level is still low, but trying to learn my best :) I would really appreciate if anyone could help me with this! Thank you^^
**Edit 2
Again Thankyou all for the advice and suggestions. I figured out a simple solution. I ended up using a Menu Wrapper to create a button click event, and also it turned out I was editing the wrong Java document, when I was suppose to be trying to add the correct code to another one that seem to almost be doing the same thing. Learn something new everyday.
I don't understand why you're implementing OnClickListener to your activity. Remove the implements OnClickListener from your activity. It should work fine.
But since you're doing this for don't-know-what reason, you should make your button clickable like this.
countButton.setOnClickListener(this);
public void onClick(View view)
{
Intent intent = new Intent(MainActivity.this,AddEditAccount.class);
MainActivity.this.startActivity(intent);
}
First of all you dont need to implement OnClickListener to set a a listner in your button. But maybe you have it for another reason, if not, remove it.
You are declaring wrong the names of the id of your xml i think, take a look at this:
Difference between "#id/" and "#+id/" in Android
May be because of the #android:id instead of #+id.
use this way call Intent
Intent intent = new Intent(MainActivity.this, AddEditAccount.class);
startActivity(intent);
look at your list view
<ListView android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
you have given width and height as fill parent so your ListView is on your button so on the screen when you click on the button you are not actually clicking on the button. when you click a button the button color changes for a sec that is not happening in your case see it for your self. so remove the listview or set the height below the button and then check your button click will work

Styling tabs in android like the google open source contacts

I'm having troubles trying to style my tabs in android.
I want to make them look exactly the same as whats in the open source android contacts list (see https://android.googlesource.com/platform/packages/apps/Contacts
).
Problem is that when they display on the screen it looks a bit different to the contacts app.
When it should look like this:
Notice how the background colors are a little bit different and the text colors are different.
Not sure why this is the case as its basically the same code and icons.
My tab layout code is the following:
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="0dp">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="0dp" />
</LinearLayout>
</TabHost>
Which doesn't contain anything special there.. and the TabActivity is as follows:
public class TabbedActivity extends TabActivity implements
TabHost.OnTabChangeListener {
private TabHost tabHost;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = getIntent();
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.tab);
tabHost = getTabHost();
tabHost.setOnTabChangedListener(this);
setupLatestTab();
setupSavedTab();
tabHost.setCurrentTab(0);
}
private void setupLatestTab() {
Intent intent = new Intent().setClass(this, ResultsActivity.class);
tabHost.addTab(tabHost
.newTabSpec("latest")
.setIndicator("Latest",
getResources().getDrawable(R.drawable.ic_tab_recent))
.setContent(intent));
}
private void setupSavedTab() {
Intent intent = new Intent().setClass(this, ResultsActivity.class);
tabHost.addTab(tabHost
.newTabSpec("saved")
.setIndicator("Saved",
getResources().getDrawable(R.drawable.ic_tab_starred))
.setContent(intent));
}
#Override
public void onTabChanged(String tabId) {
// Because we're using Activities as our tab children, we trigger
// onWindowFocusChanged() to let them know when they're active. This may
// seem to duplicate the purpose of onResume(), but it's needed because
// onResume() can't reliably check if a keyguard is active.
Activity activity = getLocalActivityManager().getActivity(tabId);
if (activity != null) {
activity.onWindowFocusChanged(true);
}
}
}
I am using the same images from the drawable folders too.
I know i can set the background of tabs manually by doing something like this in the tabactivity
tabHost.getTabWidget().getChildAt(index).setBackgroundColor(Color.parseColor("#ff202020"));
But the contacts app isn't doing this sort of thing anywhere (most of the top tab code is in DialtactsActivity), so just want to do what the open source app is doing when displaying tabs - i'm not sure how and why the contacts application tabs look much better when im basically using the same code and resources.
I guess im just missing something trivial??
This turned out to be a problem with my minimum android version not being specified ..
Added:
<uses-sdk android:minSdkVersion="8" />
to the androidmanifest and it worked fine. I guess it was reverting to the old tabs look and feel in earlier versions of android.

Categories