App crashes when changing intent? - android

I set an imageview to change my activity onClick, for some reason it crashes each time I click the imageview on my device. Any ideas? I feel as if this is a very general answer that I am missing. Also if you have any reading material you could link related to my mistake it would help me greatly. Thank you!
Main Activity
package com.gcomcode.oakgang;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class MainActivity extends ActionBarActivity {
ImageView bioicon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView musicicon = (ImageView) findViewById(R.drawable.musicicon);
ImageView galleryicon = (ImageView) findViewById(R.drawable.gallery);
ImageView connecticon = (ImageView) findViewById (R.drawable.connecticon);
ImageView contacticon = (ImageView) findViewById (R.drawable.contacticon);
ImageView eventsicon = (ImageView) findViewById (R.drawable.eventsicon);
}
public void bioClick() {
bioicon = (ImageView) findViewById(R.drawable.bioicon);
bioicon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent bioIntent = new Intent(MainActivity.this, BioActivity.class);
startActivity(bioIntent);
}
});
}
}
and here is the corresponding layout
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#color/black"
tools:context="com.gcomcode.oakgang.MainActivity"
tools:ignore="MergeRootFrame" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/black"
android:src="#drawable/oakganglogo"
/>
<android.support.v7.widget.Space
android:id="#+id/space1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="144dp"
android:layout_marginTop="216dp" />
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp" >
<ImageView
android:id="#+id/bioicon"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/bioicon"
android:onClick="bioClick" />
<android.support.v7.widget.Space
android:id="#+id/space3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/musicicon"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/musicicon" />
<ImageView
android:id="#+id/galleryicon"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/gallery" />
<android.support.v7.widget.Space
android:id="#+id/space2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="85dp"
android:layout_gravity="bottom" >
<ImageView
android:id="#+id/eventsicon"
android:layout_width="100dp"
android:layout_height="85dp"
android:src="#drawable/eventsicon" />
<ImageView
android:id="#+id/contacticon"
android:layout_width="100dp"
android:layout_height="85dp"
android:src="#drawable/contacticon" />
<ImageView
android:id="#+id/connecticon"
android:layout_width="100dp"
android:layout_height="85dp"
android:src="#drawable/connecticon" />
</LinearLayout>
This is the activity I am trying to open
package com.gcomcode.oakgang;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
public class BioActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bio_activity);
}
}

Change this:
public void bioClick() {
to this:
public void bioClick(View view) {
because in order for an onClick method to be called from the xml (layout file), that onClick method has to take in exactly one parameter, a View parameter. (The view that gets passed into the method is whichever view called it - whichever view was pressed. This is useful if you want more than one view to call the same onClick method, because then you can use the view variable to figure out which view called it, and respond accordingly.)
Now, another problem with your code:
If you make that change I wrote, then it will probably stop crashing, because now it will be able to find the right onclick method. But the first time you click on bioicon, it won't take you to a new activity. You will find that you have to click it TWICE to make it go to a new activity. That is because the first time you click it, it runs the bioClick method. But the only thing that method does is to change the onClick method for the ImageView from "bioClick" to the new internal method. If you want the activity to change the FIRST time you click the bioicon ImageView, change your method to look like this:
public void bioClick() {
Intent bioIntent = new Intent(MainActivity.this, BioActivity.class);
startActivity(bioIntent);
}
This part of the code:
bioicon = (ImageView) findViewById(R.drawable.bioicon);
bioicon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent bioIntent = new Intent(MainActivity.this, BioActivity.class);
startActivity(bioIntent);
}
});
is how you set an onClickListener programmatically, in code. If you set an onClickListener in your xml layout file (by using android:onClick="bioClick"), then you do not need to set your onClickListener programmatically as well. Do one or the other, but not both.
While I am at it, I will also point out that unless you have more code in your onCreate method of your first activity than you showed here, there is absolutely no point to doing this:
ImageView musicicon = (ImageView) findViewById(R.drawable.musicicon);
ImageView galleryicon = (ImageView) findViewById(R.drawable.gallery);
ImageView connecticon = (ImageView) findViewById (R.drawable.connecticon);
ImageView contacticon = (ImageView) findViewById (R.drawable.contacticon);
ImageView eventsicon = (ImageView) findViewById (R.drawable.eventsicon);
You only need to "get" your views into variables if you plan on doing something with them afterward. (Like setting Listeners on them, changing text, or whatever.)

