I'm new to android developing, so i apologise if this is a simple/noob-ish question, and for any incorrect terminology.
but what i need to know is how can i include a list alongside of other UI elements (such as TextView, ImageView elements etc)
upto now, all i have been able to achieve is a list activity all on its own, which to do this i have been using the ListActivity class type.
My list activity:
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class ListViewExample extends ListActivity
{
String[] exampleList = {
"Item 1",
"Item 2",
"Item 3"
//etc etc
};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, exampleList));
}
}
Which is started within my Main class/activity:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class NewtestActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startActivity(new Intent( this, ListViewExample.class));
}
}
but with the function of "startActivity()", this seems to just switch to that activity, and not "include" it to the current, which of-corse means that any elements within "R.layout.main" (defined above the calling of "startActivity()) are not shown.
Is there anyway to include this activity within my main activity?
or is there a better way of making a list?
(my goal will eventually be to make the list array dynamic, just thought id say in case that affected on any suggested solution).
thanks for any help (:
Using the startActivity to start your ListViewExample starts a whole new activity (with a whole new view) and puts it on top of the stack. When you click the back button, then your main activity will be displayed. Please see this link to learn more about the activity lifecycle.
It sounds like what you want to do is define some other UI elements alongside your listview. I dont know if you can do this on the SIDE, but I know you can include buttons/textviews on top or bottom of a listview. See this post as a good example of how to put a button below a listview.
EDIT: As an example (taken from the second link), you would do something like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="#+id/testbutton"
android:text="#string/hello" android:layout_alignParentBottom="true" />
<ListView android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="#+id/list"
android:layout_alignParentTop="true" android:layout_above="#id/testbutton" />
</RelativeLayout>
Now you could also put that button on bottom if you wanted, or include a textbox on the top and a button on bottom.
Yes as Espiandev said, you would want your main activity to extend Activity. Then in your XML you would have the above. The way you would get your listview to bind to would be
ListView lv = (ListView)findViewById(R.id.list);
Then you could bind to it:
lv.setAdapter(...)
An alternative to the other answer, which is probably more scalable, is to simply make ListViewExample extend a basic Activity. Then, in the onCreate() method, retrieve the ListView by using findViewById() and then use setAdapter() on this. For example, if your ListView was given the id listview1:
public class ListViewExample extends Activity {
String[] exampleList = {
"Item 1",
"Item 2",
"Item 3"
//etc etc
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
// Get an instance of your listview in code
ListView listview = (ListView) findViewById(R.id.listview1);
// Set the listview's adapter
listview.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, exampleList));
}
}
This will give you the flexibility to have a layout with more than just a listview in it
Related
Is there a way to implement a button that can be reached from everywhere? The Button should visible in every view of the app.
You can't make a button that exists in every activity & fragment, but you can make a button for each activity and they all look the same in each activity.
I prefer using a FloatingActionButton, and here is how to use it :
First implement androidx.appcompat:appcompat:1.1.0 to your gradle file :
implementation 'androidx.appcompat:appcompat:1.1.0'
Then add this code to the XML file for each activity just like any other view ( but add it as the last view ):
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/_fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:layout_gravity="right|bottom"
app:srcCompat="#drawable/an_icon_for_the_button"/>
Then import these to each activity:
import androidx.appcompat.app.AppCompatActivity;
import androidx.annotation.*;
import com.google.android.material.floatingactionbutton.FloatingActionButton
Then add the FloatingActionButton to each activity:
private FloatingActionButton _fab;
The add this to the onCreate void in each activity:
_fab = (FloatingActionButton) findViewById(R.id._fab);
_fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View _view) {
//here enter what will happen when the user clicks the button
//in your example, this will open the sidebar
}
});
I have a multi-edit text field in a card view I want to get a string from and show in a toast before moving on to another activity. I can fill in text just fine when running the activity, but when I click the submit button nothing happens. What am I doing wrong or what am I missing in the code?
Here is my XML file:
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
card_view:cardCornerRadius="4dp"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="0dp">
<EditText
android:id="#+id/value1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/choice_hint1c"
android:inputType="textMultiLine" />
</android.support.v7.widget.CardView>
<Button
android:id="#+id/choiceButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/round_btn_shape"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:layout_marginStart="125dp"
android:text="#string/submit"
android:textColor="#FFFFFF" />
Class file:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Choice extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choice);
addListenerOnButton();
}
public void addListenerOnButton() {
Button submitButton = (Button) findViewById(R.id.choiceButton);
final EditText editTextV1 = (EditText) findViewById(R.id.value1);
final String valueOne = editTextV1.getText().toString();
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (valueOne.equals("")) {
//happens if first field is empty
Toast.makeText(
getApplicationContext(),
"First field is empty",
Toast.LENGTH_SHORT).show();
} else {
//save selection
Toast.makeText(
getApplicationContext(),
valueOne,
Toast.LENGTH_SHORT).show();
//save response to SQLite
Intent intentSurvey = new Intent(Choice.this, MainActivity.class);
startActivity(intentSurvey);
}
}
});
}
}
You miss to add addListenerOnButton() inside onCreate method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choice);
addListenerOnButton(); // add this
}
To check whether EditText is empty
if(TextUtils.isEmpty(valueOne))
Move String valueOne = editTextV1.getText().toString(); inside onClick
I don't know what is Choice.this but first argument of Toast need be Context Example: Toast.makeText(getContext(), "Your text for toast", Toast.LENGTH_SHORT).show();
You're on the right track. When asserting on a string coming from an EditText, I prefer to use:
if(Strings.isNullOrEmpty(someStringHere)) {
do this
}
This is utilized from the espresso library. Import to your class file with
import android.support.test.espresso.core.deps.guava.base.Strings;
Make sure to add Espresso to your build.gradle file.
A string can be null, but not equal "", that's why I pursue the route mentioned above. I'm assuming your toast is showing a 'null' String.
If this does not work, I suspect it's because you're trying to find a view by id within an onClick method. onClick (and other 'on' methods for the matter of fact) have different context than your activity has. That's why When making a toast, you had to say CLASSNAME.this, rather than just 'this'.
Try pulling out your edit text, and making it a private member of your class. Find the edit text by id as you did before, but do it above and outside the onClickListener. Once inside the onclick method, you should be able to get the text values as you have already.
If neither of these solve your issue, you're going to have to post more of your code.
First is that I don't see the method addListenerOnButton() within the onCreate. This was mentioned.
Second is that the final String valueOne is being set on create, with the initial value of the EditText. This value is then persisted through closure of the anonymous class.
You need to get the String version of the text field within the listener.
I am new to android, currently in my second year in I.t..
I'm working on a grocery list app project, where I display a list of groceries for the user to select and to display them on the next screen (Screen 2).
The problem I am having, is, when I click the Show List button, it displays the indexes of the selected checkboxes instead of the text displayed... I have tried using a ListActivity to display an array in a CheckedTextView but that didn't work out either (checkboxes were not checking when selected).
I would really appreciate some help on how to display the selected text instead of the checkboxes selected indexes and would like to know where I am going wrong.
Below is my Java and XML code for the 2 screens..
Java Coding - Screen 1
package com.allmycode.lists;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
static CheckBox[] checkBoxes = new CheckBox[18];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout layout =
(LinearLayout) findViewById(R.id.linearLayout);
for (int i = 0; i < 18; i++) {
checkBoxes[i] = new CheckBox(this);
layout.addView(checkBoxes[i]);
}
checkBoxes[0].setText("Baking Ingredients");
checkBoxes[1].setText("Beverages");
checkBoxes[2].setText("Canned Foods");
checkBoxes[3].setText("Cereal");
checkBoxes[4].setText("Dairy");
checkBoxes[5].setText("Detergents");
checkBoxes[6].setText("Frozen Vegetables");
checkBoxes[7].setText("Fruit");
checkBoxes[8].setText("Broad Beans");
checkBoxes[9].setText("Herbs");
checkBoxes[10].setText("Legumes");
checkBoxes[11].setText("Meat");
checkBoxes[12].setText("Pasta");
checkBoxes[13].setText("Pet Food");
checkBoxes[14].setText("Rice");
checkBoxes[15].setText("Snacks");
checkBoxes[16].setText("Toiletries");
checkBoxes[17].setText("Vegetables");
}
public void onShowListClick(View view) {
Intent intent =
new Intent(this, MyListActivity.class);
startActivity(intent);
}
}
XML Coding - Screen 1
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=
"http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TextView>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onShowListClick"
android:text="#string/show_list" >
</Button>
Java Coding - Screen 2
package com.allmycode.lists;
import java.util.ArrayList;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class MyListActivity extends ListActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<Integer> listItems =
new ArrayList<Integer>();
for (int i = 0; i < 18; i++) {
if (MainActivity.checkBoxes[i].isChecked()) {
listItems.add(i);
}
}
setListAdapter(new ArrayAdapter <Integer> (this,
R.layout.my_list_layout, listItems));
}
}
XML Coding - Screen 2
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android=
"http://schemas.android.com/apk/res/android"
android:id="#+id/identView"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
You're only setting the indexes, so it makes sense that's what's happening:
ArrayList<Integer> listItems = new ArrayList<Integer>(); // <-- List of Integers
for (int i = 0; i < 18; i++) {
if (MainActivity.checkBoxes[i].isChecked()) {
listItems.add(i); // <-- You're adding an integer to the List
}
}
Try this instead:
ArrayList<String> listItems = new ArrayList<String>(); // <-- List of Strings
for (int i = 0; i < 18; i++) {
if (MainActivity.checkBoxes[i].isChecked()) {
listItems.add(MainActivity.checkBoxes[i].getText()); // Set it to the text of the Checkbox, not the integer index in the loop
}
}
setListAdapter(new ArrayAdapter<String> (this, R.layout.my_list_layout, listItems));
The answer from Guardanis is technically correct if you were working with a regular Java class. The Android Activity class is NOT a regular Java class however.
Never try to access fields or methods in one Activity from any other app component. In some cases it might work but that approach breaks the Activity model and if you continue along that line, i.e., assuming an Activity is just a regular Java class, at some point your app will crash and burn.
The correct way to do what you are doing is to work out which checkboxes are checked using code in your MainActivity BEFORE you start MyListActivity. You'd then need to pass that information to MyListActivity either as Intent extras or by saving the data in SharedPreferences or using some other way of sharing the data.
I have a problem in my Android application. I have a Custom ListView Adapter, but when I launch the application the list does not show any item!
My Code :
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class AccountContents extends Activity {
private ListView ls1;
String username = fourshared.username;
String password = fourshared.password;
private AccountItem[] rootContents;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rootContents = fourshared.rootContents;
CArrayAdapter adapter = new CArrayAdapter(AccountContents.this, rootContents);
setContentView(R.layout.main);
ls1 = new ListView(AccountContents.this);
ls1.setAdapter(adapter);
}
}
Does your layout contain a list view? If so, you should look that up and set the adapter on that:
ls1 = (ListView)findViewById(R.id.your_list_view_id);
Better still, make your activity a ListActivity and Android will do a lot of the work for you.
You need to add the list to your activity. To do this, add this line:
setContentView(R.layout.main);
and remove: setContentView(R.layout.main);
This will add the list into view, but remove the existing views.
or you can define a list in your xml, and, as mentioned above, find it like this:
ls1 = (ListView)findViewById(R.id.your_list_view_id);
and in xml:
<ListView android:id="#+id/ls1" ......allOtherAtributesHere...... />
i am fairly new to android programming and usually find my answers to my problems by searching, but this one i just cant and its very confusing.
The code itself doesn't show any signs of problems, well i do get 2 java exception breakpoints but i dont know how to fix those as they are "unknown"but when i run it on the emulator it says the application has stopped unexpectedly force close. I try to debug it but i dont know how to do it that well. any way here are the codes btw the app is just a test all it to do is have buttons that take me to other "pages" and back. I would appreciate any help.
Main java file
package com.simbestia.original;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class original extends Activity implements View.OnClickListener {
Button button1, button2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (Button) findViewById(R.id.pagetwo);
button2 = (Button) findViewById(R.id.main);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.pagetwo:
setContentView(R.layout.pagetwo);
break;
case R.id.main:
setContentView(R.layout.main);
break;
}
}
}
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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<Button android:text="pagetwo" android:id="#+id/pagetwo" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
Well here is what i change the code to this one is just one button but it works with multiple and i made a class for every page...
package com.simbestia.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button mainmenu = (Button) findViewById(R.id.mainmenu);
mainmenu.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), mainmenu.class);
startActivityForResult(myIntent, 0);
}
});
}
}
Works how i wanted to so its all good i guess ty again
In the command line/terminal, use ./adb logcat to see, in real time, warnings, erros and such from your device, while you run your app. That should help you a lot.
Note: Don't forget to be in the right folder... <android-sdk-version>/platform-tools, that's where the ADB is.
You should learn to debug your own application. Starting with a break point right in the first line of your onCreate() method.
You can also take a look here: http://www.droidnova.com/debugging-in-android-using-eclipse,541.html
Another possibility is to add a log call in the first line of your onCreate() so you can see where the log of your app starts...
edit:
The way you want to switch the layout is wrong. Try layout switcher or start a new activity for your new layout. calling setContentView more than once is basically just wrong...
Some things to check: make sure your code source folder is the same as your package name (com.simbestia.original) ; make sure it builds (without errors) before you try and run it and make sure that your manifest file has its package attribute set to your package name (com.simbestia.original).