Android: Simpify many classes and xml - android

Edit: I cannot get this to work correctly. Probably because I have no idea what I am doing. Anyways, here's my code. If anyone could help, I'd be very grateful: I needs to get it to display the battery mood image for the corresponding mod...
Themes:
package com.cydeon.plasmamodz;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class Themes extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.themes);
ActionBar actionBar = getActionBar();
actionBar.hide();
Button Plus = (Button) findViewById(R.id.button1);
Button Blue = (Button) findViewById(R.id.button2);
Plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(Themes.this, Bmod.class);
i.putExtra("drawableResource", R.drawable.blue);
Themes.this.startActivity(i);
}
});
Blue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent a = new Intent(Themes.this, Bmod.class);
a.putExtra("drawableResource1", R.drawable.plus);
Themes.this.startActivity(a);
}
});
}
}
Bmods:
package com.cydeon.plasmamodz;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
public class Bmod extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.battery);
Intent i = getIntent();
int drawableResource = i.getIntExtra("drawableResource", R.drawable.blue);
ImageView img = (ImageView) findViewById(R.id.iv1);
img.setImageResource(R.drawable.blue);
Intent a = getIntent();
int drawableResource1 = a.getIntExtra("drawableResource1", R.drawable.plus);
ImageView img1 = (ImageView) findViewById(R.id.iv1);
img1.setImageResource(R.drawable.plus);
}
}
battery(xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/bInstall"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="Install" />
<Button
android:id="#+id/bReturn"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="Return" />
<ImageView
android:id="#+id/iv1"
android:layout_width="match_parent"
android:layout_height="800dp" />
</RelativeLayout>

Intent i = new Intent(this, BaseClassForMod);
i.putExtra("drawableResource", R.drawable.this_mod_drawable);
startActivity(i);
Then in that Activity's onCreate():
Intent i = getIntent();
int drawableResource = i.getIntExtra("drawableResource", R.drawable.default);
//Get a reference to your ImageView...
imageView.setImageResource(drawableResource);
Don't trust this code to compile, but that's the general idea. Use the same Activity for all of them, pass along the proper resource ID in the intent (e.g. for mod1, send the drawable ID for mod1), then in the activity, check for that resource ID and set it programmatically.

You shouldn't need 50 classes and 50 xml layouts if every one of them does the same thing. Make one activity and one layout. When the user selects something, pass an id of some kind as an Intent extra to the second activity so it can load whatever item is appropriate. I don't know how your data is modeled, but there should be a way to uniquely identify each option (and if there isn't, you should implement one).
Your first activity also doesn't need a button for each item. Use a ListView and an Adapter, and then you just need to provide a layout for one row.

make a single activity only. Inside of it get a reference to your image:
ImageView iv = (ImageView)findViewById(R.id.yourImgId);
Then set the picture to whichever one you want like:
iv.setImageResource(R.drawable.battery_img_1);

Related

Passing an image from an activity to another one

I want to pass images from one activity to another when button clicked. I have one button "Show Image" in first activity. When I click on it, it should pass two images from my mipmap folder of my project and go to second activity and show one of the passed image on the ImageView of that activity. On second activity, I have two buttons which are supposed to receive images and show those images when clicked on each button. I tried using intent to pass the image, however, it didn't work. Is there other way to send images from mipmap folder from one activity to another?
Here is my code:
MainActivity.java
package com.example.abina.myapplication;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import java.io.ByteArrayOutputStream;
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showmyImage();
}
});
}
public void showmyImage(){
Intent intent = new Intent(this, Main2Activity.class);
Bitmap bitmap; // your bitmap
bitmap = null;
ByteArrayOutputStream _bs = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, _bs);
intent.putExtra("byteArray", _bs.toByteArray());
startActivity(intent);
}
}
activity_main.xml
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_marginStart="137dp"
android:text="Show Image" />
</RelativeLayout>
Main2Activity.java
package com.example.abina.myapplication;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
public class Main2Activity extends AppCompatActivity {
Button image1;
Button image2;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
image1 =(Button) findViewById(R.id.image1);
image2 = (Button) findViewById(R.id.image2);
imageView =(ImageView) findViewById(R.id.imageView);
if(getIntent().hasExtra("byteArray")) {
Bitmap _bitmap = BitmapFactory.decodeByteArray(
getIntent().getByteArrayExtra("byteArray"),0,getIntent().getByteArrayExtra("byteArray").length);
imageView.setImageBitmap(_bitmap);
}
}
}
activity_main2.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"
tools:context=".Main2Activity">
<Button
android:id="#+id/image1"
android:layout_width="199dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:text="Image1" />
<Button
android:id="#+id/image2"
android:layout_width="183dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="0dp"
android:text="Image2" />
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
Images
First the mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders.
Next since they will be in your drawables, I would just pass the #DrawableRes id e.g. the R.id.image_name value.
Intent intent = new Intent(this, Main2Activity.class);
intent.putExtra(IMAGE_RES_ID_KEY, R.id.imageName);
startActivity(intent);
Also I would recommend that you use a public static variable IMAGE_RES_ID_KEY for your extra key to avoid typos.
Then on the other side you can simply
if(getIntent().hasExtra(MainActivity.IMAGE_RES_ID_KEY)) {
imageView.setImageResource(getIntent().getIntExtra(MainActivity.IMAGE_RES_ID_KEY, 0));
}