Related

How can I make Gridview get filled AFTER save is clicked?

Im developing a contacts app, and for now Ive been trying to get this drawables from the array get uploaded into the Gridview on the main screen AFTER the save mosaic button is clicked in the mosaic creation screen.
the floating action button (red plus button) on the mosaicListScreen (main screen) leads to the MosaicCreationScreen). the user hypothetically uploads the image and enters the mosaic name then saves using the save mosaic button, as can be seen in the image here
For now, before I focus on uploading image and letting the user create their own unique mosaics (groups), Im testing the Gridview updating with some drawables, which are listed in the array as can be seen in the code below.
The issue thats occuring is as soon as the user clicks the floating action button on the main screen, it updates the gridview with the drawables listed in the array of the MosaicCreation Screen, THEN it goes to the MosaicCreationScreen, and when save mosaic button is clicked on the MosaicCreationScreen, the intent goes to the main screen as its supposed to do, except the gridview will have nothing on it.
so its like its doing the opposite of whats supposed to happen in steps.
here is my code for the two screens:
public class mosaicsListScreen extends AppCompatActivity {
public static mosaicsListScreen theScreen; //this variable is used in the MosaicCreationScreen to point to this screen to find the GridView by id
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
theScreen = this;
setContentView(R.layout.activity_mosaics_list_screen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.createMosaicButton);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),MosaicCreationScreen.class);
startActivity(intent);
finish();
}
});
}
}
here is the code for the MosaicCreationScreen (the one that opens after user clicks floating action button from mosaicListScreen (main screen))
public class MosaicCreationScreen extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mosaic_creation_screen);
final GridView mosaicList = (GridView) mosaicsListScreen.theScreen.findViewById(R.id.mosaicList);
mosaicList.setAdapter(new ImageAdapter(this)); //this line of code displays the mosaics on mosaicListScreen
Button saveNewMosaicButton = (Button) findViewById(R.id.saveNewMosaicButton);
saveNewMosaicButton.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
//mThumbIds.notify();
Intent intent = new Intent(getApplicationContext(), mosaicsListScreen.class);
startActivity(intent);
finish();
//mosaicList.setAdapter(new ImageAdapter(this)); //this displays the mosaics on mosaicListScreen, it logically should go here, however "this" causes an error saying ImageAdapter (android.content.Context) in ImageAdapter cannot be applied to (anonymous android.view.View.OnClickListener)
Toast.makeText(mosaicsListScreen.theScreen, "Mosaic Created!", Toast.LENGTH_SHORT).show();
}
});
/* mosaicList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(mosaicsListScreen.theScreen, "", Toast.LENGTH_SHORT).show();
}
});*/
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
//this array holds the drawables that would appear on the Gridview
private Integer[] mThumbIds = {
R.drawable.family,
R.drawable.project
};
}
}
Here are the XML for the layouts:
content_mosaics_list_screen.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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="codesages.mosaic.mosaicsListScreen"
tools:showIn="#layout/activity_mosaics_list_screen">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/create_a_mosaic_or_pick_from_the_mosaics_created"
android:id="#+id/textView4"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="20sp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/deleteMosaicButton"
android:src="#android:drawable/ic_menu_delete"
android:clickable="true"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:contentDescription="" />
<GridView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/textView4"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="14dp"
android:id="#+id/mosaicList"
android:layout_above="#+id/textView7"
android:numColumns="auto_fit" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/holdMosaictoDeleteLabel"
android:id="#+id/textView7"
android:layout_marginBottom="16dp"
android:layout_above="#+id/deleteMosaicButton"
android:layout_centerHorizontal="true" />
</RelativeLayout>
activity_mosaics_list_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
tools:context="codesages.mosaic.mosaicsListScreen">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/createMosaicButton"
android:layout_width="56dp"
android:layout_height="66dp"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_input_add" />
<include layout="#layout/content_mosaics_list_screen" />
</android.support.design.widget.CoordinatorLayout>
activity_mosaic_creation_screen.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="codesages.mosaic.MosaicCreationScreen"
android:focusable="true">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/mosaicNametextField"
android:hint="Mosaic Name"
android:layout_marginTop="81dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save New Mosaic"
android:id="#+id/saveNewMosaicButton"
android:layout_marginTop="48dp"
android:layout_below="#+id/uploadMosaicImageButton"
android:layout_centerHorizontal="true"
android:enabled="true"
android:clickable="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Upload Mosaic Image"
android:id="#+id/uploadMosaicImageButton"
android:layout_marginTop="68dp"
android:layout_below="#+id/mosaicNametextField"
android:layout_centerHorizontal="true"
android:enabled="true"
android:clickable="true" />
</RelativeLayout>
mosaicList.setAdapter(new ImageAdapter(this));
thats what appears to be creating the mosaics. if i comment this out, i wont see anything in the gridview.
however, i believe that should be inside the saveNewMosaicButton onClick, but I am getting an error that says "saying ImageAdapter (android.content.Context) in ImageAdapter cannot be applied to (anonymous android.view.View.OnClickListener)"
HERE is an image example of what the desired result should be. however whats happening right now is as ive stated, as soon as the floating action button is clicked, the mosaics are created, THEN it takes you to the creation screen, in which wehn i click save mosaics, it actually erases the mosaics...a job of the trash icon which is too soon to function for now heh.
appreciate help on this
Currently, you have
public static mosaicsListScreen theScreen;
in your first Activity which you use to fill the ListView in this first Activity. This is a dangerous approach because the Activity instance referenced by this variable may be destroyed, for example if you're doing work in your second Activity (e.g. downloading images) which uses much memory, but also if the user somehow triggers a configuration change.
As you are calling finish() after starting the second Activity, you even tell the system that the first Activity may be destroyed. The only reason you did not get a NPE is that the system destroys the finished Activity not instantly but as soon as it seems a good idea to do so.
All in all, you need a way to safely transmit information from one Activity to the other. In your case, I think you would like to send the Uri of the selected images ( or for now, send the resource id of the selected drawables). Both can be accomplished by using Intent extras.
Basically, there are two options:
use startActivityForResult() and override onActivityResult() to obtain the desired information for the first Activity
simply start the first Activity from the second Activity once you have the result and use getIntent() in the first Activity (e.g. in onCreate()) to check for results
No matter what you do, always access UI elements like the ListView in the Activity to which they belong!
If you choose the second option, your first Activity could look like this:
public class mosaicsListScreen extends AppCompatActivity {
public static final String THUMB_IDS = "someuniquestring";
private GridView mosaicList;
private ArrayList<Integer> mThumbIds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mosaics_list_screen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.createMosaicButton);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),MosaicCreationScreen.class);
startActivity(intent);
finish();
}
});
fillThumbIds();
mosaicList = (GridView) findViewById(R.id.mosaicList);
// Note: Adapter code in this Activity
mosaicList.setAdapter(new ImageAdapter(this));
}
private void fillThumbIds()
{
mThumbIds = new ArrayList();
// somehow get older thumb ids if necessary (from database?)
// and add to ArrayList like this:
mThumbIds.add(R.drawable.family);
mThumbIds.add(R.drawable.project);
// assuming we transmit resource id's: use an int array with the Intent
int[] newThumbIds = getIntent().getIntArrayExtra(THUMB_IDS);
if (newThumbIds != null)
{
// loop through the array to add new thumb ids
for (int i = 0; i < newThumbIds.length; i++) {
mThumbIds.add(newThumbIds[i]);
}
}
}
// Adapter code goes here
// Note: thumbIds no longer as array but as ArrayList!
}
In the second Activity, you put the selected thumb ids as Intent extra as follows:
saveNewMosaicButton.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), mosaicsListScreen.class);
// if 'myNewThumbs' is the int array with the new thumb ids
intent.putExtra(mosaicsListScreen.THUMB_IDS, myNewThumbs);
startActivity(intent);
finish();
}
});

Android - Button under Relative layout wont initiate OnClickListener when clicked

Hello this is my xml file
<RelativeLayout
android:id="#+id/tutorialBox"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="15dip"
android:paddingBottom="15dip">
<Button
android:id="#+id/closeBen"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/CloseBenny"
android:layout_alignBottom="#+id/bennybox"
android:layout_alignEnd="#+id/chatbub" />
</RelativeLayout>
i have made an on click listener for it
final Button closeBt = (Button) findViewById(R.id.closeBen);
closeBt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
closeBt.setText("Im a button");
}
});
for some reason when i click this button nothing happens it doesnt look like it has been clicked.
when i took the button out of the realtive layout everything worked fine
any suggestions?
Instead of this add onClick attribute to the button tag in xml.
<Button
android:id="#+id/closeBen"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/CloseBenny"
android:onClick = "close_clicked"
android:layout_alignBottom="#+id/bennybox"
android:layout_alignEnd="#+id/chatbub" />
Then in Main Activity just make a new method like this.
public void close_clicked (View v){
// Your code
}
No need to add on click listner.
Your RelativeLayout does not look good, is it your main container? Maybe try it this way
<?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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<Button
android:id="#+id/closeBen"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/CloseBenny"
android:layout_alignBottom="#+id/bennybox"
android:layout_alignEnd="#+id/chatbub" />
</RelativeLayout>
And a good practice is to declare your widgets globally then instantiate them in theOnCreate
public class Foo extends AppCompatActivity {
private Button closeBenny;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
closeBenny = (Button)findViewById(R.id.closeBen);
closeBenny.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
closeBenny.setText("Im a button");
}
});
}
}