Error using findViewById method

I'm trying to use the findViewById() method to to assign an action to a button I created, however it is giving me the error:
findViewById(int) in android.support.v7.app.AppCompatActivity cannot be applied to (android.widget.Button)
at the lines:
buttonStudentAccess = (Button) findViewById(buttonStudentAccess);
buttonGuestAccess = (Button) findViewById(buttonGuestAccess);
My code is as follows:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class UserTypeSelection extends AppCompatActivity implements View.OnClickListener{
private Button buttonStudentAccess;
private Button buttonGuestAccess;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_type_selection);
buttonStudentAccess = (Button) findViewById(buttonStudentAccess);
buttonGuestAccess = (Button) findViewById(buttonGuestAccess);
buttonStudentAccess.setOnClickListener(this);
buttonGuestAccess.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view == buttonStudentAccess) {
}
if (view == buttonGuestAccess) {
//startActivity(new Intent(this, MainActivity.class));
}
}
The corresponding xml file contains the buttons
<Button
android:text="Guest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/buttonStudentAccess"
android:layout_alignLeft="#+id/buttonStudentAccess"
android:layout_alignStart="#+id/buttonStudentAccess"
android:layout_marginTop="30dp"
android:id="#+id/buttonGuestAccess"
android:layout_alignRight="#+id/buttonStudentAccess"
android:layout_alignEnd="#+id/buttonStudentAccess" />
<Button
android:text="Student"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:id="#+id/buttonStudentAccess"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true" />
I used the same syntax to create and assign actions to buttons in my login and registration classes and it didn't create this error. Any help is appreciated, thank you
You need to specify where you're getting the id "buttonStudentAccess" from. so here's how you can find the view:
buttonStudentAccess = (Button) findViewById(R.id.buttonStudentAccess);
To specify that the button or any other view is located in the "resources" package you refer to it as R and .id specifies that you want to grab the view using its id.
buttonStudentAccess = (Button) findViewById(R.id.buttonStudentAccess);
buttonGuestAccess = (Button) findViewById(R.id.buttonGuestAccess);

when i change my button to an icon i can't click on it to go to a new layout

this my xml file main
<?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:background="#raw/christmas"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/by_kostas"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="83dp"
android:text="#string/by_kostas"
android:textSize="20sp"
android:textColor="#F2F3F4"/>
<ImageView
android:id="#+id/settings"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:onClick="nameOfMethod"
android:src="#raw/settings" />
</RelativeLayout>
and my java Main
package com.kostas.mytorch;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
//start our layout
super.onCreate(savedInstanceState);
setContentView(R.layout.main);{
final ImageView diskView = (ImageView) findViewById(R.id.settings);
diskView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
//my codes
}
});
diskView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// System.out.println("image clicked...");//in my logcat
startActivity(new Intent("com.kostas.standroid.settings"));
}
});
}
}
my problem is when i click in the settings icon, my program crashes instead of what i wanted to create a new layout (settings xml is just black page),can someone be kind enough to help me out
You can attach click listener to any view by two ways:
In xml, write onClick attribute of the view and pass the method
name you have implemented in the activity.
Example: android:onClick="someMethod" and in the activity code, declare a method
public void someMethod(View view)
{
// handle click here
}
In activity, use setOnClickListener() to the view.
For now, try this:
diskView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// System.out.println("image clicked...");//in my logcat
startActivity(new Intent(Main.this, settings.class));
}
});
Also remove this line from xml: android:onClick="nameOfMethod"
Some time there is contextual problem. Try this.
Intent intent = new Intent(CurrentActivity.this, UpcomingActivity.class);
startActivity(intent);
Also don't forget to define class in Manifest file
try to remove
android:onClick="nameOfMethod"
from the xml layout. I believe this is the method that it's called when you click the settings button and it doesn't exist so it crashes.

can't go back button

I have a problem with my Android app. I have three Activities that all connect with one another with a Image button.
My problem is I can't go back on any of the pages, just forwards. I have been reading about the back button and how to keep its state and not kill (End) it, so the user can click back if needed too.
I am new to Android and I know there's a lot to learn. So thank you for your help.
Java code for first Activity:
package my.hope;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.content.Intent;
public class NewhopeActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView myImage = (ImageView) findViewById(R.id.imagebutton1);
myImage.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(NewhopeActivity.this, Act2.class);
startActivity(intent);
}
});
}
}
XML code:
<?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:orientation="vertical" android:background="#drawable/mint">
<ImageButton
android:id="#+id/imagebutton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="250dp"
android:background="#drawable/ic_launcher"
android:onClick="Act2"
android:src="#drawable/ic_launcher" />
</LinearLayout>
What happens when you click the back button on your device? Unless specified, it kills the current activity and brings you back to the previous one.
However, if you wish to specify exactly what would clicking the back button do, you can override the onBackPressed() method:
#Override
public void onBackPressed() {
Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
startActivity(intent);
finish();
}