Force close error on setOnClickListener (Example from hello Android book section 3.5)

I am having problem in starting a new activity on clicking a button, here's my code:
package test.project;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
public class TestActivity 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 aboutButton = findViewById(R.id.about_content);
aboutButton.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.about_content:
Intent i = new Intent(this, testit.class);
startActivity(i);
break;
// More buttons go here (if any) ...
}
}
}
Can anyone please help me correct this error
Error Line
aboutButton.setOnClickListener(this);
Main.xml file
<?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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click here" android:layout_gravity="center"
android:text="Click here" android:layout_gravity="center" android:layout_marginTop="30dip"/>
</LinearLayout>
XML file containing about_content is
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip" >
<TextView
android:id="#+id/about_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/about_text" />
</ScrollView>
about_content is already defined here
<TextView
android:id="#+id/about_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/about_text" />
Well, you didn't post your logcat output, but since this is such a common beginner's mistake, I'm going to take a wild guess and say that you are probably getting a NullPointerException.
Your call to findViewById is probably returning null, which means that the system could not find the view associated with the id given by R.id.about_content. I would double check your XML layout for typos.
Odds are you don't have anything with the id about_content in main.xml, which will create a NullPointerException.
Also, if aboutButton is supposed to be a traditional Button, then you should use this:
Button aboutButton = (Button) findViewById(R.id.about_content);
Addition
Since aboutButton is a TextView, use this:
TextView aboutButton = (TextView) findViewById(R.id.about_content);
but this TextView must be in the layout passed to setContentView() or findViewById() will return null.
That is because the "main.xml" which you have set your content view ... does not contain the about_content TextView, its in the other xml which you have posted ...
Note: You can access only those R.id's which are present in your setContentView(R.layout.yourlayout) xml ...
you make setContentView(R.layout.main); but main.xml does not include View have id = R.id.about_content. If you raplace by findViewById(R.id.button1); It will work.
This is the solution for
Button aboutButton = (Button)findViewById(R.id.about_content);
And dont forget to add testit Activity in Android Manifest

dynamic number of gui elements in Android?

I want to create a gui application for android where the user will be able to add or remove fields of certain type (4 different type of fields) to the application. Is there a way to do so in xml?
The only way I could figure to do so is by edditing the xml file from within the app which sounds as a bad idea for me.
Hope my question is clear.
Yotam.
Edit:
I have added a simple code for direct java implantation:
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.TextView;
public class Leonidas extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.counter);
TextView TV = new TextView (this);
TextView UV = new TextView (this);
TV.setText("hello");
UV.setText("goof");
//setContentView(TV);
//setContentView(UV);
ViewGroup.LayoutParams lpars = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
this.addContentView(UV,lpars);
this.addContentView(TV, lpars);
this.setVisible(true);
}
}
Edit2:
I have searched for example and got the following working:
LayoutInflater inflater;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
inflater = LayoutInflater.from(this);
Button b = (Button) this.findViewById(R.id.alert);
b.setOnClickListener(this);
}
#Override
public void onClick(View v) {
final LinearLayout canvas = (LinearLayout)Leonidas.this.findViewById(R.id.counter_field);
final View cv = this.inflater.inflate(R.layout.counter,canvas,false);
canvas.addView(cv);
}
You can do it from within your handler too (in the implementation class).
After inflating your xml layout, you respond to some kind of user interactions.
In the handler you
either create a new View from
scratch, and specify its
layoutparams,
or inflate one using xml
After having the new view, you add it to the current (this) view, and due to its layoutparams, it will be the size, shape, color, etc. that you want.
Update:
If you'd like to add more complex views to your activity, it's better to write them in xml, and inflate them:
sample_component.xml: //inside res/layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:padding="0px">
<TextView android:id="#+id/servicename_status" android:paddingLeft="15px"
android:paddingRight="5px"
android:textStyle="bold" android:focusable="false" android:textSize="14px"
android:layout_marginLeft="10px" android:layout_marginRight="3px"
android:layout_width="fill_parent" android:layout_height="wrap_content" />
<TextView android:id="#+id/lastcheck" android:focusable="false"
android:textSize="14px" android:layout_width="fill_parent"
android:layout_marginLeft="10px" android:layout_marginRight="3px"
android:layout_height="wrap_content" android:layout_below="#id/servicename_status" />
<TextView android:id="#+id/duration" android:focusable="false"
android:textSize="14px" android:layout_width="fill_parent"
android:layout_marginLeft="10px" android:layout_marginRight="3px"
android:layout_height="wrap_content" android:layout_below="#id/lastcheck" />
<TextView android:id="#+id/attempt" android:focusable="false"
android:textSize="14px" android:layout_width="fill_parent"
android:layout_marginLeft="10px" android:layout_marginRight="3px"
android:layout_height="wrap_content" android:layout_below="#id/duration" />
<TextView android:id="#+id/statusinfo" android:focusable="false"
android:textSize="14px" android:layout_width="fill_parent"
android:layout_marginLeft="10px" android:layout_marginRight="3px"
android:layout_height="wrap_content" android:layout_below="#id/attempt" />
<CheckBox android:id="#+id/alert" android:focusable="false"
android:layout_alignParentRight="true" android:freezesText="false"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="5px" />
</RelativeLayout>
Inside your Leonidas activity class you have the handlers that have to respond to different user actions by adding/removing items to/from the view.
Below is a sample handler of a click event, which uses LayoutInflater, to add the sample_component.xml view to your activity:
public final class MyClickListener implements View.OnClickListener
{
private LayoutInflater inflater;
public MyClickListener()
{
inflater = LayoutInflater.from(Leonidas .this);
}
#Override
public void onClick(View v)
{
// TODO: change RelativeLayout here to whatever layout
// you'd like to add the new components to
final RelativeLayout canvas = (RelativeLayout)Leonidas.this.findViewById(R.id.my_canvas);
final View childView = inflater.inflate(R.layout.sample_component, canvas, false);
// TODO: Look up the 5 different signatures of the addView method,
// and pick that best fits your needs
canvas.addView(childView);
// check which button was pressed
switch (view.getId())
{
case R.id.btn_prev:
//handler for the prev button
break;
case R.id.btn_next:
//handler for the next button
break;
default:
break;
}
}
}
Note, that MyClickListener is implemented as an inline class within your Leonidas activity, thay's why for the context parameter it is used: this.Leonidas.
Update
The R.id.my_canvas would be the id of the view that you want to add components to. it is in your main.xml (or whatever xml you use for your Leonidas view).
If you put the MyClickListener class inside your Leonidas.java class (declare as inline class), it will recognize it.
Instead of specifying elements in the XML, you can create them dynamically and add it to the UI. This is demonstrated in the Android Hello World Tutorial here.

Display image after button click