Android Null Pointer Exception Button

Ok this may seem like a pointless example but if I can figure this out then the program I am trying to make will work. So I have two activities test and test two each with one button.
Test 1:
package thompson.cameron.com;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class Test extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View button = findViewById(R.id.testButton);
button.setOnClickListener(this);
}
public void onClick(View v){
Intent i = new Intent(this, Test2.class);
startActivity(i);
}
}
and test2
package thompson.cameron.com;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class Test2 extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
View test = findViewById(R.id.testButton);
test.setOnClickListener(this);
}
public void onClick(View v){
switch (v.getId()){
case R.id.testButton:
System.exit(1);
}
}
}
When I click the button on Test it is supposed to launch test2 however it is at this point I get an null pointer exception that I have narrowed down to test.setOnClickListener(this); line of code. Below are my two xml files for the layout. I can get the button to work when I only have one activity but as soon as I add a second activity with a different layout file it all falls apart
main.xml
<?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"
>
<Button
android:id="#+id/testButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEST TEST TEST"/>
</LinearLayout>
main2.xml:
<?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"
>
<Button
android:id="#+id/testButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEST2 TEST2 TEST2"/>
</LinearLayout>
I'm still new at Android programming so thanks for all your help.
Open the Debug perspective in Eclipse
Choose the 'Breakpoints' view tab.
Select the 'Add Java Exception Breakpoint' and choose
NullPointerException.
Launch your activity, either by using 'Debug As...' or attaching
the debugger to a running instance via DDMS.
Execute the offending workflow. It will break on the line that
caused the NullPointerException.
In your test.java file give:
implements View.OnClickListener
Initialize your button as:
Button testButton = (Button) findViewById(R.id.testButton);
and inside your onClick method, check whether you are clicking button:
if(v == testButton) {
//give ur intent code
}
There are different ways to perform onClick functionality.
One is the above method which I have mentioned.
Another one is what ankit has mentioned.
Third way is through your layout.
Inside your layout for your button tag, you may give as:
<Button android:id="#+id/testButton" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Click" android:onClick="onTestButtonClick" />
And inside your class just mention the below details for button:
public void onTestButtonClick(View view) {
//give your intent code
}
You may refer to the link also:
http://android-developers.blogspot.com/2009/10/ui-framework-changes-in-android-16.html
Make sure that both activities are register at the application's manifest file.
As a side note never call System.exit in your code. You can call finish() to close an Activity and this will bring at the front the previous Activity on the stack.
The issue here is that you haven't typecasted your views to buttons.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; // Needed to add this import for the button casting below
public class Test extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// I have changed View to Button and then typecasted
// with the "(Button)" the return of findViewById
Button button = (Button) findViewById(R.id.testButton);
button.setOnClickListener(this);
}
public void onClick(View v){
Intent i = new Intent(this, Test2.class);
startActivity(i);
}
}
Let me know if you have any issues with this. I just completed my first experiment through using the onClickListener implementation through the main class instead of individual anonymous listeners.
Andrew
I had the same problem, you may put the same content view that the button,
setContentView(R.layout.main); if the button is in that content view, in other case, you will put:
setContentView(R.layout.buttoncontentview);
View button = findViewById(R.id.testButton);
button.setOnClickListener(this);
public void onClick(View v){
Intent i = new Intent(this, Test2.class);
startActivity(i);
}
setContentView(R.layout.main);
sorry for my bad english, but i'm spanish
Implement OnClickListener interface
and set button.setOnClickListener(this);
and override
public void onClick(View v) {
}
I think your buttons IDs need to be different in different activities. R.id.testButton would refer to only one button.
The final solution is that you may modify the AndroidManifest.xml file, i finally solved my error in this link How to register a new activity in AndroidManifest.xml?
You can try this.it may work.
package thompson.cameron.com;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class Test extends Activity{
private Button button;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = findViewById(R.id.testButton);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent i=new Intent().setClass(Test.this,Test2.class);
startActivity(i);
}
});
}
}
First of all in main.xml and main2.xml chage the button's ids like in below code.
main.xml
<?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"
>
<Button
android:id="#+id/testButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEST TEST TEST"/>
</LinearLayout>
main2.xml
<?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"
>
<Button
android:id="#+id/testButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEST2 TEST2 TEST2"/>
</LinearLayout>
It throws nullpointerexception because of id confict with each other so in your java file use following code to find button.
In Activity 1
Button button = findViewById(R.id.testButton);
button.setOnClickListener(this);
and
In Activity 2
Button button = findViewById(R.id.testButton1);
button.setOnClickListener(this);

Categories

Resources