I am making a really simple android application that will display a picture after a button is clicked. I have searched for days and tried everything I can think of but cant seem to get it to work. I have been able to host the picture online and link to it but I want the content available offline too. Please help, sorry for the stupid question.
Update:
It is a fixed image and in my drawable resource. Here is the current code I am using to display the image from a URL. What changes should I make to to display that same image from my drawable resource?
JAVA
public class StandingOrders extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void buttonClick (View image)
{
Uri uri = Uri.parse("my url");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent)
}
}
XML
<Button android:id="#+id/btn1"
android:layout_height="wrap_content"
android:layout_width="170px"
android:text="The Button"
android:layout_gravity="center"
android:clickable="true"
android:onClick="buttonClick">
</Button>
If it's a fixed image, include it as a drawable resource and use an ImageView to display it. If it's an image to download, you can do that in a separate thread and store it in a file or an SQLite data base, then again use an ImageView to see it.
Add an ImageView to your xml layout and call setImageResource from onClick.
setImageResource(R.drawable.yourImage);
Or you could set the image in your layout and make the ImageView hidden until you click the button. See setVisibility(View.GONE)
Check out this answer: https://stackoverflow.com/a/4896272/458968
In your case, the uri should be
Uri.parse("android.resource://com.company.app/"+R.drawable.my_image);
You can try to implement the method, which I am posting below. I have done something more or less similar to your requirement.
Method:
//method to zoom images
public void zoomImage(String imageUrl)
{
AlertDialog.Builder builder;
Context mContext = ExamActivity.this;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog,
(ViewGroup) findViewById(R.id.layout_root));
//to close dialog
ImageView close_dialog = (ImageView) layout.findViewById(R.id.imageView_custom_dialog_close);
close_dialog.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
alertDialog.dismiss();
}
});
//to show image
WebView wv=(WebView) layout.findViewById(R.id.show_image_webView);
wv.getSettings().setBuiltInZoomControls(true);
wv.setInitialScale(200);
wv.loadUrl(imageUrl);
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
alertDialog = builder.create();
alertDialog.show();
}
the imageUrl is the url to the webpage containing the image. If you want to show a local image then just create a simple html page containing the image and use the local url.
Try this:-
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView imageToDisplay = (ImageView) findViewById(R.id.imageToDisplay);
Button btnShowImage = (Button) findViewById(R.id.btnShowImage);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imageToDisplay.setVisibility(View.VISIBLE);
imageToDisplay.setImageResource(R.drawable.imagelogo);
}
});
}
}
In layout imageToDisplay's visibility is gone.
try following example
you can download "android-query-0.22.10.jar" file from following url.
http://www.java2s.com/Code/Jar/a/Downloadandroidquery02210jar.htm
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.addbuttondynamic.AddButtonDynamic" >
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Load Image" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
and Main.java
import com.androidquery.AQuery;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
public class Main extends Activity {
Button btnLoad;
ImageView ivImage;
AQuery aQuery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnLoad=(Button)findViewById(R.id.button1);
ivImage=(ImageView)findViewById(R.id.imageView1);
aQuery=new AQuery(this);
btnLoad.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//load image from /res folder.
ivImage.setImageResource(R.drawable.ic_launcher);
//load image from url.
aQuery.id(ivImage).image("you URL");
// if ivImage is not working in aQuery.id() then use R.id.imageView1.
}
});
}
}
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"
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.imagechange.MainActivity"
>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="10dp"
android:text="#string/khilan"
android:onClick="btnOnClick"
/>
<ImageView
android:id="#+id/imageView1"
android:layout_width="800px"
android:layout_height="500px"
android:layout_marginTop="70dp"/>
</RelativeLayout>
MainActivity.java
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btnOnClick (View view)
{
String imagename = "khilan";
int res = getResources().getIdentifier(imagename, "drawable", getPackageName());
ImageView iv = (ImageView) findViewById(R.id.imageView1);
iv.setImageResource(res);
}
}
Create a layout with image and button, make the image hidden and onClick set the visibility to VISIBLE.
Here is what the XML should look like:
<?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">
<ImageView
android:id="#+id/image"
android:src="#drawable/image1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"/>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Image" />
</RelativeLayout>
and the following is the Java code
ImageView image = findViewById(R.id.image);
Button button = findViewById(R.id.got_it_button);
image.setVisibility(View.GONE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
image.setVisibility(View.VISIBLE);
}
});
Good luck :)

Categories

Resources